Web3 by Example: Writing to a Smart Contract

In this example we’ll see how to write a smart contract function from JavaScript.

We will load a read-write contract that has a signer can send transactions.

In the SimpleStore contract, we have a function called setValue() that takes a single parameter value. We will set the value to web3byexample. This action sends a transaction to the network.

Wait for the transaction to be mined. If the status of receipt is 1, that means the transaction was mined successfully.

After the transaction is mined, we can read the value. See, the value is now web3byexample. That means that the contract has been updated.

write-contract.js

const { ethers } = require("ethers");
const fs = require("fs");
(async () => {
const abi = JSON.parse(fs.readFileSync("storage_sol_SimpleStorage.abi"));
const address = "0x4deA5308A17Bc20589802f3E2C23e79Ba044d497";
const provider = new ethers.providers.AlchemyProvider("goerli");
const privateKey = fs.readFileSync("privatekey").toString();
const wallet = new ethers.Wallet(privateKey, provider);
const instance_rw = new ethers.Contract(address, abi, wallet);
const tx = await instance_rw.setValue("web3byexample");
console.log("hash", tx.hash);
const receipt = await tx.wait();
console.log("status", receipt.status);
const value = await instance_rw.getValue();
console.log("value", value.toString());
})();

output

➜ node write-contract.js
hash 0x9c6810cf3f53f033ae5c242fac2bd4d8973816156c68c587734c365061301157
status 1
value web3byexample

Next example: Reading Smart Contract Bytecode