Last active
September 5, 2018 12:36
-
-
Save huahuayu/4c870cf94997dc89944561882d3eba82 to your computer and use it in GitHub Desktop.
code snippet to filter ethereum event log
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/ethereum/go-ethereum" | |
"github.com/ethereum/go-ethereum/common" | |
"github.com/ethereum/go-ethereum/ethclient" | |
"context" | |
"fmt" | |
"math/big" | |
"github.com/ethereum/go-ethereum/accounts/abi" | |
"strings" | |
"ethereum-development-with-go-book/code/contracts_erc20" | |
) | |
func filterQuery(){ | |
client, err := ethclient.Dial("https://ropsten.infura.io/aikxiYGH1Yoq8PVbKNB6") | |
erc20Abi, err := abi.JSON(strings.NewReader(string(token.TokenABI))) | |
if err != nil{ | |
fmt.Println(err.Error()) | |
} | |
query := ethereum.FilterQuery{ | |
FromBlock: big.NewInt(3905790), | |
ToBlock: big.NewInt(3905792), | |
Addresses: []common.Address{common.HexToAddress("0x466fb2e1979de417a30836a82c1739706938776a")}, // test token contract address | |
Topics: [][]common.Hash{{common.HexToHash("0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef")}}, // transfer event | |
} | |
logs, err := client.FilterLogs(context.Background(), query) | |
if err != nil{ | |
fmt.Println(err.Error()) | |
} | |
for _, log := range logs{ | |
var event = struct { | |
Value *big.Int // must named "Value", dont' change. | |
}{} | |
if len(log.Data) == 0 { | |
continue | |
} | |
err = erc20Abi.Unpack(&event, "Transfer", log.Data) | |
//value, _ :=hexutil.DecodeBig(string(log.Data[:])) | |
fmt.Println("txnHash:",log.TxHash.Hex()) | |
fmt.Println("from:",common.BytesToAddress(log.Topics[1].Bytes()).String()) | |
fmt.Println("to:",common.BytesToAddress(log.Topics[2].Bytes()).String()) | |
fmt.Println("value:", event.Value) | |
fmt.Println("value1:",common.Bytes2Hex(log.Data)) | |
fmt.Println("value2:",new(big.Int).SetBytes(log.Data)) | |
// The Removed field is true if this log was reverted due to a chain reorganisation. | |
fmt.Println("txn_rollback",log.Removed) | |
//fmt.Println("blockTimestamp:", block.Time().Int64()) | |
} | |
} | |
func main(){ | |
filterQuery() | |
/* | |
result: | |
txnHash: 0x3eef03e8be9fb3db82df5a74305cf0d2fe7440f0b9dd66176f4c989da99e2772 | |
from: 0xfCcbE6622475C791B61ffe6Ba952875e4fEB8D1C | |
to: 0xAc65742DadFDE13352c919f1623FBc28A1b29D9D | |
value: <nil> todo: why it's nil? as per https://ropsten.etherscan.io/tx/0x3eef03e8be9fb3db82df5a74305cf0d2fe7440f0b9dd66176f4c989da99e2772#eventlog, it's should be 1e+23 | |
value1: 00000000000000000000000000000000000000000000152d02c7e14af6800000 | |
value2: 100000000000000000000000 | |
txn_rollback false | |
*/ | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment