[英]How to read information from ethereum transaction using transactionHash in web3?
假設我在智能合約中更新了一個變量 x as(x=10)。 我存儲了事務哈希。 然后我再次更改 x=20 的值,然后我會得到一個新的事務 hash。 那么有什么方法可以使用較早更新(x = 10)的transactionHash,我可以看到它的x值是多少?
有點晚了,但也許我的回答會幫助其他人在這個問題上掙扎。
When you make a transaction via a smart contract function call, the input parameters are ABI.encoded into the transaction data, along with the function selector , which is the first 4bytes of the hash of the function signature.
例如,使用str = 'hello'
調用function set(string memory str)
將產生以下交易數據:
0x4ed3885e0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000568656c6c6f000000000000000000000000000000000000000000000000000000
其中4ed3885e
是 function 選擇器, rest 是輸入參數編碼。
據我所知,有兩種方法可以從交易數據中解碼輸入參數。
我將粘貼一個使用這兩種方法解碼 4 個輸入參數的示例。
Web3 示例:
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('https...')); // your web3 provider
var transaction = '0xe7ad9ce53fd1d1559dc6ca57e67ed5c8cd612b6264ddc4f78b0736ad24a5bc29';
web3.eth.getTransaction(transaction, function(err, tx){
let tx_data = tx.input;
let input_data = '0x' + tx_data.slice(10); // get only data without function selector
let params = web3.eth.abi.decodeParameters(['bytes32', 'string', 'string', 'string'], input_data);
console.log(params);
});
Abi 解碼器示例:
var Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('https...')); // your web3 provider
var abiDecoder = require('abi-decoder');
var ABI = ... ; // abi of your contract
var transaction = '0xe7ad9ce53fd1d1559dc6ca57e67ed5c8cd612b6264ddc4f78b0736ad24a5bc29';
web3.eth.getTransaction(transaction, function(err, tx){
abiDecoder.addABI(ABI);
let tx_data = tx.input;
let decoded_data = abiDecoder.decodeMethod(tx_data);
let params = decoded_data.params;
let param_values = [];
for(i in params){ // loop to print parameters without unnecessary info
param_values.push(params[i].name + " : " + params[i].value);
}
console.log(param_values);
});
有兩種方法可以從智能合約中獲取 output
您直接使用智能合約 ABI 閱讀 state 並調用
該事務包含您可以從事務日志中解析的Solidity 事件
對於這兩種情況,都必須將支持寫入智能合約,並且在這個問題中,智能合約代碼本身丟失了,因此無法准確說明如何執行此操作。
一般節點不支持讀取歷史state。 但是它們支持讀取歷史事件日志,因此如果您需要訪問時間序列中的數據,那么您需要編寫智能合約以便它發出事件。
有兩種方法可以從智能合約中獲取 output
您直接使用智能合約 ABI 閱讀 state 並調用
該事務包含您可以從事務日志中解析的Solidity 事件
對於這兩種情況,都必須將支持寫入智能合約,並且在這個問題中,智能合約代碼本身丟失了,因此無法准確說明如何執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.