Skip to content

Add a handler ​

A handler turns one log into one event on TRACKER.<transactionType>. Most handlers also decode the calldata of reverted calls, so consumers see failed attempts too.

How the tracker routes ​

For each block, the tracker reads every receipt.

  • Log from a tracked address. The handler registered for the log's first topic (topic0) runs. A topic has one handler. Registering it again replaces the first one.
  • Reverted transaction to a tracked address. The handler registered for the calldata's 4-byte selector runs. Routes registered for one contract win over global ones.
  • Contract created by a tracked address. The contract creation handler runs.

Logs from untracked addresses are skipped. See Track the contract.

Write the handler ​

A handler is a function that returns a closure. The closure decodes the log with w3, builds an event.Event, and passes it to the callback, which publishes it. This handler for a log and its reverted call is based on internal/handler/token_burn.go:

go
package handler

import (
	"context"
	"math/big"

	"github.com/cosmo-local-credit/eth-tracker/pkg/event"
	"github.com/cosmo-local-credit/eth-tracker/pkg/router"
	"github.com/ethereum/go-ethereum/common"
	"github.com/lmittmann/w3"
)

const burnEventName = "TOKEN_BURN"

var (
	tokenBurnEvent = w3.MustNewEvent("Burn(address indexed _tokenBurner, uint256 _value)")
	tokenBurnToSig = w3.MustNewFunc("burn(uint256)", "bool")
)

func HandleTokenBurnLog() router.LogHandlerFunc {
	return func(ctx context.Context, lp router.LogPayload, c router.Callback) error {
		var (
			tokenBurner common.Address
			value       big.Int
		)

		if err := tokenBurnEvent.DecodeArgs(lp.Log, &tokenBurner, &value); err != nil {
			return err
		}

		return c(ctx, event.Event{
			Index:           lp.Log.Index,
			Block:           lp.Log.BlockNumber,
			ContractAddress: lp.Log.Address.Hex(),
			Success:         true,
			Timestamp:       lp.Timestamp,
			TxHash:          lp.Log.TxHash.Hex(),
			TxType:          burnEventName,
			Payload: map[string]any{
				"tokenBurner": tokenBurner.Hex(),
				"value":       value.String(),
			},
		})
	}
}

func HandleTokenBurnInputData() router.InputDataHandlerFunc {
	return func(ctx context.Context, idp router.InputDataPayload, c router.Callback) error {
		var value big.Int

		if err := tokenBurnToSig.DecodeArgs(w3.B(idp.InputData), &value); err != nil {
			return err
		}

		return c(ctx, event.Event{
			Block:           idp.Block,
			ContractAddress: idp.ContractAddress,
			Success:         false,
			Timestamp:       idp.Timestamp,
			TxHash:          idp.TxHash,
			TxType:          burnEventName,
			Payload: map[string]any{
				"tokenBurner": idp.From,
				"value":       value.String(),
			},
		})
	}
}

Follow these rules:

  • TxType becomes the subject, so use upper snake case with no dots.
  • Write amounts as decimal strings and addresses with .Hex(). Consumers parse the payload as JSON.
  • Publish at most one event per log. JetStream keys messages by <txHash>:<index>, so a second event for the same log is dropped as a duplicate.
  • An error fails the whole block. The block is retried, then sent to the dead-letter queue. If a log might not decode, for example when two contracts emit the same signature with different indexed arguments, check len(lp.Log.Topics) and branch, or return nil.
  • A block can be processed more than once. Keep side effects safe to repeat.
  • In the reverted-call handler, set Success: false and take the actor from idp.From. Fill fields that only the log carries with zero values.

If the handler needs the tracked address list, take *HandlerContainer as a parameter, as HandleIndexAddLog(hc) does.

Register the route ​

Add the route in bootstrapEventRouter in cmd/service/router.go. A log route takes topic0. An input route takes the selector in lower case, without 0x.

go
router.RegisterLogRoute(w3.H("0xcc16f5dbb4873280815c1ee09dbd06736cffcc184412cf7a71a0fdb75d397ca5"), handler.HandleTokenBurnLog())
router.RegisterInputDataRoute("42966c68", handler.HandleTokenBurnInputData())

Get both values with Foundry:

sh
cast keccak "Burn(address,uint256)"
cast sig "burn(uint256)"

To use the event variable instead of a literal, export it and pass handler.TokenBurnEvent.Topic0. To route a selector for one contract only, use RegisterInputDataRouteForContract.

Track the contract ​

A handler only sees logs from tracked addresses. A contract is tracked if one of these holds:

  • The registries list it, or it belongs to a listed pool. See Tracked contracts.
  • It is in bootstrap.contracts or bootstrap.watchlist.
  • A handler adds it at runtime with hc.cache.Add(ctx, address.Hex()), as the index, contract creation and factory handlers do.

To find a new kind of contract through the registries or pools, extend both fullEnumerateAndCache and syncCacheFromChain in internal/cache/bootstrap.go. The first runs on a cold start, the second on later starts.

Test ​

Handler tests are in package handler and need no network. Build a router.LogPayload by hand and collect the published events with the collect helper from pool_swap_test.go:

go
func TestTokenBurnLog(t *testing.T) {
	var got []event.Event
	burner := common.HexToAddress("0x000000000000000000000000000000000000dEaD")

	lp := router.LogPayload{
		Log: &types.Log{
			Address: common.HexToAddress("0x0000000000000000000000000000000000000001"),
			Topics:  []common.Hash{tokenBurnEvent.Topic0, common.BytesToHash(burner.Bytes())},
			Data:    common.LeftPadBytes(big.NewInt(100).Bytes(), 32),
		},
	}

	if err := HandleTokenBurnLog()(context.Background(), lp, collect(&got)); err != nil {
		t.Fatal(err)
	}
	if len(got) != 1 || got[0].TxType != "TOKEN_BURN" || got[0].Payload["value"] != "100" {
		t.Fatalf("got %+v", got)
	}
}
sh
go test ./internal/handler/...

Document the event ​

Add a TRACKER.<TX_TYPE> section with the payload to docs/NATS.md. clc-core, ETH Indexer and clc-app-notifications read payloads by key, so treat the keys as a contract. No stream change is needed, because the TRACKER stream accepts TRACKER.*.

To store the new event, see Add a handler for ETH Indexer.