Web3js
如何正確創建原始交易並在瀏覽器中使用 web3 對其進行簽名
我想使用 web3 在瀏覽器中創建和簽署交易。為了創建原始交易,我想我必須做這樣的事情(希望你能填補我的知識空白)
var pk = '0x6ba33b3f7997c2bf63d82f3baa1a8069014a59fa1f554af3266aa85afee9d0a9'; pk = new Buffer(pk,'hex'); var address = '0xFb4d271F3056aAF8Bcf8aeB00b5cb4B6C02c7368'; var myContractsAddress = '0x0cb4edc28d17c43a75797bf5effc141fd5da8715'; var rawTx = { nonce: web3.toHex(web3.eth.getTransactionCount(acct1)), to: myContractsAddress, gasPrice: web3.toHex(20000000000), gasLimit: web3.toHex(200000), value: ***Here I am not sure, am I supposed to encode my list of variables? and do I encode everything to hex, or just integers? And how would that list look like?*** data: *This field is irrelevant for now, and just for documentationpurpose, right?* }
這應該給我我的原始交易(關於數據欄位的部分我很遺憾不知道並且很想獲得幫助!
假設我的原始交易此時是有效且正確的,我現在必須使用私鑰對其進行簽名。我見過的解決方案使用了一個名為ethereumjs-tx的 node.js 庫。是否有僅使用 web3 的解決方案,或者我是否必須以某種方式將此庫移植到我的瀏覽器中?
下面是在https://programtheblockchain.com/dapps/counter上呼叫“增量”的工作程式碼。(有關該範例的更多資訊:https ://programtheblockchain.com/posts/2017/12/13/building-decentralized-apps-with-ethereum-and-javascript/ 。)
它使用
web3.js
和ethereumjs-tx
:<!-- from https://github.com/ethereumjs/browser-builds/raw/master/dist/ethereumjs-tx/ethereumjs-tx-1.3.3.min.js --> <script src="ethereumjs-tx-1.3.3.min.js"></script> <script> var address = "0xf15090c01bec877a122b567e5552504e5fd22b79"; var abi = [{"constant":true,"inputs":[],"name":"getCount","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"increment","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"_count","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]; var account = "<REDACTED ACCOUNT ADDRESS>"; var privateKey = "<REDACTED PRIVATE KEY WITHOUT 0x PREFIX>"; var web3 = new Web3(new Web3.providers.HttpProvider( "https://ropsten.infura.io/<REDACTED API KEY")); web3.eth.getTransactionCount(account, function (err, nonce) { var data = web3.eth.contract(abi).at(address).increment.getData(); var tx = new ethereumjs.Tx({ nonce: nonce, gasPrice: web3.toHex(web3.toWei('20', 'gwei')), gasLimit: 100000, to: address, value: 0, data: data, }); tx.sign(ethereumjs.Buffer.Buffer.from(privateKey, 'hex')); var raw = '0x' + tx.serialize().toString('hex'); web3.eth.sendRawTransaction(raw, function (err, transactionHash) { console.log(transactionHash); }); }); </script>