Web3 by Example: Loading a Smart Contract

As previous example shows, we have deployed a simple smart contract and got a contract address. Now, we will connect to this contract.

Creating a new instance of a Contract connects to an existing contract by specifying its address on the blockchain, its abi (used to populate the class' methods) and a providerOrSigner.

If a Provider is given, the contract has only read-only access, allows:

- Any constant function

- Querying Filters

- Populating Unsigned Transactions for non-constant methods

- Estimating Gas for non-constant (as an anonymous sender)

- Static Calling non-constant methods (as anonymous sender)

While a Signer(wallet) offers access to state manipulating methods.

- Everything from Read-Only (except as Signer, not anonymous)

- Sending transactions for non-constant functions


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 instance = new ethers.Contract(address, abi, provider);
console.log("address", instance.address);
const privateKey = fs.readFileSync("privatekey").toString();
const wallet = new ethers.Wallet(privateKey, provider);
const instance_rw = new ethers.Contract(address, abi, wallet);
console.log("signer ", instance_rw.signer.address);


➜ node load-contract.js
address 0x4deA5308A17Bc20589802f3E2C23e79Ba044d497
signer 0x67CF3bF40b2b3b3D68F6c361AEf81F8AEb2dB637

Next example: Querying a Smart Contract