2

I am trying to build a frontend with NextJS/React/Web3js and I'm running into one of my last hurdles. Any functions I call to my contract that requires signing doesn't work.

I suspect it's because I have two web3 objects, one initialized via Metamask and another using an Infura RPC.

Initially I had a file to initialize the Contract object in:

import Web3 from "web3"
import buildData from '../../build/contracts/Contract.json'


const provider = new Web3.providers.HttpProvider(
    process.env.NEXT_PUBLIC_RINKEBY_RPC_URL
)
const web3 = new Web3(provider)

const bContract = new web3.eth.Contract(buildData.abi,"0x6841121b8CC025D2558eBC1a7144B17B1F25159B")

export default bContract

And in my main file I had the function that initialized another web3 object with Meta mask here,

    const connectWalletHandler = async () => {
        // Check if Metamask is available
        if (typeof window !== "undefined" && typeof window.ethereum !== "undefined") {
            try {
                //request wallet connect
                await window.ethereum.request({ method: "eth_requestAccounts" })

                //set web3 instance
                web3 = new Web3(window.ethereum)
                setWeb3(web3)

                //get list of accounts
                const accounts = await web3.eth.getAccounts()
                setUserAddress(accounts[0])

            } catch (err) {
                setError(err.message)
            }
   
        } else {
            // meta not installed
            console.log("Please install Metamask")
        }
    }

But when I call functions to send transactions, I get a "method is not defined" error.

Example:

try {
             await contract.methods.placeBet(id).send({
                from: account,
                value: web3.utils.toWei(userBet,'ether')
            })
        } catch (err) {
            alert(err.message)
        }

Returned error: The method eth_sendTransaction does not exist/is not available

Yet if I use a call function to read some variable on the contract, it works swimmingly. What am I doing wrong?

1 Answer 1

1

I figured out the issue. It was indeed having 2 web3 objects created, one with Metamask, the other through the Web3 package. I couldn't sign transactions with the latter as expected as I didn't have the private key. So I ended up passing the web3 object created by Metamask to create the local Contract object in the first code block I had above.

Thank you lads for reading this, just writing out your thoughts is quite helpful for debugging.

Your Answer

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

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