Dapps

如何在乙太坊 Dapp 中顯示區塊鏈交易收據詳情

  • February 16, 2022

在我的 dapp 設計中,我希望通過指向 Etherscan 等網站的連結或在 dapp 中的單獨頁面上提供完整詳細資訊,為使用者提供查看區塊鏈交易收據詳細資訊的選項。

如何實現?

請幫助提供一些範常式式碼或實現以供參考。

假設您使用 Web3.js 之類的東西作為 dApp 的前端。

您將使用類似 inside 的函式呼叫methods.myMethod.send()web3.eth.Contract為您的後端智能合約呼叫特定的合約函式。

函式呼叫將返回一個transactionHash您可以立即使用的。

對於 etherscan 的連結,只需獲取事務雜湊並將其添加到標準 url 的末尾,如下所示:

'https://etherscan.io/tx/' + transactionHash

如果您想直接在您的使用者體驗中顯示它,您還可以繼續使用 Web3.js 從交易中獲取詳細資訊web3.eth.getTransaction()

web3.eth.getTransaction('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b§234')
.then(console.log);

> {
   "hash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
   "nonce": 2,
   "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
   "blockNumber": 3,
   "transactionIndex": 0,
   "from": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
   "to": "0x6295ee1b4f6dd65047762f924ecd367c17eabf8f",
   "value": '123450000000000000',
   "gas": 314159,
   "gasPrice": '2000000000000',
   "input": "0x57cb2fc4"
}

獲取交易收據(雜湊$$ , callback $$) . 通過交易雜湊返回交易的收據。
注意。收據不可用於待處理的交易

https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethgettransactionreceipt

var receipt = web3.eth.getTransactionReceipt('0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b');
console.log(receipt);
{
 "transactionHash": "0x9fc76417374aa880d4449a1f7f31ec597f00b1f6f3dd2d66f4c9c6c445836d8b",
 "transactionIndex": 0,
 "blockHash": "0xef95f2f1ed3ca60b048b4bf67cde2195961e0bba6f70bcbea9a2c4e133e34b46",
 "blockNumber": 3,
 "contractAddress": "0xa94f5374fce5edbc8e2a8697c15331677e6ebf0b",
 "cumulativeGasUsed": 314159,
 "gasUsed": 30234,
 "logs": [{
        // logs as returned by getFilterLogs, etc.
    }, ...],
 "status": "0x1"
}

返回

Object - 交易收據對象,如果未找到收據,則返回 null:

  • blockHash: String, 32 Bytes - 該交易所在區塊的雜湊值。
  • blockNumber: Number - 該交易所在的區塊號。
  • transactionHash: String, 32 Bytes - 交易的雜湊值。
  • transactionIndex: Number - 區塊中交易索引位置的整數。
  • from: String, 20 Bytes - 發件人的地址。
  • to: String, 20 Bytes - 接收者的地址。合約創建交易時為空。
  • 累積GasUsed:數字 - 在塊中執行此交易時使用的總氣體量。
  • gasUsed: Number - 僅此特定交易使用的氣體量。
  • contractAddress: String - 20 字節 - 創建的合約地址,如果交易是合約創建,否則為空。
  • logs: Array - 此事務生成的日誌對像數組。
  • status: String - ‘0x0’ 表示交易失敗,‘0x1’ 表示交易成功。

引用自:https://ethereum.stackexchange.com/questions/55783