MetaMask Transactions – How to Send Using Web3.js

dapp-developmentmetamasktransactionsweb3js

Metamasks injected web3 gives an error when using web3.eth.sendTransaction()

web3.eth.sendTransaction({from:web3.eth.accounts[0], to:'', data: // hash to interact with contraact, gas:85000});

enter image description here

What would be a way to use Metamask to have a website prompt a user to sign a transaction ?

Best Answer

You're missing the last argument to sendTransaction, the callback function(error, transactionHash) { ... }

The MetaMask FAQ states:

All Async - Think of MetaMask as a light client

The user does not have the full blockchain on their machine and so data lookups can be a little slow. For this reason, we are unable to support most synchronous methods. The exception to this is:

eth_accounts (web3.eth.accounts)

eth_coinbase (web3.eth.coinbase)

Usually a method call can be made async by simply adding a callback as the last argument to a synchronous method.

See ethereum wiki on "using callbacks"

Not only is this a technical limitation, it's also a user experience issue. When you use synchronous calls, you block the user's interface, and so it's a generally bad practice anyways. Think of this API restriction as a gift to your users.

So all calls to web3.js should have a callback as their last argument: the only calls where that's not needed are for web3.eth.accounts and web3.eth.coinbase. The generic form of the callback is function(error, result).