1

I have a server-side Node.js app that sends a transaction to an Ethereum smart contract like so:

const transaction = await contract.methods
    .method_name([params]).send({
      from: [wallet_address]
    });

I have my private key stored on the server but I don't know where to reference it and how to sign the transaction.

Any help is greatly appreciated.

2

Yes, you absolutely can! You will have to us the EthereumJS-tx package from NPM, you can get more information here: https://github.com/ethereumjs/ethereumjs-tx. It's as simple as:

const EthereumTx = require('ethereumjs-tx').Transaction
const privateKey = Buffer.from(
  'e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109',
  'hex',
)

const txParams = {
  nonce: '0x00',
  gasPrice: '0x09184e72a000',
  gasLimit: '0x2710',
  to: '0x0000000000000000000000000000000000000000',
  value: '0x00',
  data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057',
}

// The second parameter is not necessary if these values are used
const tx = new EthereumTx(txParams, { chain: 'mainnet', hardfork: 'petersburg' })
tx.sign(privateKey)
const serializedTx = tx.serialize()
1

You will have to perform three steps to sign in and access any methods from a deployed contract :

  1. Create transaction
  2. Sign the transaction
  3. Broadcast the transaction
// library required 
var Web3 = require('web3');
const EthereumTx = require('ethereumjs-tx').Transaction
var web3 = new Web3('https://ropsten.infura.io/v3/....');

const PRIVATE_KEY_1 = '0x562ca01e26a9f5b7a91c24beeb.........'
const AccountAddress1 = '0x8099F7ddEef97E7f1867DCA9ac990E9568ae40fc'
const privateKey1 = Buffer.from(PRIVATE_KEY_1,'hex')

    web3.eth.getTransactionCount(AccountAddress1, (err, txCount) => {
    
     //create transaction obj
    
     const txObject = {
      nonce : web3.utils.toHex(txCount),
      gasLimit : web3.utils.toHex(8000),
      gasPrice : web3.utils.toHex(web3.utils.toWei('10','gwei')),
      to : contractAddress,
      data : data
    }
    
     //sign the transaction 
    
     const tx = new EthereumTx(txObject, { chain: 'ropsten' })
     tx.sign(privateKey1)
     const serializedTransaction = tx.serialize()
     const row = "0x" + serializedTransaction.toString('hex')
    
     // Broadcast the transaction
    
     web3.eth.sendSignedTransaction(row, (err, txHash) => {
      console.log('txHash', txHash)
     })
    
    })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.