Contract Interactions (ERC Contracts)

Smart contract interaction is one of the most fundamental building blocks in any decentralized application (dApp). With this library, developers can seamlessly interact with deployed Ethereum contracts β whether calling read-only functions (view/pure) or executing state-changing transactions. This library simplifies smart contract communication by wrapping common read and write operations with a streamlined interface. This includes
Abstracted contract creation via
createContract()
Unified
read()
andwrite()
methodsBuilt-in support for gas estimation
Optional transaction configuration (e.g.,
gasLimit
,from
)
This guide explores how to interact with smart contracts β without directly using ethers.js
β using a clean and minimal library.
Creates a smart contract instance scoped to the provided provider and ABI. The returned contract object supports:
.read(methodName, args)
.write(methodName, args, txOptions)
.estimateGas(methodName, args)
π§± 1. Framework Usage (ES6/ npm modules)
π Installation
If you havenβt already:
npm install multichain-wallet-connector
Or if you use Yarn:
yarn add multichain-wallet-connector
π Example: Reading and Writing Values
π§ Contract ABI
[
{
"inputs": [{ "internalType": "int256", "name": "_value", "type": "int256" }],
"name": "setValue",
"outputs": [],
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"name": "get",
"outputs": [{ "internalType": "int256", "name": "", "type": "int256" }],
"stateMutability": "view",
"type": "function"
}
]
β
Full Interaction Script
async function contractInteraction() {
try {
const Abi = [
{
inputs: [{ internalType: "int256", name: "_value", type: "int256" }],
name: "setValue",
outputs: [],
stateMutability: "nonpayable",
type: "function",
},
{
inputs: [],
name: "get",
outputs: [{ internalType: "int256", name: "", type: "int256" }],
stateMutability: "view",
type: "function",
},
];
const contractAddress = '0x1A9CD84b055255E14848A691828B54Ef477a818d';
const contract = WalletConnector.createContract(PROVIDER, contractAddress, Abi);
// π Read operation
const value = await contract.read('get', []);
console.log('Stored Value:', value);
// β‘ Estimate gas
const estimatedGas = await contract.estimateGas('get', []);
console.log('Estimated Gas (get):', estimatedGas);
// βοΈ Write operation
const txHash = await contract.write(
'setValue',
[5000000],
{
from: ACCOUNT,
gasLimit: '300000',
}
);
console.log('Transaction Hash:', txHash);
} catch (error) {
console.error('Contract interaction failed:', error);
}
}
For typescript users, declare as a module in your types file:
declare module 'multichain-wallet-connector';
π Code Breakdown
πΉ contract.read(methodName, args[])
contract.read(methodName, args[])
Reads a view
function from the contract.
const value = await contract.read('get', []);
Returns: Resolved value from the contract.
Use Case: Free, read-only queries.
πΈcontract.estimateGas(methodName, args[])
contract.estimateGas(methodName, args[])
Estimates the gas usage for a function call before executing it.
const gasEstimate = await contract.estimateGas('get', []);
Returns: Estimated gas (number).
Use Case: Pre-transaction cost estimation.
β΄οΈ contract.write(methodName, args[], options)
contract.write(methodName, args[], options)
Sends a transaction to the contract.
const txHash = await contract.write('setValue', [123456], {
from: ACCOUNT,
gasLimit: '300000',
});
Returns: Transaction hash on submission.
Requires: Wallet connection and user approval.
Options:
from
: Wallet addressgasLimit
: (optional) Maximum gas to spend[123456] :
123456
the parameter the function is accepting, which would be used to change the state of the contract.
π 2. CommonJS via CDN (HTML/Vanilla JS)
β
Embed Script
<script src="https://cdn.jsdelivr.net/gh/Nworah-Gabriel/multichain-wallet-connector@v1.0.3/dist/connector.umd.min.js"></script>
Ensure this is added before your custom scripts in the HTML body.
π Implementation on VanillaJs via CDN
<script>
let provider, account;
async function connect() {
const res = await WalletConnector.connectWallet({ chainId: 1 }); // Mainnet
provider = res.provider;
account = res.account;
}
async function runInteraction() {
const Abi = [...]; // same ABI as above
const contract = WalletConnector.createContract(
PROVIDER,
"0x1A9CD84b055255E14848A691828B54Ef477a818d",//Contract Address
Abi
);
const value = await contract.read("get", []);
console.log("Read:", value);
const tx = await contract.write("setValue", [1000], {
from: ACCOUNT,
gasLimit: "300000",
});
console.log("TX:", tx);
}
</script>
βοΈ Error Handling (Recommended)
For production readiness, always wrap async calls with try/catch
:
π Summary
Read
read(
'<function name>',
['<function_parameters_1>', '<function_parameters_2>']
)
β
Executes a view or pure function declared in the contract.
Estimate Gas
estimateGas('<function_name>')
β
Simulates gas use without sending
Write
write(
'<function name>',
['<function_parameters_1>', '<function_parameters_2>'],
{
from: <account_provider>,
gasLimit: "<gas_limit>",
}
)
β
Executes a function that changes the state of a contract and returns tx hash
π Conclusion
This library contract abstraction provides a zero-boilerplate way to interact with Ethereum contracts. With unified read/write calls, gas estimation, and support for CDN usage, it empowers frontend developers to build dApps without the complexity of manually managing web3 libraries.
Last updated