Published on

Easily Execute Contract Methods on a Deployed Contract with Truffle

Authors

When working with a dApp once you have a contract deployed to an environment you may want to execute some of the methods on that contract.

You can use web3 to do this but it is quite tricky as to call the contract using JavaScript you need to run:

const contract = web3.eth.contract(abi).at(contractAddress)
  • abi: This is fairly large so difficult to just copy paste.
  • contractAddress: This can be seen in the output from running truffle migrate.

Doing this would normally not be an issue as you would build calls to this contract method in your dApp. But if you wanted to quickly try hit a method on the deployed contract having to update your dApp each time can be a pain.

What I found works well is using truffle to help abstract these complicated bits away. In my truffle project, I created a new folder called scripts, this folder can be named whatever you want I just called it scripts as that is where I would put my scripts. My project structure looks as follows:

-> <truffleProjectRoot>
 -> build
    -> contracts
        -> YourContract.json
 -> contracts
    -> YourContract.sol
 -> migrations
 -> package.json
 -> package-lock.json
 -> scripts
    -> myScriptToRun.js
 -> test
 -> truffle-config.js

Running truffle compile generates the build directory above which contains information about your contracts including the abi. To use it create a JavaScript file under scripts (in my case I called this myScriptToRun.js) which would look like as follows:

const YourContract = artifacts.require('./YourContract')
//change the below to be the exact accounts you want
const [account0, account1, account2] = web3.eth.accounts

//you have to set the below to the account you are using otherwise you get the Invalid Address error. See https://ethereum.stackexchange.com/questions/19524/invalid-address-error-when-interacting-with-a-smart-contract-with-metamask#answer-32026
// change account0 to the account that will be paying the eth to execute the contract methods in your script (you need to have access to this account to approve the transactions in metamask)
web3.eth.defaultAccount = account0

const contract = web3.eth.contract(YourContract.abi).at(YourContract.address)

//If this has parameters then use: contract.methodYouWantToCall(param1, param2);
contract.methodYouWantToCall()

Finally, we use truffle to call this by running the below in the scripts directory:

truffle exec myScriptToRun.js --network development
  • --network development: In my truffle-config.js I have a network called development.
    • Simply change this to any other network you have there to point to that instead

Using truffle I do not have to worry at all about what the exact abi is and I can simply write a script that can be executed against networks I have configured in my truffle-config.js.