9

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.

12

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

| improve this answer | |
  • 3
    I'm surprised this is one of the only few answers to this problem online.... most of the articles I read is asking you to type the ABI manually in js, which is really messy. – Richard Fu Jul 19 '18 at 7:10
  • 1
    I'm getting an error: Error: Cannot find module '../../node_modules/file-system' - even though I absolutely have file system installed - both globally and locally in my project's folder... Strangely the error says its on line 210 of web3.min.js - which I wouldn't think is related to any of this. Thoughts? – Mark55 Feb 19 '19 at 15:59
0

I used the require function to import the JSON file.

import Web3 from 'web3';
const web3 = new Web3(window.web3.currentProvider);
const { abi } = require('./smart_contract_after_compilation_step.json');
var smart_contract_interface = new web3.eth.Contract(abi, '0x5E54780072f1998FB85c3203D9697ef9E3F82DF0')
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.