Add a handler
This page adds a handler that stores TRACKER.TOKEN_APPROVE events, which the indexer drops today. The tracker publishes them with this payload:
{ "owner": "0x...", "spender": "0x...", "value": "1000000" }Check the payload keys for other subjects in the tracker's NATS.md. If the tracker does not publish the event yet, add a tracker handler first.
How the indexer routes
cmd/service/router.go maps each subject to a list of handlers.
- All handlers for a subject run at the same time. The event is acknowledged only if all of them return
nil. - If any handler returns an error, the event is redelivered and every handler for the subject runs again. Handlers must be safe to repeat.
RegisterRoutereplaces the handlers for a subject. Register all handlers for a subject in one call.- A panic stops the process, and the event is redelivered on restart. Check payload types instead of asserting them.
1. Add a migration
Create a migration with the next free number, such as migrations/007_token_approve.sql. Migrations run in number order at startup, and the numbers must have no gaps.
CREATE TABLE IF NOT EXISTS token_approve (
id INT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tx_id INT REFERENCES tx(id),
owner_address VARCHAR(42) NOT NULL,
spender_address VARCHAR(42) NOT NULL,
approve_value NUMERIC NOT NULL,
contract_address VARCHAR(42) NOT NULL,
log_index BIGINT NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS idx_token_approve_tx_id ON token_approve(tx_id);
CREATE UNIQUE INDEX IF NOT EXISTS idx_token_approve_unique
ON token_approve(tx_id, log_index);The unique index makes a redelivered event a no-op. Leave table names unqualified, so the indexer works in any schema.
2. Add the query
Add a named query to queries.sql. It upserts the tx row and inserts the event in one statement.
--name: insert-token-approve
-- $1: tx_hash
-- $2: block_number
-- $3: date_block
-- $4: success
-- $5: owner_address
-- $6: spender_address
-- $7: approve_value
-- $8: contract_address
-- $9: log_index
WITH upsert_tx AS (
INSERT INTO tx(tx_hash, block_number, date_block, success)
VALUES($1, $2, $3, $4)
ON CONFLICT (tx_hash) DO UPDATE SET tx_hash = EXCLUDED.tx_hash
RETURNING id
)
INSERT INTO token_approve(tx_id, owner_address, spender_address, approve_value, contract_address, log_index)
SELECT id, $5, $6, $7, $8, $9 FROM upsert_tx
ON CONFLICT DO NOTHING--name: starts a query. The loader joins the lines of a query into one line, so don't put a comment at the end of a SQL line.
3. Add the store method
In internal/store/pg.go, add a field to the queries struct. The tag matches the query name, and startup fails if the query is missing.
InsertTokenApprove string `query:"insert-token-approve"`Add the method below the other inserts:
func (pg *Pg) InsertTokenApprove(ctx context.Context, eventPayload event.Event) error {
_, err := pg.db.Exec(
ctx,
pg.queries.InsertTokenApprove,
eventPayload.TxHash,
eventPayload.Block,
time.Unix(int64(eventPayload.Timestamp), 0).UTC(),
eventPayload.Success,
eventPayload.Payload["owner"].(string),
eventPayload.Payload["spender"].(string),
eventPayload.Payload["value"].(string),
eventPayload.ContractAddress,
int64(eventPayload.Index),
)
return err
}Add it to the Store interface in internal/store/store.go:
InsertTokenApprove(context.Context, event.Event) error4. Add the handler
Create internal/handler/token_approve.go. The handler checks the payload before the store reads it. It skips an event with a missing field, because redelivery would never fix it.
package handler
import (
"context"
"github.com/cosmo-local-credit/eth-tracker/pkg/event"
)
func (h *Handler) IndexTokenApprove(ctx context.Context, event event.Event) error {
for _, key := range []string{"owner", "spender", "value"} {
if _, ok := event.Payload[key].(string); !ok {
h.logg.Warn("skipping token approve with missing field", "tx", event.TxHash, "field", key)
return nil
}
}
return h.store.InsertTokenApprove(ctx, event)
}A handler that needs the chain can use h.chainProvider. internal/handler/faucet_give.go reads a balance this way.
5. Register the route
In bootstrapRouter in cmd/service/router.go:
router.RegisterRoute(
"TRACKER.TOKEN_APPROVE",
handlerContainer.IndexTokenApprove,
)6. Run it
Start the indexer. The log shows migrations ran successfully, and approvals start to arrive:
SELECT t.block_number, a.owner_address, a.spender_address, a.approve_value
FROM token_approve a
JOIN tx t ON t.id = a.tx_id
ORDER BY t.block_number DESC
LIMIT 10;The Docker image includes migrations/ and queries.sql, so rebuild it after you change them.
The repository has no tests yet. Store is an interface, so a fake store can test a handler without a database.