[Ethereum] web3.js import contract abi from .json file

abidappsjson-rpcweb3js

So I have a deployed contract with address0. I can easily interact with it using my index.html like so:

import contract_artifacts from '../../build/contracts/contract.json'
var contract0 = contract(contract_artifacts);

Then I can call it's functions like so:

contract0.deployed().then(function(something){});

But I also have another previously deployed contract with address1. The contract is the same as the contract with the address0.
I see only one way to work with the contract1:

var abiarray = [ here goes pretty big abi ];
contract1 = web3.eth.contract(abiarray).at(address1);

Is there another way to do it without including the whole abi of the contract? Because I already have it in contract_artifacts, I just don't know how to get it from there. Thank you.

Best Answer

I know the question is old, but I had some problems with this so I will share what helped me.

To import the ABI from a JSON file, you can use the following code (assuming you already have your web3 Object):

var fs = require('fs');
var jsonFile = "pathToYourJSONFile/project.json";
var parsed= JSON.parse(fs.readFileSync(jsonFile));
var abi = parsed.abi;

var YourContract= new web3.eth.Contract(abi, 0x12345678912345678912345678912345678912);

You can read more about it here: https://web3js.readthedocs.io/en/1.0/web3-eth-contract.html


Update 01/2020: Since Typescript 2.9, reading JSON Files is supported directly. So if you try to get the ABI or Bytecode from within a Typescript Project (Angular, React, ...) simply go to your tsconfig.json and set:

{
  "compilerOptions": {
    "resolveJsonModule": true,
    "esModuleInterop": true  
  }
}

You can then use import ContractName from 'path/to/contract/ContractName.json' to import your Contracts and get the Abi with ContractName.abi.

Cheers

Related Topic