Smart Contract Interaction Example

This is a short example on how Ether.js can be used to interact with Smart Contracts.

Here is a simple example of a smart contract to send or deposit ether to an address

pragma solidity ^0.8.0;

contract EtherDeposit {
    address payable public owner;
    
    constructor() {
        owner = payable(msg.sender);
    }
    
    function deposit(address payable recipient) public payable {
        require(msg.sender == owner, "Only the owner can deposit ether.");
        recipient.transfer(msg.value);
    }
}

In this contract, the owner can deposit ether to any recipient address by calling the deposit function and specifying the recipient address as a parameter. The require statement ensures that only the owner can deposit ether.

Here is an example of how the ABI can be used with Ether.js to execute the deposit function:

const { ethers } = require('ethers');

const abi = [/* insert ABI here */];
const contractAddress = '/* insert contract address here */';

const provider = new ethers.providers.JsonRpcProvider('/* insert provider URL here */');
const signer = provider.getSigner();
const contract = new ethers.Contract(contractAddress, abi, signer);

const recipientAddress = '/* insert recipient address here */';
const etherAmount = ethers.utils.parseEther('1'); // 1 ether

const depositTx = await contract.deposit(recipientAddress, { value: etherAmount });
await depositTx.wait();

In this example, we first create an Ether.js provider and signer to connect to an Ethereum node. We then create an instance of the contract using the contract's address and ABI. Finally, we call the deposit function on the contract instance, passing in the recipient address and ether amount as parameters. The ethers.utils.parseEther function is used to convert the ether amount to wei. We then wait for the transaction to be mined using the wait function.

ABI Example:

[
  { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" },
  {
    "inputs": [
      {
        "internalType": "address payable",
        "name": "recipient",
        "type": "address"
      }
    ],
    "name": "deposit",
    "outputs": [],
    "stateMutability": "payable",
    "type": "function"
  },
  {
    "inputs": [],
    "name": "owner",
    "outputs": [
      {
        "internalType": "address payable",
        "name": "",
        "type": "address"
      }
    ],
    "stateMutability": "view",
    "type": "function"
  }
]

Last updated