With truffle-contract, all you needed to do to get the contract instance was something like this:
const getContract = require('truffle-contract')
const contractJSON = require('./MyContract.json')
const contract = getContract(contractJSON)
contract.setProvider(web3.currentProvider)
const instance = await contract.deployed()
return instance
- Please note that the
MyContract.json
file is the build artifact from Truffle.
But since the instance created by truffle-contract returns promises instead of the PromiEvent which came with version 1.0 of Web3, I decided that I wanted to use regular v1.0 Web3 in order to get the contract instance. In other words, I no longer wanted to rely on truffle-contract.
Unfortunately, I am not that familiar with the contract API in the new 1.0 Web3. This is my attempt:
const contract = new web3.eth.Contract(contractJSON.abi)
contract.methods.get().call()
The first line is okay, but the second line throws the following error:
This contract object doesn't have address set yet, please set an address first.
I see that this makes sense because the documentation seems to state that you can set an address so that it will know where to find the deployed instance.
Does this mean that I'd have to go to my Truffle Console (aka testrpc) to find the contract address and copy and paste this in every time? I sure hope not, because with truffle-contract, all I needed to do was just include the JSON file and it figured it out for me.
How am I supposed to get this address and pass it in?
Best Answer
I couldn't find where the address was stored because the JSON file I took was an out-dated version. It was one that was generated before I migrated on Truffle. It turns out that the JSON file is updated every time Truffle runs its migrations. And with that, it will add the address of the deployed contract instance.
I had to dig deep into their docs to find it here: https://github.com/trufflesuite/truffle/tree/develop/packages/truffle-contract-schema#networks
From there, it was easy to find the pre-deployed address. The final code looks something like this: