Web3j Transaction Receipt Processor 簡介與使用


  之前的文章有聊過Transaction Manager,當時對於一個參數TransactionReceiptProcessor 不太能了解,這次因為一些需求,找到了這個物件,剛好可以解決我們的問題。所以這邊要聊聊Web3中,TransactionReceiptProcessor 的運用。

     在我們實際開發的場景中,在smart contract的function最後會留下一個event,作為紀錄,方便當下的驗證,在未來的稽核跟調閱歷史紀錄也比較方便。最一開始,我們選擇了web3j wrapper裡提供的event observable去對event做註冊的方式,如何使用可以參考這篇文章的How to monitor events。
    不過,在實際的應用上會發現,observable回來的物件,資訊不太足夠,只有單純event的參數內容,還是會希望有transaction receipt會比較方便作後面的應用。但是也不希望每次送transaction都等在那邊,或是用aync放到queue再開thread做polling。簡單來說,就是希望簡單用,不要只是送個交易,還要做這麼多管理。

    此次我們的應用,是要把前端資料,藉由後端sign過再push到鏈上,所以原則上是send raw transaction的方式,這次單純使用RawTransactionManager這個物件。在RawTransactionManager預設是使用 PollingTransactionReceiptProcessor ,根據官方解釋:
is the default processor used in web3j, which polls periodically for a transaction receipt for each individual pending transaction.
 此時發現另一種process叫做,QueuingTransactionReceiptProcessor
has an internal queue of all pending transactions. It contains a worker that runs periodically to query if a transaction receipt is available yet. If a receipt is found, a callback to the client is invoked.
兩種運作方式不一樣,不過簡單來說,QueuingTransactionReceiptProcessor會在背後幫我們做polling,等到有結果後,會呼叫callback,讓開發者比較輕鬆去得到transaction 的結果。更詳細可以看官方的介紹
使用方式如下:
RawTransactionManager txMgr = new RawTransactionManager(Main.Web3, credentials, (byte)-1, new QueuingTransactionReceiptProcessor( Web3, new Callback() { @Override public void accept(TransactionReceipt transactionReceipt) { // do what you want } @Override public void exception(Exception e) { // handle exception... } }, DEFAULT_POLLING_ATTEMPTS_PER_TX_HASH, pollingInterval) )};
    從override的accept可以得到transaction receipt,transaction receipt可以幹麻我就不解釋了。特別講一下裡面有兩個變數,gasUsed, cumulativeGasUsed,一開始接觸的可能不熟悉,或是在自己私鏈測試的可能看不出差別(我自己就是 XD),gasUsed就是直覺所知的,這個transaction的gas使用量,而cumulativeGasUsed是整個block的累積用量。
    在多解釋一下,如果這個transaction是有event的,在receipt裡topic的第一個值就是event的sha3值,裡面的值會是這樣算出來,keccak256("EventTest(string,uint256)")。如果你smart contract的event參數有加上indexed(不清楚這是啥的,可以參考這裡),那就是array接著的第二個, 三個值等等。

這篇就簡單介紹到這裡,如果任何不清楚或是錯誤,歡迎指教

留言

張貼留言

這個網誌中的熱門文章

What's New in Ethereum Serenity (2.0)

瑞士滑雪分享2 - 策馬特

動手實做零知識 - circom