Web3.0-使用metamask獲取某個賬號(錢包地址)的余額、交易回執(zhí)
獲取某個賬號(錢包地址)的最新余額
以下代碼就是獲取制定賬戶余額的方法,獲取到的余額是16進(jìn)制的wei,在獲取余額成功后我已經(jīng)做了轉(zhuǎn)換,params中兩個參數(shù),第1個是你要查詢的賬戶(錢包地址),第2個是固定參數(shù),表示最新余額。
//獲取余額 ? ?ethereum.request({ ? ? ? ? ? ?method: 'eth_getBalance', ? ? ? ? ? ?params: [ ? ? ? ? ? ? ? '0xBcFf5a3c1970D795777d7471F2792832BAF5679d' , ? ? ? ? ? ? ? ?'latest' ? ? ? ? ? ?] ? ? ? ?}) ? ? ? ?.then((result) => { ? ? ? ? ? ?console.log("獲取余額success--->" + result) ? ? ? ? ? ?let formartEther = ethers.utils.formatEther(result); //16進(jìn)制的wei ? ? ? ? ? ?console.log(formartEther) ? ? ? ?}) ? ? ? ?.catch((error) => { ? ? ? ? ? ?console.log("獲取余額error--->" + error.code) ? ? ? ?});
或者:
// 連接賬號 function connect() { ? ?console.log('Calling connect()') ? ?ethereum ? ?.request({ method: 'eth_requestAccounts' }) ? ?.then(handleAccountsChanged) ? ?.catch((err) => { ? ?if (err.code === 4001) { ? ? ? ?// EIP-1193 userRejectedRequest error ? ? ? ?// If this happens, the user rejected the connection request.賬號拒絕登錄metamask ? ? ? ?console.log('Please connect to MetaMask.'); ? ? ? ?$('#status').html('You refused to connect Metamask') ? ?} else { ? ? ? ?console.error(err); ? ?} ? ?}); }
獲取交易回執(zhí)
//發(fā)出支付請求 ? ?ethereum ? ? ? ?.request({ ? ? ? ? ? ?method: 'eth_sendTransaction', ? ? ? ? ? ?params: [ ? ? ? ? ? ? ? ?{ ? ? ? ? ? ? ? ? ? ?from: fromAddress, ? ? ? ? ? ? ? ? ? ?to: toAddress, ? ? ? ? ? ? ? ? ? ?value: value, ? ? ? ? ? ? ? ?} ? ? ? ? ? ?] ? ? ? ?}) ? ? ? ?.then((result) => { ? ? ? ? ? ?console.log(result) ? ? ? ? ? ?//'0xec9026d3a9d4cd4d44ac7cd49186a05c8a2db4d697a05207d8e804d2a245455a' ? ? ? ? ? ?if (result != null || result != undefined){ ? ? ? ? ? ? ? ?console.log("開始計時") ? ? ? ? ? ? ? ?let paramsStr = []; ?//對應(yīng)查詢時的參數(shù)params,列表 ? ? ? ? ? ? ? ?paramsStr[0] = result; ? ? ? ? ? ? ? ?//需要等待十秒 才能收到回執(zhí)單信息 返回回執(zhí)代碼串 和 回執(zhí)單不是同時的 所以有時候能直接通過回執(zhí)代碼串獲取到回執(zhí)單 有時候獲取不到 可能跟網(wǎng)速有關(guān)系 所以在獲取到 ? ? ? ? ? ? ? ?//回執(zhí)代碼串之后 延時十秒再獲取回執(zhí)單即可 ? ? ? ? ? ? ? ?setTimeout(function () { ? ? ? ? ? ? ? ? ? ?getReceipt(paramsStr) // 10秒后執(zhí)行下面的函數(shù),獲取交易回執(zhí) ? ? ? ? ? ? ? ?},10000); ? ? ? ? ? ?} ? ? ? ?}) ? ? ? ?.catch((error) => { ? ? ? ?}); //獲取回執(zhí)單的方法 ? ?function getReceipt(paramsStr) { ? ? ? ?ethereum.request({ ? ? ? ? ? ?method: 'eth_getTransactionReceipt', ? ? ? ? ? ?params: paramsStr ? ? ? ?}) ? ? ? ? ? ?.then((result) => { ? ? ? ? ? ? ? ?console.log(result) ? ? ? ? ? ?}) ? ? ? ? ? ?.catch((error) => { ? ? ? ? ? ? ? ?console.log("error--->" + error.message) ? ? ? ? ? ? ? ?// If the request fails, the Promise will reject with an error. ? ? ? ? ? ?}); ? ?}
//發(fā)出支付請求之10秒后,通過返回值paramsStr,即Transaction Hash從以太坊交易中讀取交易回執(zhí)信息。

編輯切換為居中
回執(zhí):

編輯切換為居中
實際操作
在交易提交返回到Transaction Hash時,說明交易成功,可以在這個時候?qū)ransaction Hash及其他交易信息,一并提交至數(shù)據(jù)庫。至于獲取訂單回執(zhí),隨時可以通過錢包地址及Transaction Hash獲取。
