0

I've been trying to get a go program going that monitors a smart contract for emitted events. I had found the amazingly written https://goethereumbook.org/event-read-erc20/ unfortunately it appears to be quite outdated and I couldn't get the presented sample code to work.

(the contract inherits from openzeppelin ERC20 and is deployed on a local hardhat node and I can interact and monitor for events via ethers)

After taking a closer look at the code generated by
abigen --sol testcontract.sol --out testcontract.go --pkg testcontract

from a simple

pragma solidity 0.8.4;

contract TestContract {
  event Transfer(address indexed from, address indexed to, uint tokens);
}

It appears that the generated code already provides a WatchTransfer function to monitor for the events. I guess this didn't exists yet when the goethereumbook was written.

The code runs, I can see on the node that it calls eth_subscribe but for some reason the events are not being logged. I guess I'm still missing one crucial piece and hope someone can point me in the right direction.

client, err := ethclient.Dial(websocketAddress)
if err != nil {
  log.Fatal(err)
}
log.Printf("websocket connection established: %s", websocketAddress)

tc, err := testcontract.NewTestContract(common.HexToAddress(localNetworkContractAddress), client)
if err != nil {
  log.Fatal(err)
}

transfers := make(chan *testcontract.TestContractTransfer)

sub, err := tc.WatchTransfer(nil, transfers, nil, nil)
if err != nil {
  log.Fatal(err)
}

for {
  select {
  case err := <-sub.Err():
    log.Fatal(err)
  case t := <-transfers:
    fmt.Printf("%s -> %s : %v", t.From, t.To, t.Tokens)
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.