[Ethereum] Monitoring pending transactions with Go

filtersgo-ethereumgolang

I'm trying to write a program in Go to watch pending transactions, using a geth full node that I'm connected to over websockets. I'm pretty sure I have to use the github.com/ethereum/go-ethereum/eth/filters package to create a new event system, on which I can then call SubscribePendingTxs, but I don't know what I should use as the backend.

Best Answer

This is how you do it if you want to make two type of calls at the same time, via Ethereum client and raw RPC (web):

; ETH_NODE_RPC_URL="http://localhost:8545"
import(
    "github.com/ethereum/go-ethereum/ethclient"
    "github.com/ethereum/go-ethereum/rpc"
)
const RPC_URL = os.Getenv("ETH_NODE_RPC_URL")
rpcclient, err=rpc.DialContext(context.Background(), RPC_URL)
eclient = ethclient.NewClient(rpcclient)

filter := ethereum.FilterQuery{}
filter.FromBlock = big.NewInt(block_num_from)
filter.ToBlock = big.NewInt(block_num_to)
topics := make([]common.Hash,0,1)
signature := common.BytesToHash(evt_name_registered2)
topics = append(topics,signature)
filter.Topics= append(filter.Topics,topics)
filter.Addresses = nil 
logs,err := eclient.FilterLogs(context.Background(),filter)
if err!= nil {
    //
}
for _,log := range logs {
    //
}

This code snippet I am using it to scan events, but for pending logs it should be similar. Try to make it work over HTTP first, then switching the medium to web service should be trivial.

Related Topic