Before starting this tutorial on interacting with a smart contract, you should have completed part 1 — Hello World Smart Contract (creating and deploying a smart contract). In part 3 we'll go over submitting our contract to Etherscan so anyone can understand how to interact with it!
Part 2: Interact with your Smart Contract
Now that we've successfully deployed a smart contract to the ropsten network, let's test out our web3 skills and interact with it!
Step 1: Create a interact.js file
This is the file where we'll write our interaction script. We'll be using the Ethers.js library that you previously installed in Part 1.
Step 2: Update your .env file
Step 3: Grab your contract ABI
Our contract ABI (Application Binary Interface) is the interface to interact with our smart contract. You can learn more about Contract ABIs here. Hardhat (and Truffle) automatically generates an ABI for us and saves it in the HelloWorld.json file.
If you want to see the ABI you can print it to your console:
Step 4: Create an instance of your contract
In order to interact with our contract we need to create an instance of it in our code. To do so with Ethers.js, we'll need to work with three concepts:
- Provider - this is a node provider that gives you read and write access to the blockchain.
- Signer - this represents an Ethereum account that has the ability to sign transactions.
- Contract - this is an Ethers.js object that represents a specific contract deployed on-chain.
We'll use the contract ABI from the previous step to create our instance of the contract:
You can read more about Providers, Signers, and Contracts in the Ethers.js documentation.
Step 5: Read the init message
Congrats! You've just successfully read smart contract data from the Ethereum blockchain, way to go!
Step 6: Update the message
Step 7: Read the new message
Now just run the script and you should be able to see the old message, the updating status, and the new message printed out to your terminal!
And that's it! You've now deployed AND interacted with an Ethereum smart contract. If you'd like to publish your contract to Etherscan so that anyone will know how to interact with it, check out part 3: submitting your smart contract to etherscan! 🎉
Once you complete this tutorial, let us know how your experience was or if you have any feedback by tagging us on Twitter @alchemyplatform!