Ethereumjs
如何在瀏覽器中使用 ethereumjs-tx.js
我一直在嘗試在瀏覽器中使用 ethereumjs-tx。我已經從這裡下載了瀏覽器版本https://github.com/ethereumjs/browser-builds/tree/master/dist
這是我的程式碼片段
<head> <title></title> <meta charset="utf-8" /> <script type="text/javascript" src="ethereumjs-tx.js"></script> </head> <body> <script> var Tx = require('ethereumjs-tx'); var privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex'); var rawTx = { nonce: '00', gasPrice: '09184e72a000', gasLimit: '2710', to: '0000000000000000000000000000000000000000', value: '00', data: '7f7465737432000000000000000000000000000000000000000000000000000000600057' }; var tx = new Tx(rawTx); tx.sign(privateKey); var serializedTx = tx.serialize(); </script>
但是,它一直在控制台中拋出錯誤 Uncaught ReferenceError: require is not defined
試試這個..
<html> <head> <!-- <script src="https://github.com/ethereumjs/browser-builds/blob/master/dist/ethereumjs-tx/ethereumjs-tx-1.3.3.min.js"></script> --> <script src="https://cdn.jsdelivr.net/gh/ethereumjs/browser-builds/dist/ethereumjs-tx/ethereumjs-tx-1.3.3.min.js"></script> <script> console.log('typeof ethereumjs:', (typeof ethereumjs)) console.log('Object.keys(ethereumjs):', Object.keys(ethereumjs)) console.log('typeof ethereumjs.Tx:', (typeof ethereumjs.Tx)) console.log('typeof ethereumjs.RLP:', (typeof ethereumjs.RLP)) console.log('typeof ethereumjs.Util:', (typeof ethereumjs.Util)) console.log('typeof ethereumjs.Buffer:', (typeof ethereumjs.Buffer)) console.log('typeof ethereumjs.Buffer.Buffer:', (typeof ethereumjs.Buffer.Buffer)) { let privateKey = new ethereumjs.Buffer.Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex') let txParams = { nonce: '0x00', gasPrice: '0x09184e72a000', gasLimit: '0x2710', to: '0x0000000000000000000000000000000000000000', value: '0x00', data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057' } let tx = new ethereumjs.Tx(txParams) tx.sign(privateKey) let serializedTx = tx.serialize().toString('hex') console.log('serializedTx:', serializedTx) } </script> </head> <body> </body> </html>
這實際上與乙太坊無關,但無論如何。
require() 不是有效的 JS 函式客戶端。意思是……您的瀏覽器在到達該行時不知道該怎麼做
require
。有一個名為require.js的漂亮包,它確實將 require 功能擴展到您的瀏覽器。
我不熟悉他們的瀏覽器版本,但可能是您使用的程式碼不適用於這些版本。如果我是你,我會嘗試刪除“require”行並查看它是否執行,因為你正在載入 ethereumjs-tx。
此外,如果那是一個 HTML 片段,您應該將您的 JS 包裝在
<script>
標籤中,並且可能console.log(serializedTx)
或任何您想要得到的東西,這樣您就可以在它執行時實際看到結果。;)