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() and write() methods

  • Built-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[])

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[])

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)

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 address

    • gasLimit: (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>

For production readiness, always wrap async calls with try/catch:

πŸ“š Summary

Operation
Method
Signature Required
Notes

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