Web3.js查詢以太幣和代幣余額及轉(zhuǎn)賬
安裝
npm install web3
web3.js查詢以太幣及代幣余額以及進行以太幣和代幣轉(zhuǎn)賬
在私鏈和主鏈上查詢以太幣及代幣余額
查詢類方法在私鏈和主鏈上的方法都是一樣的
主鏈地址??梢匀?code>infura申請
contractAbi
。合約的abi。可以去https://etherscan.io獲取,如果代幣合約提供了code
,就會有abi
// 引入web3 var Web3 = require('web3'); if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { // web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:7545")); web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io/yourAddress")); } // 定義合約abi var contractAbi = [{"constant":true,"inputs":[],"name":"mintingFinished","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"cap","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"unpause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_amount","type":"uint256"}],"name":"mint","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"paused","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_subtractedValue","type":"uint256"}],"name":"decreaseApproval","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"finishMinting","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"pause","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_addedValue","type":"uint256"}],"name":"increaseApproval","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"_owner","type":"address"},{"name":"_spender","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"burner","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[],"name":"Pause","type":"event"},{"anonymous":false,"inputs":[],"name":"Unpause","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"amount","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[],"name":"MintFinished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"owner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"}]; // 合約地址 var contractAddress = "0x7FCCF800568747b178c6cBbe4Bf3d147df75ac61"; // 賬號 var currentAccount = "0x4e9d5c58d8d6f02FFe5A6EF10CB804FfFB556bBb"; // 定義合約 var myContract = new web3.eth.Contract(contractAbi, contractAddress, { from: currentAccount, // default from address gasPrice: '10000000000' // default gas price in wei, 10 gwei in this case }); // 查詢以太幣余額 web3.eth.getBalance(currentAccount).then(console.log); // 查看某個賬號的代幣余額 myContract.methods.balanceOf(contractAddress).call({from: currentAccount}, function(error, result){ if(!error) { console.log(result); } else { console.log(error); } });
這里還可以查詢代幣的名稱,符號,小數(shù)位,發(fā)行總量等等,因為代幣合約一般都符合
ERC
標準,都有這些基本方法。甚至如果你有合約代碼和abi
,還可以調(diào)用合約的其他方法,當然調(diào)用有些方法需要權(quán)限及前置條件
// 獲得代幣名稱 myContract.methods.name().call({from: currentAccount}, function(error, result){ if(!error) { console.log(result); } else { console.log(error); } }); // 獲取代幣符號 myContract.methods.symbol().call({from: currentAccount}, function(error, result){ if(!error) { console.log(result); } else { console.log(error); } }); // 獲取代幣總量 myContract.methods.totalSupply().call({from: currentAccount}, function(error, result){ if(!error) { console.log(result); } else { console.log(error); } }); // 查看某個賬號允許另一個賬號可使用的代幣數(shù)量 myContract.methods.allowance(sender, spender).call({from: currentAccount}, function(error, result){ if(!error) { console.log(result); } else { console.log(error); } });
在私鏈上轉(zhuǎn)賬以太幣及代幣
// 以太幣轉(zhuǎn)賬 web3.eth.sendTransaction({ from: currentAccount, to: receiverAccount, value: '1000000000000000' }) .then(function(receipt){ console.log(receipt); }); // 代幣轉(zhuǎn)賬 myContract.methods.transfer(to, amount).send({from: currentAccount}), function(error, transactionHash){ if(!error) { console.log('transactionHash is ' + transactionHash); } else { console.log(error); } });
在主鏈上轉(zhuǎn)賬以太幣及代幣
上面的方法只適用于私鏈。因為你在私鏈的賬戶在本地是有私鑰的。而在主鏈上要進行寫入數(shù)據(jù)的方法,是需要獲取賬戶的私鑰并對交易進行簽名的,所以要用到
web3.eth.sendSignedTransaction
方法-文檔
npm install ethereumjs-tx
以太幣轉(zhuǎn)賬
// 引入ethereumjs-tx var Tx = require('ethereumjs-tx'); // 以太幣轉(zhuǎn)賬 // 先獲取當前賬號交易的nonce web3.eth.getTransactionCount(currentAccount, web3.eth.defaultBlock.pending).then(function(nonce){ // 獲取交易數(shù)據(jù) var txData = { // nonce每次++,以免覆蓋之前pending中的交易 nonce: web3.utils.toHex(nonce++), // 設(shè)置gasLimit和gasPrice gasLimit: web3.utils.toHex(99000), gasPrice: web3.utils.toHex(10e9), // 要轉(zhuǎn)賬的哪個賬號 to: '0x3b11f5CAB8362807273e1680890A802c5F1B15a8', // 從哪個賬號轉(zhuǎn) from: currentAccount, // 0.001 以太幣 value: web3.utils.toHex(10e14), data: '' } var tx = new Tx(txData); // 引入私鑰,并轉(zhuǎn)換為16進制 const privateKey = new Buffer('your account privateKey', 'hex'); // 用私鑰簽署交易 tx.sign(privateKey); // 序列化 var serializedTx = tx.serialize().toString('hex'); web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), function(err, hash) { if (!err) { console.log(hash); } else { console.error(err); } }); });
代幣轉(zhuǎn)賬
// 補齊64位,不夠前面用0補齊 function addPreZero(num){ var t = (num+'').length, s = ''; for(var i=0; i<64-t; i++){ s += '0'; } return s+num; } web3.eth.getTransactionCount(currentAccount, web3.eth.defaultBlock.pending).then(function(nonce){ // 獲取交易數(shù)據(jù) var txData = { nonce: web3.utils.toHex(nonce++), gasLimit: web3.utils.toHex(99000), gasPrice: web3.utils.toHex(10e9), // 注意這里是代幣合約地址 to: contractAddress, from: currentAccount, // 調(diào)用合約轉(zhuǎn)賬value這里留空 value: '0x00', // data的組成,由:0x + 要調(diào)用的合約方法的function signature + 要傳遞的方法參數(shù),每個參數(shù)都為64位(對transfer來說,第一個是接收人的地址去掉0x,第二個是代幣數(shù)量的16進制表示,去掉前面0x,然后補齊為64位) data: '0x' + 'a9059cbb' + addPreZero('3b11f5CAB8362807273e1680890A802c5F1B15a8') + addPreZero(web3.utils.toHex(1000000000000000000).substr(2)) } var tx = new Tx(txData); const privateKey = new Buffer('your account privateKey', 'hex'); tx.sign(privateKey); var serializedTx = tx.serialize().toString('hex'); web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), function(err, hash) { if (!err) { console.log(hash); } else { console.error(err); } }); });
到此這篇關(guān)于Web3.js查詢以太幣和代幣余額以及轉(zhuǎn)賬的文章就介紹到這了,更多相關(guān)Web3.js 轉(zhuǎn)賬余額查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
javascript getElementsByTagName
DC大神為早期不支持getElementsByTagName的瀏覽器寫的hack,當然與原生的不能同日而言,原生的用到緩存機制呢。2011-01-01js中Number數(shù)字數(shù)值運算后值不對的解決方法
下面小編就為大家?guī)硪黄猨s中Number數(shù)字數(shù)值運算后值不對的解決方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02如何正確使用javascript 來進行我們的程序開發(fā)
Javascript 正確使用方法,下面為大家介紹的是一個關(guān)于如何正確使用javascript 來進行我們的程序開發(fā),需要的朋友可以參考下2014-06-06JavaScript+CSS無限極分類效果完整實現(xiàn)方法
這篇文章主要介紹了JavaScript+CSS無限極分類效果完整實現(xiàn)方法,涉及JavaScript針對頁面元素節(jié)點遍歷與動態(tài)操作技巧,需要的朋友可以參考下2015-12-12JavaScript通過RegExp實現(xiàn)客戶端驗證處理程序
通過RegExp實現(xiàn)客戶端驗:讓文本框只允許輸入數(shù)字、文本框只允許輸入中文、郵箱輸入格式的判斷等等,具體實現(xiàn)如下,感興趣的朋友可以參考下哈2013-05-05