Solidity – How to Call a Smart Contract Function Using Web3 and Infura

infurasolidityweb3js

Imagine having the below code:

pragma solidity ^0.8.9;

contract Message {
    address myMessage;

    function setMessage() public {
        myMessage = msg.sender;
    }
}

Now i know that infura does not support eth_sendTransaction. and i know how to sign the transaction and send it using web3 library.

However my only confusion, how to make the contract call in the transaction itself? i dont want to send any value just make a contract call.

please advise

Best Answer

Using ethers, you need to create the contract using the contracts address + abi and a signer.

import <Your contract deployment address>; 
import <Your contract abi>; 
const connection = await new Web3Modal().connect(); 
const provider = new ethers.providers.Web3Provider(connection); 
const signer = provider.getSigner(); 
const contract = new Contract(contractAddress, contractAbi, signer);

You can then call the contract via :

 await contract.setMessage();

Note I used https://github.com/web3modal/web3modal here, but another way to get a signer can be found in ethers documentation.

Related Topic