Как я могу подписать транзакцию на стороне сервера?

У меня есть серверное приложение Node.js, которое отправляет транзакцию в смарт-контракт Ethereum следующим образом:

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

Мой закрытый ключ хранится на сервере, но я не знаю, где на него ссылаться и как подписать транзакцию.

Любая помощь приветствуется.

Ответы (2)

Да, вы абсолютно можете! Вам понадобится пакет EthereumJS-tx от NPM, дополнительную информацию вы можете получить здесь: https://github.com/ethereumjs/ethereumjs-tx . Это так же просто, как:

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. Создать транзакцию
  2. Подпишите транзакцию
  3. Транслировать транзакцию
// 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)
     })
    
    })