Solidity
如何使用 Web3.js 指定特定使用者?
我是 Web3.js 的新手。
在geth中,我需要先解鎖一個帳戶,然後才能使用該帳戶發送一些交易。這確實有道理。
但是在web3.js中,不知道怎麼指定賬號。根據該文件,我嘗試按如下方式發送交易:
mycontract.methods.myfunc(params).send({from: pk})
在這裡,我剛剛指定了from address,它起作用了。但我從不解鎖帳戶或簽署此交易。誰能告訴我為什麼。。
簽署交易意味著提供私鑰。在 geth 中,解鎖意味著使私鑰可用於交易。因此,您不需要顯式定義私鑰。
添加@shrestha Bikesh 的資訊,如果您解鎖帳戶,則意味著您擁有自己的私鑰,該私鑰已加密,並且您正在使用解鎖密碼對其進行**解密。**我想你明白了。
有關資訊,
In testrpc 10 account address are given with private key separately. Here you don't need to unlock the account because this is already unlokced.
現在讓我們來看看 geth,當你從 geth 中取消帳戶並使用 web3js 庫中的帳戶地址時,你就可以了!您可以成功進行交易。
從 Dapp 你可以使用私鑰,你可以用給定的私鑰
web3.eth.accounts.signTransaction(tx, privateKey)簽署交易
$$ , callback $$);
tx - Object: The transaction object as follows: nonce - String: (optional) The nonce to use when signing this transaction. Default will use web3.eth.getTransactionCount(). chainId - String: (optional) The chain id to use when signing this transaction. Default will use web3.eth.net.getId(). to - String: (optional) The recevier of the transaction, can be empty when deploying a contract. data - String: (optional) The call data of the transaction, can be empty for simple value transfers. value - String: (optional) The value of the transaction in wei. gasPrice - String: (optional) The gas price set by this transaction, if empty, it will use web3.eth.gasPrice() gas - String: The gas provided by the transaction. privateKey - String: The private key to sign with. callback - Function: (optional) Optional callback, returns an error object as first parameter and the result as second.
返回為:
Promise 返回對象:簽名數據 RLP 編碼的交易,或者如果 returnSignature 為 true,則簽名值如下:
messageHash - String: The hash of the given message. r - String: First 32 bytes of the signature s - String: Next 32 bytes of the signature v - String: Recovery value + 27 rawTransaction - String: The RLP encoded transaction, ready to be send using web3.eth.sendSignedTransaction.
這裡@eth 定義如下
All transactions need to be signed. Otherwise they are considered invalid transactions and will not be included in the blockchain. A raw transaction is a transaction in raw bytes. If one has the raw bytes of a valid transaction, they can use sendRawTransaction. Otherwise, web3.js creates the signed transaction's bytes for you automatically as part of sendTransaction(). web3.js converts the JSON transaction {from:..., to:..., value:...} to the raw bytes and signs it for you automatically.
我想你現在得出結論,
每筆交易都需要簽名。