[Ethereum] signing transactions with web3.js

go-ethereumsolidityweb3-providersweb3js

Im trying to create a node.js based dapp that interacts with ropsten ethereum network via infura node.here we need sign transaction with web3.js. but the code showing error from the contract side. please let me know what seems to be the problem

let myData=contract.methods.greet("hello blockchain devs").encodeABI()
                            ^

TypeError: Cannot read property 'greet' of undefined

here is my code:

var Tx     = require('ethereumjs-tx')
const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/<API KEY>')

const account1 = '<account address>' // Your account address 1

const privateKey1 = Buffer.from('<Private Key>', 'hex')
const abi=[{"constant":false,"inputs":[{"name":"_greeting","type":"string"}],"name":"greet","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"getGreeting","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}];
const contract_Address="0xcbe74e21b070a979b9d6426b11e876d4cb618daf";
const contract =web3.eth.contract(abi, contract_Address)
let myData=contract.methods.greet("hello blockchain devs").encodeABI()
web3.eth.getTransactionCount(account1, (err, txCount) => {
  // Build the transaction
  const txObject = {
    nonce:    web3.utils.toHex(txCount),
    to:       contract_Address,
    value:    web3.utils.toHex(web3.utils.toWei('0.1', 'ether')),
    gasLimit: web3.utils.toHex(21000),
    gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
    data: myData
  }

  // Sign the transaction
  const tx = new Tx(txObject)
  tx.sign(privateKey1)

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

  // Broadcast the transaction
  web3.eth.sendSignedTransaction(raw, (err, txHash) => {
    console.log('txHash:', txHash)
    // Now go check etherscan to see the transaction!
  })
})

Best Answer

Fix:

const contract = new web3.eth.Contract(abi, contract_Address);

gasLimit: web3.utils.toHex(2100000)

value: web3.utils.toHex(web3.utils.toWei('0', 'ether')),

Related Topic