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
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!
That is due to the mining process! If you are curious about how to track transactions while they are being mined, visit the Alchemy mempool to see the status of your transaction (whether it's pending, mined, or got dropped by the network). If your transaction got dropped, it's also helpful to check Ropsten Etherscan and search for your transaction hash.
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! 🎉