INFURA / infura

Official Public Repository for INFURA
https://infura.io
381 stars 62 forks source link

Cannot write with Infura and Web3 #199

Closed nphsu closed 4 years ago

nphsu commented 4 years ago

Problem

Cannot write values to the contract even though it successfully worked a few days ago on the same code.

const web3 = new Web3(new Web3.providers.HttpProvider(`https://rinkeby.infura.io/v3/${INFURA_KEY}`))
web3.eth.accounts.wallet.add(PRIV_KEY)

const txParam = {
    from: sender,
    gas: gas,
    gasPrice: gasPrice
}

const contract = new web3.eth.Contract(ABI, CONTRACT_ADDRESS)
contract.methods
        .initialize(...args)
        .send(txParam)
        .on('receipt', receipt => console.log(receipt.transactionHash))
        .catch(e => { if (e) throw e })

Error Message

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

Versions

solc v0.5.16 web3 v1.2.6

egalano commented 4 years ago

Hi there. The code you are using is not calling the right method. You need to be using eth_sendSignedTransaction and handling the transaction signing on your end. Using the code as you've written it would require Infura to hold your private keys which is not something we support since it compromises your key's security. Take a look at the tutorial here: https://medium.com/coinmonks/signing-and-making-transactions-on-ethereum-using-web3-js-1b5663207d63

nphsu commented 4 years ago

@egalano Thank you for your kind reply. The tutorial makes sense and would help us to implement. However, it was successfully working for several months. I would appreciate it if you know there are any breaking changes recently.

egalano commented 4 years ago

Hmm. I don't know why it would ever have been working unless there is something in web3js that was locally signing the transaction for you. According to the docs: https://web3js.readthedocs.io/en/v1.2.0/web3-eth.html#id62 there is a note that says:

The from property can also be an address or index from the web3.eth.accounts.wallet. It will then sign locally using the private key of that account, and send the transaction via web3.eth.sendSignedTransaction().

So if I'm understanding that correctly, if you supply a from address that exists in your local web3 account wallet, it should sign and send the transaction correctly to Infura. Has anything in that part of your code changed recently or have you changed the version of web3js you are using?

nphsu commented 4 years ago

I found the reason. As MetaMask exports the private key without 0x, it causes the error. I raised a new PR on the web3.js repository. https://github.com/ethereum/web3.js/issues/3458

egalano commented 4 years ago

Thanks for the update. I'll close this issue then. Glad you were able to find the root cause.