Web3js

使用web3js v1.2.11離線創建簽名合約交易

  • October 6, 2021

我正在嘗試使用 web3js v1.2.11 離線簽署契約交易。

signingAddr = //my eth address
signingPk = //my private key

// docs: The options object for the contract instance. from, gas and gasPrice are used as fallback values when sending transactions.
myContractInstance.options = {
 gas : 800000,
 gasPrice : 60000000000,
 value : 1000000000000000,
 from : signingAddr
}
//docs: Creates a transaction object for that method, which then can be called, send, estimated.
let tx = await myContractInstance.methods.myFunction(myParam1,myParam2)

//docs: "Signs an Ethereum transaction with a given private key."
let signedTx = await web3.eth.signTransaction(tx,signingPk)

console.log(signedtx)
//Error: The send transactions "from" field must be defined!

我也嘗試過:

let tx = await myContractInstance.methods.myFunction(myParam1,myParam2).send({from:signingAddr})
//TypeError: Cannot read property 'filter' of undefined

文件連結:

我知道 contract 方法返回的 tx 對象與signTransaction. 我不確定 web3.js 是否可行?

似乎在早期版本的 web3js 中有一個函式getData可以獲取所需的呼叫數據。

如何使用 webjs v1.2.11 離線創建有效的簽名合約呼叫交易?

tx 對像如下:

const tx = {
 nonce: nonce,
 gasPrice: gasPrice,
 gasLimit: gasLimit,
 to: contractAddress,
 value: value,
 data: contractData,
};

我認為您正在尋找的是使用enoceABI()web3 函式獲得的數據參數(參見https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#methods-mymethod-encodeabi) :

contractData = myContractInstance.methods.myFunction(myParam1,myParam2).encodeABI();

我有很多錯誤的地方:

要添加到@clement 的答案,tx應該是:

 tx = {
   nonce: nonce,
   gasPrice: gasPrice,
   gasLimit: gasLimit,
   to: contractAddress,
   value: value,
   data: contractData,
   chainId : 1,
}); //add chainId

我還需要創建一個帳戶對象:

let acc = await web3.eth.accounts.wallet.add(signingPrivateKey)

然後呼叫signTransaction它:

signedtx = await acc.signTransaction(tx,signingPrivateKey)

引用自:https://ethereum.stackexchange.com/questions/86421