1

I'm using ethers.js to interact with a contract. When I call a method of my contract, i.e const txn = await someContract.someMethod(...data).

It returns a signed transaction and also sends it to the chain which I'd like to avoid cause I want to replay it on a local fork. I tried populateTransaction and signTransaction but there'll be some missing information if you do it this way.

1 Answer 1

1

You can create a transaction (without sending it) like this using web3js:

    const web3Provider = new Web3(
      new Web3.providers.Web3Provider(
        ENDPOINT
      )
    )
    web3Provider.eth.accounts.wallet.add(WALLET_KEY)

    const contract = new web3Provider.eth.Contract(
      ABI,
      CONTRACT_ADDRESS
    )


    const trx = contract.methods.METHOD_NAME(...params)

    const gas = await trx.estimateGas({ from: WALLET_ADDRESS })
    console.log('gas :>> ', gas)
    const gasPrice = await provider.eth.getGasPrice()
    console.log('gasPrice :>> ', gasPrice)
    const data = trx.encodeABI()
    console.log('data :>> ', data)
    const nonce = await provider.eth.getTransactionCount(WALLET_ADDRESS)

    console.log('nonce :>> ', nonce)

    const trxData = {
      from: WALLET_ADDRESS,
      to: CONTRACT_ADDRESS,
      data,
      gas,
      gasPrice,
      nonce,
    }

    console.log('Transaction ready to be sent')
    // actually send the transaction now 👇
    const receipt = await provider.eth.sendTransaction(trxData)
    console.log(`Transaction sent, hash is ${receipt.transactionHash}`)

Just adapt the wallet address, contract, method and params

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.