💻 Interacting with a Smart Contract

How to interact with a deployed Ethereum smart contract by sending a transaction, for beginners. Part 2 of a series.

Elan Halpern
Alchemy

--

Before starting this tutorial on interacting with a smart contract, you should have completed Part 1: Creating and Deploying a Smart Contract. In Part 3: Submitting Your Smart Contract to Etherscan, we’ll go over submitting our contract to Etherscan so anyone can understand how to interact with it!

Now that you’ve successfully deployed a smart contract to the Ropsten network, let’s test out our web3 skills and interact with it!

UPDATE: We now have a video tutorial covering this article by our rockstar developer ALBERT!

If you have questions at any point feel free to reach out in the Alchemy Discord!

Still haven’t written and deployed your own smart contract? Check out this tutorial. Don’t have an Alchemy account yet? Sign up for free.

Step 1: Install web3 library‌

Web3.js is a library used to make requests to the Ethereum chain much easier. There are a handful of web3 providers you can choose from, however in this tutorial we’ll be using Alchemy Web3, which is an enhanced web3 library that offers automatic retries and robust WebSocket support.‌

In your project home directory run:

npm install @alch/alchemy-web3‌

Step 2: Create a contract-interact.js file‌

Inside the scripts/folder for your Hello World project, create a file named contract-interact.js and add the following lines of code:

require('dotenv').config();
const API_URL = process.env.API_URL;
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3 = createAlchemyWeb3(API_URL);

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 automatically generates an ABI for us when we deploy our smart contract, and saves it in the HelloWorld.json file. In order to use this we’ll need to parse out the contents by adding the following lines of code to our contract-interact.js file:

require('dotenv').config();
const API_URL = process.env.API_URL;
const { createAlchemyWeb3 } = require("@alch/alchemy-web3");
const web3 = createAlchemyWeb3(API_URL);
const contract = require("../artifacts/contracts/HelloWorld.sol/HelloWorld.json");

If you want to see the ABI you can print it to your console by adding this line to the bottom of your contract-interact.js file:

console.log(JSON.stringify(contract.abi));‌

To run contract-interact.js and see your ABI printed to the console navigate to your terminal and run:

node scripts/contract-interact.js

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, we’ll need our contract address which we can get from the deployment or from Etherscan by looking up the address you used to deploy the contract. In the above example our contract address is 0x70c86b8d660eBd0adef24E9ACcb389BFb6611B2b .

‌Next we will use the web3 contract method to create our contract using the ABI and address:

const contractAddress = "0x70c86b8d660eBd0adef24E9ACcb389BFb6611B2b";
const helloWorldContract = new web3.eth.Contract(contract.abi, contractAddress);

Step 5: Read the init message

Remember when we deployed our contract with the initMessage = "Hello world!"? We are now going to read that message stored in our smart contract and print it to the console.

In JavaScript we use asynchronous functions to interact with networks. Check out this article to learn more about this.‌

Use the code below to call the message function in our smart contract and read the init message:

async function main() {
const message = await helloWorldContract.methods.message().call();
console.log("The message is: " + message);
}
main();‌

After running the file using node scripts/contract-interact.js in the terminal we should see this response:

The message is: Hello world!

Congrats! You’ve just successfully read smart contract data from the Ethereum blockchain, way to go! 🎉

Step 6: Update the message‌

Now instead of just reading the message, we’ll update the messaged saved in our smart contract using the update function. ‌‌

In order to do so we’ll need to create a transaction, sign it, and send it inside another async function that we’ll call updateMessage(newMessage). This can be pretty confusing when you first get started so we'll split it up into multiple steps.

Step 7: Update the .env file‌

Currently, our .env file contains our private key and our Alchemy API key. In this step, we’ll add our public Ethereum account address which we’ll use to get the account nonce (will explain what this means later).

Your public key is the hex address at the top of your Metamask wallet, simply click on it to copy it:

Metamask public key

Your .env should now look like this:

API_URL = "https://eth-ropsten.alchemyapi.io/v2/your-api-key"
PRIVATE_KEY = "your-metamask-private-key"
PUBLIC_KEY = "your-metamask-public-key"

Step 8: Create the transaction‌

Define updateMessage(newMessage) and create our transaction.

  1. First grab your PUBLIC_KEY and PRIVATE_KEY from the .env file.
  2. Next, we’ll need to grab the account nonce. The nonce specification is used to keep track of the number of transactions sent from your address. We need this for security purposes and to prevent replay attacks. To get the number of transactions sent from your address we use getTransactionCount.
  3. Next, we’ll use eth_estimateGas to figure out the right amount of gas to include in order to complete our transaction. This avoids the risk of a failed transaction due to insufficient gas.
  4. Finally we’ll create our transaction with the following info:‌
  • 'from': PUBLIC_KEY : The origin of our transaction is our public address
  • 'to': contractAddress : The contract we wish to interact with and send the transaction
  • 'nonce': nonce : The account nonce with the number of transactions send from our address
  • 'gas': estimatedGas : The estimated gas needed to complete the transaction
  • 'data': helloWorldContract.methods.update("<new message>").encodeABI() : The computation we wish to perform in this transaction (updating the contract message)‌

Your contract-interact.js file should look like this now:

contract-interact.js

Step 9: Sign the transaction

Now that we’ve created our transaction, we need to sign it in order to send it off. Here is where we’ll use our private key.

web3.eth.sendSignedTransaction will give us the transaction hash, which we can use to make sure our transaction was mined and didn't get dropped by the network.

contract-interact.js

Step 10: Call updateMessage and run contract-interact.js

Finally, we can call updateMessage with our new message by making an await call in main for updateMessage with your newMessage.

Then run node scripts/contract-interact.js from your command line.

contract-interact.js

You should see a response that looks like:

The message is: Hello world!The hash of your transaction is: 0xd6b89d1e31d53b732afc461e04ed0cebc451cfe6e8470519fe06eb4295f5b504Check Alchemy's Mempool to view the status of your transaction!‌

Next visit your 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.

‌Once your transaction gets mined, comment out the await updateMessage("Hello Drupe!"); line in main() and re-run node scripts/contract-interact.js to print out the new message.‌

Your main() should look like (everything else in your contract-interact.js should stay the same):

async function main() {
const message = await helloWorldContract.methods.message().call();
console.log("The message is: " + message);
// await updateMessage("Hello Drupe!");
}‌

After running node scripts/contract-interact.js you should now see the new message printed to your console:

The message is: Hello Drupe!‌

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, stay tuned for part 3: submitted your smart contract to Etherscan! 🎉

Alchemy provides the leading blockchain development platform powering millions of users for 99% of countries worldwide. Our mission is to provide developers with the fundamental building blocks they need to create the future of technology, and lower the barrier to entry for developers to build blockchain applications. Alchemy currently powers 70% of the top Ethereum applications and over $15 billion in on-chain transactions, and have been featured on TechCrunch, Wired, Bloomberg and numerous other media outlets. The Alchemy team draws from decades of deep expertise in massively scalable infrastructure, AI, and blockchain from leadership roles at technology pioneers like Google, Microsoft, Facebook, Stanford, and MIT.

Never want to miss an update? Subscribe to our newsletter here! Be sure to also follow our Twitter and join our Discord.

--

--

Elan Halpern
Alchemy

Elan Halpern works on developer experience at Alchemy, the world's leading blockchain developer platform. She received her BS in Computer Science at Stanford.