2

I have been researching this whole day, but I have a web3 instance, (the Web3 is version 1.0.0)

const web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/<myKey>'));

Later I used it to sign a transaction (which is a call to a contract). I have

const contract = new web3.eth.Contract(abiArray, contractAddr);
var func = contract.methods.myMethod('foo', 'bar')

var encodedFunc = func.encodeABI();

var tx = {
    from: ownerWallet,
    to: contractAddr,
    gas: web3.utils.toHex(1000000), //1m, also tried string '1000000'
    gasPrice: web3.utils.toHex(20000000000), //20gwei, also tried string '20000000000'
    data: encodedFunc
}

//might just be unnecessary three lines
const account = web3.eth.accounts.privateKeyToAccount(ownerPrivate)
console.log(account)
web3.eth.getBalance(ownerWallet).then(console.log)

const signed = await web3.eth.accounts.signTransaction(tx, ownerPrivate)
var trans = web3.eth.sendSignedTransaction(signed.rawTransaction)

Error is like,

Error: Returned error: insufficient funds for gas * price + value

Everything seems quite normal. What could be the issue?

2
  • gas and gasPrice definitely have to be wrapped in web3.toHex(), like gasPrice: web3.toHex(20000000000)
    – n1cK
    Commented Apr 14, 2018 at 9:57
  • @NikitaFuchs, I tried. Still the same error. I modified my question to toHex too. Can there be other reasons?
    – Bigman
    Commented Apr 14, 2018 at 16:56

1 Answer 1

4

So... I figured out. The reason is Web3 takes the private key in 0xa0b1c2... format. I used to use ethereumjs-tx package, which takes a private key in const privateKey = new Buffer('a0b1c2...') without 0x

I changed to const privateKey = '0xa0b1c2...' and it worked.

Hope this helps whoever visits this page.

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.