# Contract Interactions (ERC Contracts)

<figure><img src="https://3894187460-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FWkWLaQ69AQX6Dq1b8smA%2Fuploads%2F7PVwNmOnwNO9JVOMzBjP%2FScreenshot%20from%202025-05-06%2003-26-45.png?alt=media&#x26;token=5e4643c5-a316-49d5-9f56-7fc169553640" alt=""><figcaption></figcaption></figure>

[![npm version](https://img.shields.io/npm/v/multichain-wallet-connector)](https://www.npmjs.com/package/multichain-wallet-connector)[![License: GPL-3.0](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://opensource.org/licenses/GPL-3.0)[![GitHub stars](https://img.shields.io/github/stars/Nworah-Gabriel/multichain-wallet-connector)](https://github.com/Nworah-Gabriel/multichain-wallet-connector/stargazers)

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:

```bash
npm install multichain-wallet-connector
```

Or if you use Yarn:

```bash
yarn add multichain-wallet-connector
```

## 📘 Example: Reading and Writing Values

### 🧠 Contract ABI

```javascript
[
  {
    "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

```javascript
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:

```typescript
declare module 'multichain-wallet-connector';
```

## 📌 Code Breakdown

#### 🔹 `contract.read(methodName, args[])`

Reads a `view` function from the contract.

```javascript
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.

```javascript
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.

```javascript
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

```html
<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

```html
<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

<table><thead><tr><th width="126">Operation</th><th width="479">Method</th><th>Signature Required</th><th>Notes</th></tr></thead><tbody><tr><td>Read</td><td><pre class="language-javascript"><code class="lang-javascript">read(
    '&#x3C;function name>',
    ['&#x3C;function_parameters_1>', '&#x3C;function_parameters_2>']
    )
</code></pre></td><td>❌</td><td>Executes a view or pure  function declared in the contract.</td></tr><tr><td>Estimate Gas</td><td><pre class="language-javascript"><code class="lang-javascript">estimateGas('&#x3C;function_name>')
</code></pre></td><td>❌</td><td>Simulates gas use without sending</td></tr><tr><td>Write</td><td><pre class="language-javascript"><code class="lang-javascript">write(
<strong>    '&#x3C;function name>',
</strong><strong>    ['&#x3C;function_parameters_1>', '&#x3C;function_parameters_2>'],
</strong>    {
        from: &#x3C;account_provider>,
        gasLimit: "&#x3C;gas_limit>",
    }
)
</code></pre></td><td>✅</td><td>Executes a function that changes the state of a contract and returns tx hash</td></tr></tbody></table>

### 🚀 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.
