1

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

2 Answers 2

1

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.

1
  • 1
    Thanks, can you show me how to connect to Rinkeby testnet with web3modal using Infura?
    – нεx
    Nov 17, 2021 at 10:13
0

@chunter 's answer is very good, for additional info, I recommand infura's official doc: https://docs.infura.io/infura/tutorials/ethereum/call-a-contract

enter image description here

here is an code snippet for example ( for complete code ,please refer to the official doc ):

const Web3 = require('web3')

const fs = require('fs')

const { abi } = JSON.parse(fs.readFileSync('Demo.json'))

async function main(){
  const network = process.env.ETHEREUM_NETWORK

  // step1. init the web3 instance
  const web3 = new Web3(
    new Web3.providers.HttpProvider(
      `https://rinkeby.infura.io/v3/<YOUR INFURA PROJECT ID>`
    )
  )

  // step2. create signer
  const signer = web3.eth.accounts.privateKeyToAccount(  process.env.SIGNER_PRIVATE_KEY)
  web3.eth.accounts.wallet.add(signer)

  // step3. create contract, abi 
  const contract = new web3.eth.Contract( abi, process.env.DEMO_CONTRACT)

  // step4. create tx , here we used the signature
  const tx = contract.methods.echo(" Hi hihihi ")
  const receipt = await tx
    .send({ from: signer.address, gas: await tx.estimateGas() })
    .once("transactionHash" , (txHash) => {
      console.info("mining transaction...", txHash)
    })

  console.info("mined in block: ", receipt.blockNumber)
}

require('dotenv').config()
main()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.