- Published on
How to use Truffle Migrations to Modify the State of an Already Deployed Contract
- Authors
- Name
- Yair Mark
- @yairmark
Truffle makes it super easy to migrate new contracts.
One thing that was not clear to me was: how do I call methods on an already deployed contract?
It turns out it is actually quite easy. For example, to call a method that changes the state of an item on an existing contract would look something like:
const AwesomeContract = artifacts.require("./path/to/Awesome.sol");
require("dotenv-flow").config();
const awesomeContractAddress = process.env.AWESOME_CONTRACT_ADDRESS;
console.log(`awesomeContractAddress: [${awesomeContractAddress}]`);
module.exports = async deployer => {
const awesomeContractInstance = await AwesomeContract.at(awesomeContractAddress);
const someMethodTx = await awesomeContractInstance.someMethod(
"FOO"
);
console.log("Events Fired During SomeMethof:");
console.log("===========================\n");
console.log(someMethodTx.logs);
console.log("===========================\n");
In the above we can see that:
- We made a new migration
.js
file and put it in themigrations
folder. - We do not use the deployer: we are not deploying any new contract.
- We use
AwesomeContract.at
to refer to the contract's existing address. - We store the transaction resulting from the contract method execution and
console.log
its logs so we can see what events were fired. - Add/remove
console.log
s as you see fit, I did this for debuggability when this migration script runs.
I use dotenv-flow which is completely optional. This allows me to have .env
files for different environments. For example, locally I have .env.local
. dotenv-flow
looks at the NODE_ENV
environment variable to determine which .env
file to use. To make it use my .env.local
one I run truffle migrate as follows:
NODE_ENV=local truffle migrate