1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
| package main
import ( "context" "fmt" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/ethclient" "log" )
func main() { client,err := ethclient.Dial("wss://mainnet.infura.io/ws/v3/80d7c83efe29424c99930c19a6980114") if err != nil{ log.Fatal(1,err) } chainID, err := client.NetworkID(context.Background()) if err != nil { log.Fatal(2,err) } defer func() { if err := recover();err != nil{ fmt.Println(err) } }()
for{ headers := make(chan *types.Header) sub,err := client.SubscribeNewHead(context.Background(),headers) if err != nil{ log.Fatal(1,err) } for { select { case err := <- sub.Err(): log.Fatal(err) case header := <- headers: block,err := client.BlockByHash(context.Background(),header.Hash()) if err != nil{ log.Fatal(2,err) } for _,tx := range block.Transactions(){ message,err := tx.AsMessage(types.LatestSignerForChainID(chainID),tx.GasPrice()) if err != nil{ log.Fatal(3,err) } switch message.From().Hex() { case "": fmt.Println("txHash: ",tx.Hash().Hex()) fmt.Println("from: ",message.From().Hex()) if message.To() != nil{ fmt.Println("to: ",message.To().Hex()) } fmt.Println("value: ",tx.Value().String()) fmt.Println("------------------------------------------------") default: fmt.Println("txHash: ",tx.Hash().Hex()) fmt.Println("from: ",message.From().Hex()) if message.To() != nil { fmt.Println("to: ", message.To().Hex()) } fmt.Println("value: ",tx.Value().String()) fmt.Println("------------------------------------------------") } } } } } }
|