manniru
2/23/2018 - 7:43 AM

Send a signed transaction to a contract in Ethereum

Send a signed transaction to a contract in Ethereum

// Sending a signed transaction to a contract
// using the contract's owner's private key
// "web3": "^1.0.0-beta.30"
// "ethereumjs-tx": "^1.3.3",
// createItem function takes (name, price) as args

const web3 = new Web3(new Web3.providers.HttpProvider(INFURA_URL))
const myContract = new web3.eth.Contract(MY_ABI, MY_CONRACT_ADDRESS)
const ownerAccount = ""
const ownerPrivateKey = ""

web3.eth.getTransactionCount(ownerAccount, (err, nonce) => {
  if (err) {
    console.log(err)
    callback(err)
    return
  }

  const data = myContract.methods.createItem(name, price).encodeABI()
  const tx = new EthereumTx({
    nonce: nonce,
    gasPrice: web3.utils.toHex(web3.utils.toWei('20', 'gwei')),
    gasLimit: 100000,
    to: MY_CONRACT_ADDRESS,
    value: 0,
    data: data,
  })

  tx.sign(new Buffer(ownerPrivateKey, 'hex'))

  const raw = '0x' + tx.serialize().toString('hex')

  web3.eth.sendSignedTransaction(raw, (err, transactionHash) => {
    if (err) {
      console.log(err)
      callback()
      return
    }

    callback(transactionHash)
  })
})