Web3js
使用 web3 從錢包發送付款
如何從我的 ubuntu 乙太坊節點向任何地址發送付款?
有沒有可行的例子,可以幫助我完成這項工作?
程式碼編輯
var Web3 = require('web3'); var Tx = require('ethereumjs-tx'); // Show Web3 where it needs to look for a connection to Ethereum. //web3 = new Web3(new Web3.providers.HttpProvider('http://127.0.0.1:8545')); web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/<account-id>')); var gasPrice = "2";//or get with web3.eth.gasPrice var gasLimit = 3000000; var addr = "0x......................"; var toAddress = "0x.............................."; var amountToSend = "0.00192823123348952"; //$1 var nonce = web3.eth.getTransactionCount(addr); //211; var rawTransaction = { "from": addr, "nonce": web3.utils.toHex(nonce), "gasPrice": web3.utils.toHex(gasPrice * 1e9), "gasLimit": web3.utils.toHex(gasLimit), "to": toAddress, "value": amountToSend , "chainId": 41 //remember to change this }; var privateKey = "........................................................."; var privKey = new Buffer(privateKey, 'hex'); console.log("privKey : ", privKey); var tx = new Tx(rawTransaction); tx.sign(privKey); var serializedTx = tx.serialize(); console.log('serializedTx : '+serializedTx); web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) { if (!err) { console.log('Txn Sent and hash is '+hash); } else { console.error(err); } });
有兩種方法可以做到這一點。如果您想使用帶有密碼的地址,請按照以下方法操作。
web3.personal.unlockAccount(addr, pass); const toAddress = "0x...."; // Address of the recipient const amount = 2; // Willing to send 2 ethers const amountToSend = web3.utils.toWei(amount, "ether"); // Convert to wei value var send = web3.eth.sendTransaction({ from: addr, to: toAddress, value: amountToSend });
對於上述方法,您需要密鑰庫文件存在於同一台 Ubuntu 機器中。
如果您想發送
privateKey
:var gasPrice = 2; // Or get with web3.eth.gasPrice var gasLimit = 3000000; var rawTransaction = { "from": addr, "nonce": web3.toHex(nonce), "gasPrice": web3.utils.toHex(gasPrice * 1e9), "gasLimit": web3.utils.toHex(gasLimit), "to": toAddress, "value": amountToSend, "chainId": 4 // Remember to change this }; var privKey = new Buffer(privateKey, 'hex'); var tx = new Tx(rawTransaction); tx.sign(privKey); var serializedTx = tx.serialize(); web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) { if (!err) { console.log('Txn Sent and hash is '+hash); } else { console.error(err); } });