diff --git a/cmd/ternchain/scan_test.go b/cmd/ternchain/scan_test.go
new file mode 100644
index 0000000..e269293
--- /dev/null
+++ b/cmd/ternchain/scan_test.go
@@ -0,0 +1,129 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "path/filepath"
+ "testing"
+
+ netscan "github.com/nenkoru/tern/internal/scan"
+)
+
+// The scanner (internal/scan, examples/scanner) reads a network's names,
+// cards, payments, locks, swaps, claims and mail volume from its events alone,
+// and a second run picks up only what is new.
+func TestScanNetwork(t *testing.T) {
+ w := newWorld(t)
+ alice, _ := w.owner("alice")
+ bob, _ := w.owner("bob")
+ carol, _ := w.owner("carol")
+ ai := w.agent(alice, "ai", coins(3), `{"free_pay":"0.3"}`)
+ w.must(alice.deposit(coins(10)))
+ w.must(bob.deposit(coins(10)))
+ w.must(alice.setCard(`{"offer":"proofreading"}`))
+ w.must(alice.pay("bob", coins(1.5), "thanks"))
+
+ // An escrow ruled 70/30, and one left open.
+ open := func(args ...string) uint64 {
+ m := lockOut(t, func() error { return runLockOpen(alice, args, lockFlags{prim: primFlags{days: 30}}) })
+ return uint64(m["lock"].(float64))
+ }
+ esc := open("escrow", "bob", "carol", "1", "translate", "the", "site")
+ lockOut(t, func() error { return runLockDecide(carol, []string{fmt.Sprint(esc), "7000", "partly", "done"}) })
+ lockOut(t, func() error { return runLockSettle(bob, []string{fmt.Sprint(esc)}) })
+ pending := open("escrow", "bob", "carol", "0.5", "logo")
+
+ w.must(alice.attest("bob", "review", "on time", 0))
+ if _, err := ai.send(SendOpts{To: "alice", Intent: "inform", Text: "hello from your agent"}); err != nil {
+ t.Fatal(err)
+ }
+
+ net := netscan.Net{Network: "test", ChainID: w.ch.chainID.Int64(), Contracts: w.ch.dep.Contracts, Block: w.ch.dep.Block, Schema: w.ch.dep.Schema}
+ if net.Schema == "" {
+ net.Schema = alice.schema().Hex()
+ }
+ cache := filepath.Join(t.TempDir(), "scan.json")
+ ctx := context.Background()
+ s := netscan.Load(cache, net)
+ update := func() {
+ t.Helper()
+ if err := s.Update(ctx, w.sim.Client(), net, netscan.Options{Save: func(s *netscan.State) error { return s.Save(cache) }}); err != nil {
+ t.Fatal(err)
+ }
+ }
+ update()
+
+ if n := s.Names["alice"]; n == nil || n.Kind != "owner" || n.Card != `{"offer":"proofreading"}` || len(n.Agents) != 1 || n.Agents[0] != "ai.alice" {
+ t.Fatalf("alice: %+v", n)
+ }
+ if a := s.Names["ai.alice"]; a == nil || a.Kind != "agent" || a.Owner != "alice" || a.Limits[netscan.Coin] != coins(3).String() {
+ t.Fatalf("ai.alice: %+v", a)
+ }
+ var paid bool
+ for _, p := range s.Payments {
+ if p.From == "alice" && p.To == "bob" && p.Amount == "1.5" && p.Token == netscan.Coin {
+ paid = true
+ }
+ }
+ if !paid {
+ t.Fatalf("alice's payment to bob is missing: %+v", s.Payments)
+ }
+ l := lockByID(s, esc)
+ if l == nil || l.Kind != "escrow" || l.Decider != "carol" || l.From != "alice" || l.Payee != "bob" || l.Status != "split" ||
+ l.Paid != "0.7" || l.Refunded != "0.3" {
+ t.Fatalf("the ruled escrow: %+v", l)
+ }
+ if l := lockByID(s, pending); l == nil || l.Status != "open" || l.Total != "0.5" {
+ t.Fatalf("the open escrow: %+v", l)
+ }
+ var reviewed bool
+ for _, c := range s.Claims {
+ if c.Attester == "alice" && c.Subject == "bob" && c.Kind == "review" && c.Data == "on time" {
+ reviewed = true
+ }
+ }
+ if !reviewed {
+ t.Fatalf("alice's claim about bob is missing: %+v", s.Claims)
+ }
+ if mailCount(s) == 0 {
+ t.Fatal("no mail counted")
+ }
+
+ // A second run from the cache adds only what is new: an item sold for coins (a swap).
+ before := len(s.Payments) + len(s.Locks)
+ sword, err := alice.createItem("ipfs://sword.json", 10, false)
+ w.must(err)
+ w.must(alice.mintItem(sword, "alice", 2))
+ offer, err := alice.offerItem(sword, 1, coins(2), "", "")
+ w.must(err)
+ _, err = bob.buyItem(offer)
+ w.must(err)
+ s = netscan.Load(cache, net)
+ update()
+ if len(s.Swaps) != 1 {
+ t.Fatalf("swaps: %+v", s.Swaps)
+ }
+ item, coin := lockByID(s, s.Swaps[0].Offer), lockByID(s, s.Swaps[0].Answer)
+ if item == nil || coin == nil || item.Item != fmt.Sprint(sword) || item.Total != "1" || coin.Total != "2" || item.Status != "paid" || coin.Status != "paid" {
+ t.Fatalf("the swap's locks: %+v %+v", item, coin)
+ }
+ if got := len(s.Payments) + len(s.Locks); got != before+2 {
+ t.Fatalf("the second run counted %d new payments and locks, want 2 (the swap's locks)", got-before)
+ }
+}
+
+func lockByID(s *netscan.State, id uint64) *netscan.Lock {
+ for _, l := range s.Locks {
+ if l.ID == id {
+ return l
+ }
+ }
+ return nil
+}
+
+func mailCount(s *netscan.State) (n uint64) {
+ for _, m := range s.Mail {
+ n += m.Envelopes
+ }
+ return n
+}
diff --git a/examples/scanner/README.md b/examples/scanner/README.md
new file mode 100644
index 0000000..0e73838
--- /dev/null
+++ b/examples/scanner/README.md
@@ -0,0 +1,68 @@
+# Scanner: what is happening on the network
+
+A block explorer shows transactions and addresses. This shows tern: who has a name and which agents, what their cards offer, who paid whom, which deals are open and how the closed ones ended, what was swapped and at what price, who said what about whom, and how much mail goes through.
+
+It only reads the chain's public events (and a few view calls): no key, no name, no faucet, nothing sent. Mail is sealed, so it counts envelopes and bytes per day and nothing else.
+
+Built from: the events of Registry, Bank, SwapCondition, EAS and Inbox, the ABIs the binary already embeds, and `net.json`. The code is `internal/scan` (the scan) and `main.go` here (the views). No new contracts.
+
+## Try it
+
+From the repository's root:
+
+```sh
+go run ./examples/scanner
+```
+
+The first run reads the network from the block its contracts were deployed in, 10,000 blocks per request (`log_range` in `net.json`), and keeps what it read in your cache directory (`ternscan/`). Later runs read only the new blocks. An interrupted scan goes on where it stopped. A request that fails (public RPCs drop one now and then) is tried again a few times; an RPC that keeps failing is replaced by the next one in `net.json` (`rpcs`), which goes on from the last block read. `--rpc URL` uses that one only.
+
+```text
+scanner [COMMAND] [flags]
+
+ (none) the summary
+ names every name: owners, their agents, cards
+ name NAME one name: its agents, card, payments, deals, claims
+ deals every lock (escrow, bond, swap, subscription…) and how it ended
+ payments every payment
+ swaps swaps, with the price when one side is money
+ claims claims (reviews, ratings, rulings…)
+ mail envelopes and bytes per day
+ serve a web page with all of it, scanned again every --every
+```
+
+Flags: `--net FILE` (default `$TERNCHAIN_NET`, then `~/tern/net.json`, then `networks/tern-base-sepolia-1/net.json`), `--rpc URL`, `--json`, `--offline` (only the cache), `--limit N` (rows, newest first; default 50, 0 for all), `--confirmations N` (stay N blocks behind the head; default 3), `--cache DIR`, and for `serve`: `--listen ADDR` (default `127.0.0.1:8080`) and `--every D` (default `1m`).
+
+`--json` prints the same thing for programs. With no command it prints everything scanned: names, payments, locks, swaps, claims, mail per day and the tokens seen. Amounts are given in whole units and, in the `*_raw` fields, as integers in the token's smallest unit.
+
+## The web page
+
+```sh
+go run ./examples/scanner serve
+```
+
+Open http://127.0.0.1:8080/. One page, nothing loaded from elsewhere: an overview (counts, recent activity, mail per day), then names, deals, payments, swaps, claims and mail, each filterable. A name links to its page (`#name=alice`): its agents, card, deals, payments and claims. The server reads new blocks every `--every` and the page fetches them; `--offline` serves the cache as it is. If the chain can't be read, the page keeps showing the cache and says why.
+
+The page fetches `/state.json`: the same as `--json`, plus `order` (owners, each followed by its agents), `swap_rows` (both sides and the price) and `every_seconds`.
+
+Everything on the page was written by someone on the network (names, cards, claims). The page puts it in as text, never as markup, and its Content-Security-Policy lets nothing load or run from elsewhere. It listens on 127.0.0.1 by default; put it behind a reverse proxy to share it.
+
+## What it reads, and what it can't tell
+
+| Shown | From |
+|---|---|
+| names, agents, agents' daily limits, revocations, cards | `Registry`: `OwnerRegistered`, `AgentGranted`, `AgentRevoked`, `CardSet`; `Bank`: `TokenLimitSet` |
+| payments | `Bank`: `Paid`, `TokenPaid` |
+| deals | `Bank`: `Locked` (its kind from the condition and, for `AttestationCondition`, the demand: escrow, bond, bounty; a lock held by `TernJobs` is an ERC-8183 job), `Claimed`, `Released`, `Refunded`, `GivenBack`; the token and item from `Bank.locks` and `Bank.itemOf` |
+| swaps | `SwapCondition`: `Swapped`, with both sides' locks |
+| claims | `EAS`: `Attested` with tern's claim schema, read with `getAttestation`; `Revoked` |
+| mail | `Inbox`: `Posted`, `Committed` (envelopes and bytes) |
+
+- **Who is behind a payment.** Payments and locks name owner and agent ids, so they show as names. A split or a deal subject shows as a short hash. A claim's issuer is an address; it shows as a name when that address is a name's controller or agent key.
+- **Times** are interpolated between each range's first and last block: exact on Base (a block every 2 seconds), close elsewhere.
+- **"past its refund time"** is a lock nobody settled or refunded yet after its refund time: its payer can take it back.
+- **Mail volume** counts envelopes as the Inbox saw them, whoever sent them. Group posts, receipts and votes are envelopes too.
+
+## Make it yours
+
+- **A price feed.** `swaps --json` gives every settled swap with both sides. A price for a token or an item is an average over a window of these, from distinct owners, above a minimum volume (one trade with yourself must not move it).
+- **Alerts.** Run it from cron with `--json` and compare: a new card with a word you care about, a deal of yours past its refund time, a claim about you.
diff --git a/examples/scanner/index.html b/examples/scanner/index.html
new file mode 100644
index 0000000..eec8df4
--- /dev/null
+++ b/examples/scanner/index.html
@@ -0,0 +1,348 @@
+
+
+
+
+
+tern scanner
+
+
+
+
+
tern scanner
+ loading…
+
+
+
+
+
+
+
+
+
+
+
diff --git a/examples/scanner/main.go b/examples/scanner/main.go
new file mode 100644
index 0000000..3fe4b60
--- /dev/null
+++ b/examples/scanner/main.go
@@ -0,0 +1,681 @@
+// Command scanner shows what is happening on a tern network: names and their
+// agents, cards, payments, deals and how they ended, swaps, claims and the
+// volume of mail, read from the chain's public events (internal/scan). It
+// only reads: no key, no transactions. See README.md.
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "io"
+ "math/big"
+ "net/url"
+ "os"
+ "os/signal"
+ "path/filepath"
+ "slices"
+ "sort"
+ "strings"
+ "text/tabwriter"
+ "time"
+
+ "github.com/ethereum/go-ethereum/ethclient"
+
+ "github.com/nenkoru/tern/internal/scan"
+)
+
+const usage = `scanner [COMMAND] [flags]
+
+ (none) the summary
+ names every name: owners, their agents, cards
+ name NAME one name: its agents, card, payments, deals, claims
+ deals every lock (escrow, bond, swap, subscription…) and how it ended
+ payments every payment
+ swaps swaps, with the price when one side is money
+ claims claims (reviews, ratings, rulings…)
+ mail envelopes and bytes per day (mail is sealed: only its volume shows)
+ serve a web page with all of it, scanned again every --every
+
+flags:
+ --net FILE the network file (default $TERNCHAIN_NET, ~/tern/net.json, or networks/tern-base-sepolia-1/net.json)
+ --rpc URL another RPC than the network file's
+ --json the same as JSON (with no command: everything scanned)
+ --offline show the cache, don't read the chain
+ --cache DIR where the scan is kept (default the user cache directory, ternscan/)
+ --confirmations N stay N blocks behind the head (default 3)
+ --limit N at most N rows, newest first (default 50; 0: all)
+ --listen ADDR serve: where (default 127.0.0.1:8080)
+ --every D serve: how often to read new blocks (default 1m)
+`
+
+type opts struct {
+ net, rpc, cache string
+ json, offline bool
+ confirmations uint64
+ limit int
+ listen string
+ every time.Duration
+ command, argument string
+}
+
+func main() {
+ o, err := parseArgs(os.Args[1:])
+ if err != nil {
+ fmt.Fprint(os.Stderr, err, "\n\n", usage)
+ os.Exit(2)
+ }
+ if err := run(o, os.Stdout); err != nil {
+ fmt.Fprintln(os.Stderr, "scanner:", err)
+ os.Exit(1)
+ }
+}
+
+// parseArgs takes flags before or after the command.
+func parseArgs(args []string) (opts, error) {
+ var o opts
+ fs := flag.NewFlagSet("scanner", flag.ContinueOnError)
+ fs.SetOutput(io.Discard)
+ fs.StringVar(&o.net, "net", "", "")
+ fs.StringVar(&o.rpc, "rpc", "", "")
+ fs.StringVar(&o.cache, "cache", "", "")
+ fs.BoolVar(&o.json, "json", false, "")
+ fs.BoolVar(&o.offline, "offline", false, "")
+ fs.Uint64Var(&o.confirmations, "confirmations", 3, "")
+ fs.IntVar(&o.limit, "limit", 50, "")
+ fs.StringVar(&o.listen, "listen", "127.0.0.1:8080", "")
+ fs.DurationVar(&o.every, "every", time.Minute, "")
+ var pos []string
+ for {
+ if err := fs.Parse(args); err != nil {
+ if err == flag.ErrHelp {
+ fmt.Print(usage)
+ os.Exit(0)
+ }
+ return o, err
+ }
+ if fs.NArg() == 0 {
+ break
+ }
+ pos, args = append(pos, fs.Arg(0)), fs.Args()[1:]
+ }
+ if len(pos) > 0 {
+ o.command = pos[0]
+ }
+ if len(pos) > 1 {
+ o.argument = pos[1]
+ }
+ switch o.command {
+ case "", "names", "deals", "payments", "swaps", "claims", "mail", "serve":
+ if len(pos) > 1 {
+ return o, fmt.Errorf("%s takes no argument", o.command)
+ }
+ case "name":
+ if len(pos) != 2 {
+ return o, fmt.Errorf("name takes one NAME")
+ }
+ case "help":
+ fmt.Print(usage)
+ os.Exit(0)
+ default:
+ return o, fmt.Errorf("unknown command %q", o.command)
+ }
+ return o, nil
+}
+
+func netPath(flagged string) (string, error) {
+ if flagged != "" {
+ return flagged, nil
+ }
+ if p := os.Getenv("TERNCHAIN_NET"); p != "" {
+ return p, nil
+ }
+ if home, err := os.UserHomeDir(); err == nil {
+ if p := filepath.Join(home, "tern", "net.json"); exists(p) {
+ return p, nil
+ }
+ }
+ if p := filepath.Join("networks", "tern-base-sepolia-1", "net.json"); exists(p) {
+ return p, nil
+ }
+ return "", scan.ErrNoNet
+}
+
+func exists(p string) bool { _, err := os.Stat(p); return err == nil }
+
+func run(o opts, w io.Writer) error {
+ p, err := netPath(o.net)
+ if err != nil {
+ return err
+ }
+ n, err := scan.ReadNet(p)
+ if err != nil {
+ return err
+ }
+ if o.rpc != "" {
+ n.RPC, n.RPCs = o.rpc, nil // that one only
+ }
+ dir := o.cache
+ if dir == "" {
+ if dir, err = os.UserCacheDir(); err != nil {
+ return err
+ }
+ dir = filepath.Join(dir, "ternscan")
+ }
+ cache := filepath.Join(dir, fmt.Sprintf("%s-%d.json", orDefault(n.Network, "network"), n.ChainID))
+ s := scan.Load(cache, n)
+ ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
+ defer stop()
+ var stale error // serve: a failed first update, shown on the page while the cache is served
+ if !o.offline {
+ if err := update(ctx, s, n, cache, o.confirmations); err != nil {
+ if o.command != "serve" || s.ToTime == 0 || ctx.Err() != nil {
+ return err
+ }
+ fmt.Fprintln(os.Stderr, "scanner: update:", err, "(serving the cache; trying again every", o.every.String()+")")
+ stale = err
+ }
+ } else if s.ToTime == 0 {
+ return fmt.Errorf("nothing cached for %s yet: run once without --offline", n.Network)
+ }
+ if o.command == "serve" {
+ return serve(ctx, s, n, cache, o, stale)
+ }
+ return show(w, s, o)
+}
+
+// update reads new blocks through the network's rpc, and through its other
+// rpcs (net.json "rpcs") in turn when one keeps failing. Each range read is
+// saved, so the next rpc goes on where the last one stopped.
+func update(ctx context.Context, s *scan.State, n scan.Net, cache string, confirmations uint64) error {
+ var urls []string
+ for _, u := range append([]string{n.RPC}, n.RPCs...) {
+ if u != "" && !slices.Contains(urls, u) {
+ urls = append(urls, u)
+ }
+ }
+ if len(urls) == 0 {
+ return fmt.Errorf("the network file names no rpc: pass --rpc")
+ }
+ var err error
+ for i, u := range urls {
+ if err = updateFrom(ctx, s, n, u, cache, confirmations); err == nil || ctx.Err() != nil {
+ break
+ }
+ if i < len(urls)-1 {
+ fmt.Fprintf(os.Stderr, "scanner: %s: %v; trying %s\n", host(u), err, host(urls[i+1]))
+ }
+ }
+ if ctx.Err() != nil {
+ return fmt.Errorf("interrupted at block %d: the next run goes on from there", s.ToBlock)
+ }
+ return err
+}
+
+func host(u string) string {
+ if p, err := url.Parse(u); err == nil && p.Host != "" {
+ return p.Host
+ }
+ return u
+}
+
+func updateFrom(ctx context.Context, s *scan.State, n scan.Net, rpc, cache string, confirmations uint64) error {
+ c, err := ethclient.DialContext(ctx, rpc)
+ if err != nil {
+ return err
+ }
+ defer c.Close()
+ start, shown := time.Now(), false
+ err = s.Update(ctx, c, n, scan.Options{Confirmations: confirmations,
+ Save: func(s *scan.State) error { return s.Save(cache) },
+ Progress: func(from, to, head uint64) {
+ if time.Since(start) > 2*time.Second { // only for a scan that takes a while (the first one)
+ fmt.Fprintf(os.Stderr, "\rscanning block %d of %d (%d%%) ", to, head, 100*(to-n.Block+1)/(head-n.Block+1))
+ shown = true
+ }
+ }})
+ if shown {
+ fmt.Fprintln(os.Stderr)
+ }
+ return err
+}
+
+func show(w io.Writer, s *scan.State, o opts) error {
+ switch o.command {
+ case "":
+ if o.json {
+ return writeJSON(w, s)
+ }
+ summary(w, s)
+ case "names":
+ if o.json {
+ return writeJSON(w, s.Names)
+ }
+ names(w, s, sortedNames(s))
+ case "name":
+ return oneName(w, s, o)
+ case "deals":
+ ls := newest(s.Locks, o.limit)
+ if o.json {
+ return writeJSON(w, ls)
+ }
+ deals(w, s, ls)
+ case "payments":
+ ps := newest(s.Payments, o.limit)
+ if o.json {
+ return writeJSON(w, ps)
+ }
+ payments(w, s, ps)
+ case "swaps":
+ rows := swapRows(s, newest(s.Swaps, o.limit))
+ if o.json {
+ return writeJSON(w, rows)
+ }
+ swaps(w, rows)
+ case "claims":
+ cs := newest(s.Claims, o.limit)
+ if o.json {
+ return writeJSON(w, cs)
+ }
+ claims(w, cs)
+ case "mail":
+ if o.json {
+ return writeJSON(w, s.Mail)
+ }
+ mail(w, s)
+ }
+ return nil
+}
+
+// ---- the views
+
+func summary(w io.Writer, s *scan.State) {
+ fmt.Fprintf(w, "%s · blocks %d–%d · up to %s UTC\n\n", s.Network, s.FromBlock, s.ToBlock, time.Unix(s.ToTime, 0).UTC().Format("2006-01-02 15:04"))
+ var owners, agents, revoked, cards int
+ for _, n := range s.Names {
+ if n.Kind == "owner" {
+ owners++
+ } else {
+ agents++
+ if n.Revoked {
+ revoked++
+ }
+ }
+ if n.Card != "" {
+ cards++
+ }
+ }
+ t := tab(w)
+ fmt.Fprintf(t, "Names\t%d owners · %d agents (%d revoked) · %d cards\n", owners, agents, revoked, cards)
+ sums := map[string]*big.Int{}
+ for _, p := range s.Payments {
+ add(sums, p.Token, p.AmountRaw)
+ }
+ fmt.Fprintf(t, "Payments\t%d · %s\n", len(s.Payments), totals(s, sums))
+ status, kinds := map[string]int{}, map[string]int{}
+ for _, l := range s.Locks {
+ status[l.Status]++
+ kinds[l.Kind]++
+ }
+ fmt.Fprintf(t, "Deals\t%d open · %d past their refund time · %d paid · %d refunded · %d split\n",
+ status["open"]+status["partly paid"], status["refundable"], status["paid"], status["refunded"], status["split"])
+ if len(kinds) > 0 {
+ fmt.Fprintf(t, "\tby kind: %s\n", counts(kinds))
+ }
+ fmt.Fprintf(t, "Swaps\t%d\n", len(s.Swaps))
+ ck := map[string]int{}
+ for _, c := range s.Claims {
+ ck[c.Kind]++
+ }
+ fmt.Fprintf(t, "Claims\t%d", len(s.Claims))
+ if len(ck) > 0 {
+ fmt.Fprintf(t, " · %s", counts(ck))
+ }
+ fmt.Fprintln(t)
+ var env, bytes uint64
+ for _, m := range s.Mail {
+ env += m.Envelopes
+ bytes += m.Bytes
+ }
+ fmt.Fprintf(t, "Mail\t%d envelopes · %s · last 14 days %s\n", env, size(bytes), spark(s, 14))
+ t.Flush()
+}
+
+func names(w io.Writer, s *scan.State, ns []*scan.Name) {
+ t := tab(w)
+ fmt.Fprintln(t, "NAME\tKIND\tSINCE\tAGENTS / LIMIT\tCARD")
+ for _, n := range ns {
+ extra := strings.Join(n.Agents, ", ")
+ if n.Kind == "agent" {
+ extra = limits(s, n)
+ if n.Revoked {
+ extra = "revoked"
+ }
+ }
+ fmt.Fprintf(t, "%s\t%s\t%s\t%s\t%s\n", n.Name, n.Kind, scan.Day(n.Since), extra, cardLine(n.Card))
+ }
+ t.Flush()
+}
+
+func oneName(w io.Writer, s *scan.State, o opts) error {
+ n := s.Names[o.argument]
+ if n == nil {
+ return fmt.Errorf("no name %q on %s (as of block %d)", o.argument, s.Network, s.ToBlock)
+ }
+ me := func(x string) bool { return x == n.Name }
+ var ps []*scan.Payment
+ for _, p := range s.Payments {
+ if me(p.From) || me(p.To) {
+ ps = append(ps, p)
+ }
+ }
+ var ls []*scan.Lock
+ for _, l := range s.Locks {
+ if me(l.From) || me(l.Payee) || me(l.Decider) {
+ ls = append(ls, l)
+ }
+ }
+ var cs []*scan.Claim
+ for _, c := range s.Claims {
+ if me(c.Attester) || me(c.Subject) {
+ cs = append(cs, c)
+ }
+ }
+ ps, ls, cs = newest(ps, o.limit), newest(ls, o.limit), newest(cs, o.limit)
+ if o.json {
+ return writeJSON(w, map[string]any{"name": n, "payments": ps, "deals": ls, "claims": cs})
+ }
+ fmt.Fprintf(w, "%s · %s since %s (block %d)\n", n.Name, n.Kind, scan.Day(n.Since), n.Block)
+ if n.Owner != "" {
+ fmt.Fprintf(w, "owner: %s · limit: %s", n.Owner, limits(s, n))
+ if n.Revoked {
+ fmt.Fprint(w, " · revoked")
+ }
+ fmt.Fprintln(w)
+ }
+ if len(n.Agents) > 0 {
+ fmt.Fprintf(w, "agents: %s\n", strings.Join(n.Agents, ", "))
+ }
+ if n.Card != "" {
+ fmt.Fprintf(w, "card: %s\n", n.Card)
+ }
+ section := func(title string, k int, f func()) {
+ fmt.Fprintf(w, "\n%s (%d)\n", title, k)
+ if k > 0 {
+ f()
+ }
+ }
+ section("Payments", len(ps), func() { payments(w, s, ps) })
+ section("Deals", len(ls), func() { deals(w, s, ls) })
+ section("Claims", len(cs), func() { claims(w, cs) })
+ return nil
+}
+
+func deals(w io.Writer, s *scan.State, ls []*scan.Lock) {
+ t := tab(w)
+ fmt.Fprintln(t, "LOCK\tOPENED\tKIND\tFROM → TO\tAMOUNT\tDECIDER\tSTATUS")
+ for _, l := range ls {
+ to := orDefault(l.Payee, "(open)")
+ st := l.Status
+ switch st {
+ case "split", "partly paid":
+ st += fmt.Sprintf(" (%s paid, %s back)", l.Paid, l.Refunded)
+ case "open":
+ st += " until " + scan.Day(l.RefundAfter)
+ }
+ fmt.Fprintf(t, "#%d\t%s\t%s\t%s → %s\t%s\t%s\t%s\n", l.ID, scan.Day(l.Time), l.Kind, l.From, to, lockAmount(s, l),
+ orDefault(l.Decider, "-"), st)
+ }
+ t.Flush()
+}
+
+func payments(w io.Writer, s *scan.State, ps []*scan.Payment) {
+ t := tab(w)
+ fmt.Fprintln(t, "DAY\tFROM → TO\tAMOUNT")
+ for _, p := range ps {
+ fmt.Fprintf(t, "%s\t%s → %s\t%s %s\n", scan.Day(p.Time), p.From, p.To, p.Amount, s.Symbol(p.Token))
+ }
+ t.Flush()
+}
+
+type swapRow struct {
+ Day string `json:"day"`
+ Offer uint64 `json:"offer_lock"`
+ Answer uint64 `json:"answer_lock"`
+ A string `json:"a"` // name: what
+ B string `json:"b"`
+ Price string `json:"price,omitempty"` // of one unit of the side that isn't money
+}
+
+func swapRows(s *scan.State, sw []*scan.Swap) []swapRow {
+ byID := map[uint64]*scan.Lock{}
+ for _, l := range s.Locks {
+ byID[l.ID] = l
+ }
+ var out []swapRow
+ for _, x := range sw {
+ a, b := byID[x.Offer], byID[x.Answer]
+ r := swapRow{Day: scan.Day(x.Time), Offer: x.Offer, Answer: x.Answer}
+ if a == nil || b == nil {
+ out = append(out, r)
+ continue
+ }
+ r.A, r.B = a.From+": "+lockAmount(s, a), b.From+": "+lockAmount(s, b)
+ // The price: money per unit of the other side. An item is never the
+ // money; between two tokens, the answer (the buyer's side) is.
+ goods, money := a, b
+ if a.Item == "" && b.Item != "" {
+ goods, money = b, a
+ }
+ if money.Item == "" && goods.Total != "0" && (goods.Item != "" || goods.Token != money.Token) {
+ r.Price = ratio(money.Total, goods.Total) + " " + s.Symbol(money.Token) + " per " + unit(s, goods)
+ }
+ out = append(out, r)
+ }
+ return out
+}
+
+func swaps(w io.Writer, rows []swapRow) {
+ t := tab(w)
+ fmt.Fprintln(t, "DAY\tLOCKS\tGIVES\tGIVES\tPRICE")
+ for _, r := range rows {
+ fmt.Fprintf(t, "%s\t#%d ↔ #%d\t%s\t%s\t%s\n", r.Day, r.Offer, r.Answer, r.A, r.B, orDefault(r.Price, "-"))
+ }
+ t.Flush()
+}
+
+func claims(w io.Writer, cs []*scan.Claim) {
+ t := tab(w)
+ fmt.Fprintln(t, "DAY\tBY\tABOUT\tKIND\tSCORE\tDATA")
+ for _, c := range cs {
+ data := strings.ReplaceAll(c.Data, "\n", " ")
+ if c.Revoked {
+ data = "(revoked) " + data
+ }
+ fmt.Fprintf(t, "%s\t%s\t%s\t%s\t%d\t%s\n", scan.Day(c.Time), c.Attester, c.Subject, c.Kind, c.Score, clip(data, 60))
+ }
+ t.Flush()
+}
+
+func mail(w io.Writer, s *scan.State) {
+ days := make([]string, 0, len(s.Mail))
+ for d := range s.Mail {
+ days = append(days, d)
+ }
+ sort.Sort(sort.Reverse(sort.StringSlice(days)))
+ t := tab(w)
+ fmt.Fprintln(t, "DAY\tENVELOPES\tBYTES")
+ for _, d := range days {
+ fmt.Fprintf(t, "%s\t%d\t%s\n", d, s.Mail[d].Envelopes, size(s.Mail[d].Bytes))
+ }
+ t.Flush()
+}
+
+// ---- helpers
+
+func tab(w io.Writer) *tabwriter.Writer { return tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) }
+
+func writeJSON(w io.Writer, v any) error {
+ e := json.NewEncoder(w)
+ e.SetIndent("", " ")
+ return e.Encode(v)
+}
+
+// newest: the last n of a list in chain order, newest first (n 0: all).
+func newest[T any](xs []T, n int) []T {
+ out := make([]T, 0, len(xs))
+ for i := len(xs) - 1; i >= 0 && (n <= 0 || len(out) < n); i-- {
+ out = append(out, xs[i])
+ }
+ return out
+}
+
+func sortedNames(s *scan.State) []*scan.Name {
+ // Owners in the order they came, each followed by its agents.
+ var owners []*scan.Name
+ for _, n := range s.Names {
+ if n.Kind == "owner" {
+ owners = append(owners, n)
+ }
+ }
+ sort.Slice(owners, func(i, j int) bool { return owners[i].Block < owners[j].Block })
+ var out []*scan.Name
+ for _, o := range owners {
+ out = append(out, o)
+ for _, a := range o.Agents {
+ if n := s.Names[a]; n != nil {
+ out = append(out, n)
+ }
+ }
+ }
+ return out
+}
+
+func limits(s *scan.State, n *scan.Name) string {
+ var parts []string
+ for tok, raw := range n.Limits {
+ parts = append(parts, s.Fmt(tok, raw)+" "+s.Symbol(tok)+"/day")
+ }
+ sort.Strings(parts)
+ return orDefault(strings.Join(parts, ", "), "-")
+}
+
+// cardLine: a card's "offer", or its first characters.
+func cardLine(card string) string {
+ var m map[string]any
+ if json.Unmarshal([]byte(card), &m) == nil {
+ if o, ok := m["offer"].(string); ok {
+ return clip(o, 50)
+ }
+ }
+ return clip(card, 50)
+}
+
+func lockAmount(s *scan.State, l *scan.Lock) string {
+ if l.Item != "" {
+ return l.Total + " × " + unit(s, l)
+ }
+ return l.Total + " " + s.Symbol(l.Token)
+}
+
+func unit(s *scan.State, l *scan.Lock) string {
+ if l.Item != "" {
+ return "item " + l.Item + " of " + s.Symbol(l.Token)
+ }
+ return s.Symbol(l.Token)
+}
+
+func ratio(a, b string) string {
+ x, ok1 := new(big.Rat).SetString(a)
+ y, ok2 := new(big.Rat).SetString(b)
+ if !ok1 || !ok2 || y.Sign() == 0 {
+ return "?"
+ }
+ out := new(big.Rat).Quo(x, y).FloatString(6)
+ return strings.TrimRight(strings.TrimRight(out, "0"), ".")
+}
+
+func add(m map[string]*big.Int, token, raw string) {
+ v, _ := new(big.Int).SetString(raw, 10)
+ if v == nil {
+ return
+ }
+ if m[token] == nil {
+ m[token] = new(big.Int)
+ }
+ m[token].Add(m[token], v)
+}
+
+func totals(s *scan.State, m map[string]*big.Int) string {
+ var parts []string
+ for tok, v := range m {
+ parts = append(parts, s.Fmt(tok, v.String())+" "+s.Symbol(tok))
+ }
+ sort.Strings(parts)
+ return orDefault(strings.Join(parts, " + "), "nothing")
+}
+
+func counts(m map[string]int) string {
+ ks := make([]string, 0, len(m))
+ for k := range m {
+ ks = append(ks, k)
+ }
+ sort.Slice(ks, func(i, j int) bool { return m[ks[i]] > m[ks[j]] || (m[ks[i]] == m[ks[j]] && ks[i] < ks[j]) })
+ var parts []string
+ for i, k := range ks {
+ if i == 6 {
+ parts = append(parts, "…")
+ break
+ }
+ parts = append(parts, fmt.Sprintf("%s %d", k, m[k]))
+ }
+ return strings.Join(parts, ", ")
+}
+
+// spark: envelopes per day for the last n days up to the scan's end.
+func spark(s *scan.State, n int) string {
+ bars := []rune("▁▂▃▄▅▆▇█")
+ end := time.Unix(s.ToTime, 0).UTC()
+ vals := make([]uint64, n)
+ var top uint64
+ for i := range vals {
+ if m := s.Mail[end.AddDate(0, 0, i-n+1).Format("2006-01-02")]; m != nil {
+ vals[i] = m.Envelopes
+ }
+ top = max(top, vals[i])
+ }
+ var b strings.Builder
+ for _, v := range vals {
+ if v == 0 {
+ b.WriteRune('·')
+ continue
+ }
+ b.WriteRune(bars[int(v*uint64(len(bars)-1)/max(top, 1))])
+ }
+ return b.String()
+}
+
+func size(b uint64) string {
+ switch {
+ case b >= 1<<20:
+ return fmt.Sprintf("%.1f MB", float64(b)/(1<<20))
+ case b >= 1<<10:
+ return fmt.Sprintf("%.1f kB", float64(b)/(1<<10))
+ }
+ return fmt.Sprintf("%d B", b)
+}
+
+func clip(s string, n int) string {
+ if r := []rune(s); len(r) > n {
+ return string(r[:n]) + "…"
+ }
+ return s
+}
+
+func orDefault(s, d string) string {
+ if s == "" {
+ return d
+ }
+ return s
+}
diff --git a/examples/scanner/web.go b/examples/scanner/web.go
new file mode 100644
index 0000000..434e938
--- /dev/null
+++ b/examples/scanner/web.go
@@ -0,0 +1,115 @@
+package main
+
+import (
+ "context"
+ _ "embed"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net"
+ "net/http"
+ "os"
+ "sync/atomic"
+ "time"
+
+ "github.com/nenkoru/tern/internal/scan"
+)
+
+// index.html: the whole page (styles and script inline, nothing from elsewhere).
+//
+//go:embed index.html
+var indexHTML []byte
+
+// page is what the page fetches: the scan, plus what the text views compute.
+type page struct {
+ *scan.State
+ Order []string `json:"order"` // names: owners in the order they came, each followed by its agents
+ SwapRow []swapRow `json:"swap_rows"`
+ Every int64 `json:"every_seconds"` // how often the server reads new blocks (0: never, --offline)
+ Error string `json:"error,omitempty"`
+}
+
+func pageOf(s *scan.State, every time.Duration, err error) []byte {
+ p := page{State: s, SwapRow: swapRows(s, newest(s.Swaps, 0)), Every: int64(every / time.Second)}
+ for _, n := range sortedNames(s) {
+ p.Order = append(p.Order, n.Name)
+ }
+ if err != nil {
+ p.Error = err.Error()
+ }
+ b, _ := json.Marshal(p)
+ return b
+}
+
+// handler serves the page and its data. Everything shown comes from the
+// chain, written by anyone: the page puts it in as text, never as markup,
+// and the policy below lets nothing load from elsewhere.
+func handler(data func() []byte) http.Handler {
+ mux := http.NewServeMux()
+ secure := func(w http.ResponseWriter) {
+ h := w.Header()
+ h.Set("Content-Security-Policy", "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'")
+ h.Set("X-Content-Type-Options", "nosniff")
+ h.Set("Referrer-Policy", "no-referrer")
+ }
+ mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
+ secure(w)
+ w.Header().Set("Content-Type", "text/html; charset=utf-8")
+ w.Write(indexHTML)
+ })
+ mux.HandleFunc("GET /state.json", func(w http.ResponseWriter, r *http.Request) {
+ secure(w)
+ w.Header().Set("Content-Type", "application/json")
+ w.Header().Set("Cache-Control", "no-store")
+ w.Write(data())
+ })
+ return mux
+}
+
+// serve: the page, with the scan read again every o.every (unless --offline).
+func serve(ctx context.Context, s *scan.State, n scan.Net, cache string, o opts, stale error) error {
+ every := o.every
+ if o.offline {
+ every = 0
+ } else if every < 5*time.Second {
+ every = 5 * time.Second
+ }
+ var cur atomic.Pointer[[]byte]
+ set := func(err error) { b := pageOf(s, every, err); cur.Store(&b) }
+ set(stale)
+ l, err := net.Listen("tcp", o.listen)
+ if err != nil {
+ return err
+ }
+ srv := &http.Server{Handler: handler(func() []byte { return *cur.Load() }), ReadHeaderTimeout: 10 * time.Second}
+ fmt.Fprintf(os.Stderr, "serving %s at http://%s/ (Ctrl-C to stop)\n", s.Network, l.Addr())
+ go func() {
+ <-ctx.Done()
+ sh, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ srv.Shutdown(sh)
+ }()
+ if every > 0 {
+ go func() {
+ t := time.NewTicker(every)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ }
+ // The scan is changed only here; the page reads the bytes made after each update.
+ err := update(ctx, s, n, cache, o.confirmations)
+ if err != nil && ctx.Err() == nil {
+ fmt.Fprintln(os.Stderr, "scanner: update:", err)
+ }
+ set(err)
+ }
+ }()
+ }
+ if err := srv.Serve(l); err != nil && !errors.Is(err, http.ErrServerClosed) {
+ return err
+ }
+ return nil
+}
diff --git a/examples/scanner/web_test.go b/examples/scanner/web_test.go
new file mode 100644
index 0000000..18874e3
--- /dev/null
+++ b/examples/scanner/web_test.go
@@ -0,0 +1,67 @@
+package main
+
+import (
+ "encoding/json"
+ "io"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/nenkoru/tern/internal/scan"
+)
+
+// The page and its data: the scan as JSON with the names' order and the swap
+// rows, and a policy that loads nothing from elsewhere.
+func TestServePage(t *testing.T) {
+ s := &scan.State{Network: "test", ToBlock: 7,
+ Names: map[string]*scan.Name{
+ "alice": {Name: "alice", Kind: "owner", Block: 1, Agents: []string{"ai.alice"}, Card: ``},
+ "ai.alice": {Name: "ai.alice", Kind: "agent", Owner: "alice", Block: 2},
+ "bob": {Name: "bob", Kind: "owner", Block: 3},
+ },
+ Locks: []*scan.Lock{{ID: 0, From: "alice", Item: "4", Token: "0xabc item", Total: "1"}, {ID: 1, From: "bob", Token: scan.Coin, Total: "2"}},
+ Swaps: []*scan.Swap{{Offer: 0, Answer: 1}},
+ Tokens: map[string]*scan.Token{scan.Coin: {Symbol: "coin", Decimals: 18}, "0xabc": {Symbol: "SWORD", Decimals: 0}},
+ }
+ srv := httptest.NewServer(handler(func() []byte { return pageOf(s, time.Minute, nil) }))
+ defer srv.Close()
+
+ r, err := srv.Client().Get(srv.URL + "/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ := io.ReadAll(r.Body)
+ if r.StatusCode != 200 || !strings.Contains(string(body), "tern scanner") ||
+ !strings.Contains(r.Header.Get("Content-Security-Policy"), "default-src 'none'") {
+ t.Fatalf("page: %d %q", r.StatusCode, r.Header.Get("Content-Security-Policy"))
+ }
+ if strings.Contains(string(body), "innerHTML") {
+ t.Fatal("the page puts chain data in as markup")
+ }
+
+ r, err = srv.Client().Get(srv.URL + "/state.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var p struct {
+ Network string `json:"network"`
+ Order []string `json:"order"`
+ Swaps []swapRow `json:"swap_rows"`
+ Every int64 `json:"every_seconds"`
+ Names map[string]any `json:"names"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
+ t.Fatal(err)
+ }
+ if p.Network != "test" || strings.Join(p.Order, ",") != "alice,ai.alice,bob" || p.Every != 60 || len(p.Names) != 3 {
+ t.Fatalf("state: %+v", p)
+ }
+ if len(p.Swaps) != 1 || p.Swaps[0].Price != "2 coin per item 4 of SWORD" {
+ t.Fatalf("swap rows: %+v", p.Swaps)
+ }
+
+ if r, _ := srv.Client().Get(srv.URL + "/other"); r.StatusCode != 404 {
+ t.Fatalf("an unknown path: %d", r.StatusCode)
+ }
+}
diff --git a/internal/scan/scan.go b/internal/scan/scan.go
new file mode 100644
index 0000000..8bdb447
--- /dev/null
+++ b/internal/scan/scan.go
@@ -0,0 +1,916 @@
+// Package scan reads a tern network's public events into one summary: names
+// and agents, cards, payments, locks and how they ended, swaps, claims and the
+// volume of mail. It only reads (eth_getLogs and a few view calls), needs no
+// key, and resumes from where its last run stopped. Mail stays sealed: it
+// counts envelopes and bytes, nothing more. examples/scanner is its command.
+package scan
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "math/big"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/ethereum/go-ethereum"
+ "github.com/ethereum/go-ethereum/accounts/abi"
+ "github.com/ethereum/go-ethereum/common"
+ "github.com/ethereum/go-ethereum/core/types"
+ "github.com/ethereum/go-ethereum/crypto"
+
+ "github.com/nenkoru/tern"
+)
+
+// Backend is what a scan needs from a chain connection (ethclient.Client and
+// a simulated backend's client both are one).
+type Backend interface {
+ ethereum.LogFilterer
+ ethereum.BlockNumberReader
+ HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error)
+ CallContract(ctx context.Context, msg ethereum.CallMsg, block *big.Int) ([]byte, error)
+}
+
+// Net is the part of a network file (net.json) a scan uses.
+type Net struct {
+ Network string `json:"network"`
+ RPC string `json:"rpc"`
+ RPCs []string `json:"rpcs"` // the rpc and others for the same chain
+ ChainID int64 `json:"chain_id"`
+ Contracts map[string]string `json:"contracts"`
+ Block uint64 `json:"block"` // the first block with the network's contracts
+ Schema string `json:"schema"` // the EAS claim schema
+ LogRange uint64 `json:"log_range"`
+ Host string `json:"host"`
+ Settle *struct {
+ Token string `json:"token"`
+ Symbol string `json:"symbol"`
+ Decimals int `json:"decimals"`
+ } `json:"settle"`
+}
+
+// ReadNet reads a net.json.
+func ReadNet(path string) (Net, error) {
+ var n Net
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return n, err
+ }
+ if err := json.Unmarshal(b, &n); err != nil {
+ return n, fmt.Errorf("%s: %w", path, err)
+ }
+ if n.Contracts["Registry"] == "" || n.Contracts["Bank"] == "" {
+ return n, fmt.Errorf("%s: no Registry or Bank: not a tern network file", path)
+ }
+ return n, nil
+}
+
+// cacheVersion: raise it when what a scan derives changes, so old caches are read again.
+const cacheVersion = 1
+
+// fingerprint changes when the network's contracts do (or cacheVersion), so a
+// cache made for another deployment is thrown away.
+func (n Net) fingerprint() string {
+ ks := make([]string, 0, len(n.Contracts))
+ for k, v := range n.Contracts {
+ ks = append(ks, k+"="+strings.ToLower(v))
+ }
+ sort.Strings(ks)
+ return crypto.Keccak256Hash([]byte(fmt.Sprint(cacheVersion, n.ChainID, n.Block, ks))).Hex()[:18]
+}
+
+// State is everything a scan learned, up to ToBlock. Amounts are kept as
+// integers in the token's smallest unit (the *_raw fields) and shown in whole
+// units next to them.
+type State struct {
+ Network string `json:"network"`
+ ChainID int64 `json:"chain_id"`
+ Fingerprint string `json:"fingerprint"`
+ FromBlock uint64 `json:"from_block"`
+ ToBlock uint64 `json:"to_block"` // scanned up to and including
+ ToTime int64 `json:"to_time"`
+ Names map[string]*Name `json:"names"`
+ IDs map[string]string `json:"ids"` // bytes32 id => name
+ Addrs map[string]string `json:"addrs"` // controller or agent address => name
+ Payments []*Payment `json:"payments"`
+ Locks []*Lock `json:"locks"`
+ Swaps []*Swap `json:"swaps"`
+ Claims []*Claim `json:"claims"`
+ Mail map[string]*Mail `json:"mail"` // UTC day => envelopes
+ Tokens map[string]*Token `json:"tokens"`
+}
+
+type Name struct {
+ Name string `json:"name"`
+ Kind string `json:"kind"` // owner | agent
+ Owner string `json:"owner,omitempty"` // an agent's
+ Since int64 `json:"since"`
+ Block uint64 `json:"block"`
+ Card string `json:"card,omitempty"`
+ Agents []string `json:"agents,omitempty"`
+ Revoked bool `json:"revoked,omitempty"`
+ // Limits: an agent's spending limit per epoch (a day), per token ("coin" for the network coin)
+ Limits map[string]string `json:"limits,omitempty"`
+}
+
+type Payment struct {
+ Block uint64 `json:"block"`
+ Time int64 `json:"time"`
+ From string `json:"from"`
+ To string `json:"to"`
+ Token string `json:"token"`
+ Amount string `json:"amount"`
+ AmountRaw string `json:"amount_raw"`
+}
+
+type Lock struct {
+ ID uint64 `json:"id"`
+ Block uint64 `json:"block"`
+ Time int64 `json:"time"`
+ From string `json:"from"`
+ Payee string `json:"payee"` // "" while open to whoever the condition names
+ Kind string `json:"kind"`
+ Condition string `json:"condition"`
+ Decider string `json:"decider,omitempty"`
+ Token string `json:"token"`
+ Item string `json:"item,omitempty"` // an item lock: the item id in its collection
+ Total string `json:"total"`
+ Paid string `json:"paid"`
+ Refunded string `json:"refunded"`
+ TotalRaw string `json:"total_raw"`
+ PaidRaw string `json:"paid_raw"`
+ RefundedRaw string `json:"refunded_raw"`
+ RefundAfter int64 `json:"refund_after"`
+ Status string `json:"status"` // open | refundable | paid | refunded | split | partly paid
+ Ended int64 `json:"ended,omitempty"`
+}
+
+type Swap struct {
+ Block uint64 `json:"block"`
+ Time int64 `json:"time"`
+ Offer uint64 `json:"offer"` // its lock
+ Answer uint64 `json:"answer"` // its lock
+}
+
+type Claim struct {
+ UID string `json:"uid"`
+ Block uint64 `json:"block"`
+ Time int64 `json:"time"`
+ Attester string `json:"attester"`
+ Subject string `json:"subject"`
+ Kind string `json:"kind"`
+ Score int64 `json:"score"`
+ Data string `json:"data,omitempty"` // the first bytes, when they are text
+ Revoked bool `json:"revoked,omitempty"`
+}
+
+type Mail struct {
+ Envelopes uint64 `json:"envelopes"`
+ Bytes uint64 `json:"bytes"`
+}
+
+type Token struct {
+ Symbol string `json:"symbol"`
+ Decimals int `json:"decimals"`
+}
+
+// Coin is the token key of the network's own coin (a lock or payment with token 0).
+const Coin = "coin"
+
+func newState(n Net) *State {
+ return &State{Network: n.Network, ChainID: n.ChainID, Fingerprint: n.fingerprint(), FromBlock: n.Block,
+ Names: map[string]*Name{}, IDs: map[string]string{}, Addrs: map[string]string{}, Mail: map[string]*Mail{}, Tokens: map[string]*Token{}}
+}
+
+// Load reads a cached state for this network, or starts an empty one.
+func Load(path string, n Net) *State {
+ s := newState(n)
+ b, err := os.ReadFile(path)
+ if err != nil {
+ return s
+ }
+ var c State
+ if json.Unmarshal(b, &c) != nil || c.Fingerprint != s.Fingerprint || c.Names == nil {
+ return s
+ }
+ for _, m := range []*map[string]string{&c.IDs, &c.Addrs} {
+ if *m == nil {
+ *m = map[string]string{}
+ }
+ }
+ if c.Mail == nil {
+ c.Mail = map[string]*Mail{}
+ }
+ if c.Tokens == nil {
+ c.Tokens = map[string]*Token{}
+ }
+ return &c
+}
+
+// Save writes the state where Load finds it.
+func (s *State) Save(path string) error {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ return err
+ }
+ b, err := json.Marshal(s)
+ if err != nil {
+ return err
+ }
+ tmp := path + ".tmp"
+ if err := os.WriteFile(tmp, b, 0o644); err != nil {
+ return err
+ }
+ return os.Rename(tmp, path)
+}
+
+// Options steer an update.
+type Options struct {
+ Confirmations uint64 // stay this many blocks behind the head (reorgs)
+ Progress func(from, to, head uint64) // after each range
+ Save func(*State) error // after each range, so an interrupted scan resumes
+}
+
+// Update scans from the block after the last one scanned up to the head.
+func (s *State) Update(ctx context.Context, b Backend, n Net, o Options) error {
+ b = retrying{b}
+ sc, err := newScanner(b, n, s)
+ if err != nil {
+ return err
+ }
+ head, err := b.BlockNumber(ctx)
+ if err != nil {
+ return err
+ }
+ if head < o.Confirmations {
+ return nil
+ }
+ head -= o.Confirmations
+ from := s.FromBlock
+ if s.ToBlock >= from && s.ToTime != 0 {
+ from = s.ToBlock + 1
+ }
+ step := n.LogRange
+ if step == 0 {
+ step = 10_000
+ }
+ for from <= head {
+ to := min(from+step-1, head)
+ logs, err := sc.logs(ctx, from, to)
+ if err != nil {
+ if step > 100 && smaller(err) {
+ step /= 2 // some RPCs refuse wide ranges or many results
+ continue
+ }
+ return fmt.Errorf("logs %d-%d: %w", from, to, err)
+ }
+ if err := sc.clock(ctx, from, to); err != nil {
+ return err
+ }
+ for _, l := range logs {
+ if err := sc.apply(ctx, l); err != nil {
+ return fmt.Errorf("block %d tx %s: %w", l.BlockNumber, l.TxHash.Hex(), err)
+ }
+ }
+ s.ToBlock, s.ToTime = to, sc.t1
+ s.refresh()
+ if o.Save != nil {
+ if err := o.Save(s); err != nil {
+ return err
+ }
+ }
+ if o.Progress != nil {
+ o.Progress(from, to, head)
+ }
+ from = to + 1
+ }
+ s.refresh()
+ return nil
+}
+
+// retrying: a public RPC drops a request now and then (a TLS handshake that
+// times out, a 502, a rate limit): each call is tried again a few times,
+// waiting longer each time. A refused range comes back at once, for Update
+// to ask for a smaller one.
+type retrying struct{ Backend }
+
+const tries = 4
+
+var backoff = time.Second // the first wait; it doubles (tests shorten it)
+
+func retry[T any](ctx context.Context, f func() (T, error)) (T, error) {
+ var v T
+ var err error
+ for i := range tries {
+ if v, err = f(); err == nil || ctx.Err() != nil || tooWide(err) {
+ return v, err
+ }
+ if i < tries-1 {
+ select {
+ case <-ctx.Done():
+ return v, ctx.Err()
+ case <-time.After(backoff << i):
+ }
+ }
+ }
+ return v, err
+}
+
+func (r retrying) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) {
+ return retry(ctx, func() ([]types.Log, error) { return r.Backend.FilterLogs(ctx, q) })
+}
+
+func (r retrying) BlockNumber(ctx context.Context) (uint64, error) {
+ return retry(ctx, func() (uint64, error) { return r.Backend.BlockNumber(ctx) })
+}
+
+func (r retrying) HeaderByNumber(ctx context.Context, n *big.Int) (*types.Header, error) {
+ return retry(ctx, func() (*types.Header, error) { return r.Backend.HeaderByNumber(ctx, n) })
+}
+
+func (r retrying) CallContract(ctx context.Context, msg ethereum.CallMsg, block *big.Int) ([]byte, error) {
+ return retry(ctx, func() ([]byte, error) { return r.Backend.CallContract(ctx, msg, block) })
+}
+
+// tooWide: the RPC refused the range or the number of results.
+func tooWide(err error) bool {
+ m := strings.ToLower(err.Error())
+ for _, w := range []string{"block range", "range is too", "range too", "too many", "exceed", "10000 results", "limit"} {
+ if strings.Contains(m, w) {
+ return true
+ }
+ }
+ return false
+}
+
+// smaller: after the retries, a range worth asking for in halves (refused
+// as too wide, or timing out under the load of a wide one).
+func smaller(err error) bool {
+ m := strings.ToLower(err.Error())
+ return tooWide(err) || strings.Contains(m, "timeout") || strings.Contains(m, "429")
+}
+
+// ---- the scanner: one pass over a range of blocks
+
+type scanner struct {
+ b Backend
+ n Net
+ s *State
+ abis map[string]abi.ABI // contract name => ABI
+ byAddr map[common.Address]string // contract address => name
+ events map[common.Hash]abi.Event // topic0 => event (names are unique across the contracts read)
+ addrs []common.Address
+ topics []common.Hash
+ schema common.Hash
+ // block times: the range's ends, read once; blocks between are interpolated
+ b0, b1 uint64
+ t0, t1 int64
+}
+
+// what is read: contract => its events
+var watched = map[string][]string{
+ "Registry": {"OwnerRegistered", "ControllerChanged", "AgentGranted", "AgentRevoked", "CardSet"},
+ "Bank": {"Paid", "TokenPaid", "Locked", "Claimed", "Refunded", "Released", "GivenBack", "TokenLimitSet"},
+ "SwapCondition": {"Swapped"},
+ "EAS": {"Attested", "Revoked"},
+ "Inbox": {"Posted", "Committed"},
+}
+
+func loadABI(name string) (abi.ABI, error) {
+ b, err := tern.Build.ReadFile("build/" + name + "_sol_" + name + ".abi")
+ if err != nil {
+ b, err = tern.BuildExt.ReadFile("build/ext/" + name + "_sol_" + name + ".abi")
+ }
+ if err != nil {
+ return abi.ABI{}, err
+ }
+ return abi.JSON(strings.NewReader(string(b)))
+}
+
+func newScanner(b Backend, n Net, s *State) (*scanner, error) {
+ sc := &scanner{b: b, n: n, s: s, abis: map[string]abi.ABI{}, byAddr: map[common.Address]string{}, events: map[common.Hash]abi.Event{},
+ schema: common.HexToHash(n.Schema)}
+ for _, c := range []string{"Registry", "Bank", "SwapCondition", "EAS", "Inbox"} {
+ a, err := loadABI(c)
+ if err != nil {
+ return nil, err
+ }
+ sc.abis[c] = a
+ addr, ok := n.Contracts[c]
+ if !ok {
+ continue // a network without it (no swaps yet)
+ }
+ sc.addrs = append(sc.addrs, common.HexToAddress(addr))
+ for _, e := range watched[c] {
+ ev, ok := a.Events[e]
+ if !ok {
+ return nil, fmt.Errorf("%s has no event %s", c, e)
+ }
+ sc.events[ev.ID] = ev
+ sc.topics = append(sc.topics, ev.ID)
+ }
+ }
+ for name, addr := range n.Contracts {
+ sc.byAddr[common.HexToAddress(addr)] = name
+ }
+ return sc, nil
+}
+
+func (sc *scanner) logs(ctx context.Context, from, to uint64) ([]types.Log, error) {
+ return sc.b.FilterLogs(ctx, ethereum.FilterQuery{FromBlock: new(big.Int).SetUint64(from), ToBlock: new(big.Int).SetUint64(to),
+ Addresses: sc.addrs, Topics: [][]common.Hash{sc.topics}})
+}
+
+func (sc *scanner) clock(ctx context.Context, from, to uint64) error {
+ h0, err := sc.b.HeaderByNumber(ctx, new(big.Int).SetUint64(from))
+ if err != nil {
+ return err
+ }
+ h1 := h0
+ if to != from {
+ if h1, err = sc.b.HeaderByNumber(ctx, new(big.Int).SetUint64(to)); err != nil {
+ return err
+ }
+ }
+ sc.b0, sc.b1, sc.t0, sc.t1 = from, to, int64(h0.Time), int64(h1.Time)
+ return nil
+}
+
+// at: a block's time, interpolated between the range's ends (exact on chains
+// with a fixed block time, such as Base's 2 seconds).
+func (sc *scanner) at(block uint64) int64 {
+ if sc.b1 == sc.b0 {
+ return sc.t0
+ }
+ return sc.t0 + (sc.t1-sc.t0)*int64(block-sc.b0)/int64(sc.b1-sc.b0)
+}
+
+func (sc *scanner) decode(l types.Log) (string, map[string]any, error) {
+ ev, ok := sc.events[l.Topics[0]]
+ if !ok {
+ return "", nil, nil
+ }
+ contract := sc.byAddr[l.Address]
+ m := map[string]any{}
+ if len(l.Data) > 0 {
+ if err := sc.abis[contract].UnpackIntoMap(m, ev.Name, l.Data); err != nil {
+ return "", nil, fmt.Errorf("%s.%s: %w", contract, ev.Name, err)
+ }
+ }
+ var indexed abi.Arguments
+ for _, in := range ev.Inputs {
+ if in.Indexed {
+ indexed = append(indexed, in)
+ }
+ }
+ if err := abi.ParseTopicsIntoMap(m, indexed, l.Topics[1:]); err != nil {
+ return "", nil, fmt.Errorf("%s.%s topics: %w", contract, ev.Name, err)
+ }
+ return contract + "." + ev.Name, m, nil
+}
+
+func (sc *scanner) apply(ctx context.Context, l types.Log) error {
+ if len(l.Topics) == 0 || l.Removed {
+ return nil
+ }
+ what, m, err := sc.decode(l)
+ if err != nil || what == "" {
+ return err
+ }
+ s, t := sc.s, sc.at(l.BlockNumber)
+ switch what {
+ case "Registry.OwnerRegistered":
+ name := m["name"].(string)
+ s.IDs[hexOf(m["id"])] = name
+ s.Addrs[addrKey(m["controller"])] = name
+ s.Names[name] = &Name{Name: name, Kind: "owner", Since: t, Block: l.BlockNumber}
+ case "Registry.ControllerChanged":
+ if name, ok := s.IDs[hexOf(m["id"])]; ok {
+ s.Addrs[addrKey(m["controller"])] = name
+ }
+ case "Registry.AgentGranted":
+ name, owner := m["name"].(string), s.IDs[hexOf(m["owner"])]
+ s.IDs[hexOf(m["id"])] = name
+ s.Addrs[addrKey(m["agent"])] = name
+ a := s.Names[name]
+ if a == nil {
+ a = &Name{Name: name, Kind: "agent", Owner: owner, Since: t, Block: l.BlockNumber}
+ s.Names[name] = a
+ if o := s.Names[owner]; o != nil {
+ o.Agents = append(o.Agents, name)
+ }
+ }
+ a.Revoked = false // a new grant (generation) for the same name
+ if v := m["spendPerEpoch"].(*big.Int); v.Sign() > 0 {
+ a.setLimit(Coin, v.String())
+ }
+ case "Registry.AgentRevoked":
+ if a := s.Names[s.IDs[hexOf(m["id"])]]; a != nil {
+ a.Revoked = true
+ }
+ case "Registry.CardSet":
+ if o := s.Names[s.IDs[hexOf(m["id"])]]; o != nil {
+ o.Card = m["card"].(string)
+ }
+ case "Bank.TokenLimitSet":
+ if a := s.Names[s.IDs[hexOf(m["agent"])]]; a != nil {
+ tok, err := sc.token(ctx, m["token"].(common.Address))
+ if err != nil {
+ return err
+ }
+ a.setLimit(tok, m["perEpoch"].(*big.Int).String())
+ }
+ case "Bank.Paid", "Bank.TokenPaid":
+ tok := Coin
+ if a, ok := m["token"].(common.Address); ok {
+ if tok, err = sc.token(ctx, a); err != nil {
+ return err
+ }
+ }
+ s.Payments = append(s.Payments, &Payment{Block: l.BlockNumber, Time: t, From: s.who(m["from"]), To: s.who(m["to"]), Token: tok,
+ AmountRaw: m["amount"].(*big.Int).String()})
+ case "Bank.Locked":
+ return sc.locked(ctx, l, m, t)
+ case "Bank.Claimed", "Bank.Released":
+ if k := s.lock(m["id"]); k != nil {
+ k.PaidRaw = addRaw(k.PaidRaw, m["amount"].(*big.Int))
+ k.Ended = t
+ }
+ case "Bank.Refunded", "Bank.GivenBack":
+ if k := s.lock(m["id"]); k != nil {
+ k.RefundedRaw = addRaw(k.RefundedRaw, m["amount"].(*big.Int))
+ k.Ended = t
+ }
+ case "SwapCondition.Swapped":
+ s.Swaps = append(s.Swaps, &Swap{Block: l.BlockNumber, Time: t, Offer: m["offer"].(*big.Int).Uint64(), Answer: m["answer"].(*big.Int).Uint64()})
+ case "EAS.Attested":
+ if common.Hash(m["schemaUID"].([32]byte)) != sc.schema {
+ return nil // only tern's claim schema
+ }
+ return sc.attested(ctx, l, common.Hash(m["uid"].([32]byte)), t)
+ case "EAS.Revoked":
+ uid := common.Hash(m["uid"].([32]byte)).Hex()
+ for _, c := range s.Claims {
+ if c.UID == uid {
+ c.Revoked = true
+ }
+ }
+ case "Inbox.Posted":
+ s.mail(t, m["n"].(*big.Int).Uint64(), uint64(len(m["batch"].([]byte))))
+ case "Inbox.Committed":
+ s.mail(t, m["n"].(*big.Int).Uint64(), m["size"].(*big.Int).Uint64())
+ }
+ return nil
+}
+
+func (sc *scanner) locked(ctx context.Context, l types.Log, m map[string]any, t int64) error {
+ s := sc.s
+ id := m["id"].(*big.Int)
+ k := &Lock{ID: id.Uint64(), Block: l.BlockNumber, Time: t, From: s.who(m["from"]), Payee: s.who(m["payee"]),
+ TotalRaw: m["total"].(*big.Int).String(), PaidRaw: "0", RefundedRaw: "0", RefundAfter: int64(m["refundAfter"].(uint64))}
+ cond := m["condition"].(common.Address)
+ k.Condition = sc.byAddr[cond]
+ if k.Condition == "" {
+ k.Condition = cond.Hex()
+ }
+ k.Kind, k.Decider = sc.kindOf(k.Condition, m["demand"].([]byte))
+ // The event doesn't carry the token or the item: the lock does (both fixed when it opened).
+ bank := sc.abis["Bank"]
+ out, err := sc.call(ctx, "Bank", bank, "locks", id)
+ if err != nil {
+ return fmt.Errorf("lock %d: %w", k.ID, err)
+ }
+ if k.Token, err = sc.token(ctx, out[9].(common.Address)); err != nil {
+ return err
+ }
+ if out, err := sc.call(ctx, "Bank", bank, "itemOf", id); err == nil && out[0].(*big.Int).Sign() > 0 {
+ k.Item = new(big.Int).Sub(out[0].(*big.Int), big.NewInt(1)).String()
+ k.Token += " item"
+ }
+ s.Locks = append(s.Locks, k)
+ return nil
+}
+
+// kindOf names the recipe a lock was made with, as the client's `lock show` does.
+func (sc *scanner) kindOf(cond string, demand []byte) (kind, decider string) {
+ switch cond {
+ case "AttestationCondition":
+ t, _ := abi.NewType("tuple", "", []abi.ArgumentMarshaling{
+ {Name: "attester", Type: "bytes32"}, {Name: "schema", Type: "bytes32"}, {Name: "subject", Type: "bytes32"},
+ {Name: "kindHash", Type: "bytes32"}, {Name: "minScore", Type: "int64"}, {Name: "mode", Type: "uint8"}})
+ v, err := abi.Arguments{{Type: t}}.Unpack(demand)
+ if err != nil || len(v) != 1 {
+ return "conditional", ""
+ }
+ d := *abi.ConvertType(v[0], new(struct {
+ Attester, Schema, Subject, KindHash [32]byte
+ MinScore int64
+ Mode uint8
+ })).(*struct {
+ Attester, Schema, Subject, KindHash [32]byte
+ MinScore int64
+ Mode uint8
+ })
+ decider = sc.s.who(d.Attester)
+ switch common.Hash(d.KindHash) {
+ case crypto.Keccak256Hash([]byte("ruling")):
+ return "escrow", decider
+ case crypto.Keccak256Hash([]byte("slash")):
+ return "bond", decider
+ case crypto.Keccak256Hash([]byte("award")):
+ return "bounty", decider
+ }
+ return "conditional", decider
+ case "OptimisticCondition":
+ return "optimistic", ""
+ case "PanelCondition":
+ return "panel", ""
+ case "RulingCondition":
+ return "ruling", ""
+ case "RateCondition":
+ return "subscription", ""
+ case "VoucherCondition":
+ return "channel", ""
+ case "HashlockCondition":
+ return "htlc", ""
+ case "PledgeCondition":
+ return "pledge", ""
+ case "RevealCondition":
+ return "reveal", ""
+ case "SwapCondition":
+ return "swap", ""
+ case "Clock":
+ return "game clock", ""
+ case "TernJobs":
+ return "job", "" // an ERC-8183 job: its evaluator decides (job show)
+ }
+ return "other", ""
+}
+
+func (sc *scanner) attested(ctx context.Context, l types.Log, uid common.Hash, t int64) error {
+ out, err := sc.call(ctx, "EAS", sc.abis["EAS"], "getAttestation", uid)
+ if err != nil {
+ return fmt.Errorf("claim %s: %w", uid.Hex(), err)
+ }
+ a := abi.ConvertType(out[0], new(struct {
+ Uid [32]byte
+ Schema [32]byte
+ Time uint64
+ ExpirationTime uint64
+ RevocationTime uint64
+ RefUID [32]byte
+ Recipient common.Address
+ Attester common.Address
+ Revocable bool
+ Data []byte
+ })).(*struct {
+ Uid [32]byte
+ Schema [32]byte
+ Time uint64
+ ExpirationTime uint64
+ RevocationTime uint64
+ RefUID [32]byte
+ Recipient common.Address
+ Attester common.Address
+ Revocable bool
+ Data []byte
+ })
+ args := abi.Arguments{{Type: mustType("bytes32")}, {Type: mustType("string")}, {Type: mustType("bytes")}, {Type: mustType("int64")}}
+ v, err := args.Unpack(a.Data)
+ if err != nil {
+ return nil // not tern's claim shape after all
+ }
+ c := &Claim{UID: uid.Hex(), Block: l.BlockNumber, Time: t, Attester: sc.s.byAddr(a.Attester), Subject: sc.s.who(v[0]),
+ Kind: v[1].(string), Score: v[3].(int64), Revoked: a.RevocationTime != 0}
+ if d := v[2].([]byte); isText(d) {
+ c.Data = clip(string(d), 200)
+ }
+ sc.s.Claims = append(sc.s.Claims, c)
+ return nil
+}
+
+func (sc *scanner) call(ctx context.Context, contract string, a abi.ABI, method string, args ...any) ([]any, error) {
+ in, err := a.Pack(method, args...)
+ if err != nil {
+ return nil, err
+ }
+ to := common.HexToAddress(sc.n.Contracts[contract])
+ out, err := sc.b.CallContract(ctx, ethereum.CallMsg{To: &to, Data: in}, nil)
+ if err != nil {
+ return nil, err
+ }
+ return a.Unpack(method, out)
+}
+
+var erc20, _ = abi.JSON(strings.NewReader(`[
+{"type":"function","name":"symbol","stateMutability":"view","inputs":[],"outputs":[{"type":"string"}]},
+{"type":"function","name":"decimals","stateMutability":"view","inputs":[],"outputs":[{"type":"uint8"}]}]`))
+
+// token: a token's key in State.Tokens (its address, or Coin), read once.
+func (sc *scanner) token(ctx context.Context, a common.Address) (string, error) {
+ if a == (common.Address{}) {
+ if sc.s.Tokens[Coin] == nil {
+ sym := "coin"
+ if sc.n.Host != "" {
+ sym = "ETH" // a network on a host chain: its coin is the host's
+ }
+ sc.s.Tokens[Coin] = &Token{Symbol: sym, Decimals: 18}
+ }
+ return Coin, nil
+ }
+ key := strings.ToLower(a.Hex())
+ if sc.s.Tokens[key] != nil {
+ return key, nil
+ }
+ tk := &Token{Symbol: a.Hex()[:8], Decimals: 18}
+ if st := sc.n.Settle; st != nil && strings.EqualFold(st.Token, a.Hex()) {
+ tk = &Token{Symbol: st.Symbol, Decimals: st.Decimals}
+ } else {
+ if out, err := sc.erc20(ctx, a, "symbol"); err == nil {
+ tk.Symbol = out[0].(string)
+ }
+ if out, err := sc.erc20(ctx, a, "decimals"); err == nil {
+ tk.Decimals = int(out[0].(uint8))
+ }
+ }
+ sc.s.Tokens[key] = tk
+ return key, nil
+}
+
+func (sc *scanner) erc20(ctx context.Context, a common.Address, method string) ([]any, error) {
+ in, _ := erc20.Pack(method)
+ out, err := sc.b.CallContract(ctx, ethereum.CallMsg{To: &a, Data: in}, nil)
+ if err != nil {
+ return nil, err
+ }
+ return erc20.Unpack(method, out)
+}
+
+// ---- the state's helpers
+
+func (n *Name) setLimit(token, raw string) {
+ if n.Limits == nil {
+ n.Limits = map[string]string{}
+ }
+ n.Limits[token] = raw
+}
+
+// who: a bytes32 id as a name, or a short hash when no name has it (a split, a deal subject).
+func (s *State) who(v any) string {
+ h := hexOf(v)
+ if h == (common.Hash{}).Hex() {
+ return ""
+ }
+ if n, ok := s.IDs[h]; ok {
+ return n
+ }
+ return h[:10] + "…"
+}
+
+func (s *State) byAddr(a common.Address) string {
+ if n, ok := s.Addrs[addrKey(a)]; ok {
+ return n
+ }
+ return a.Hex()[:10] + "…"
+}
+
+func (s *State) lock(v any) *Lock {
+ id := v.(*big.Int).Uint64()
+ // Locks are numbered in order, so the id is nearly always the index.
+ if id < uint64(len(s.Locks)) && s.Locks[id].ID == id {
+ return s.Locks[id]
+ }
+ for _, k := range s.Locks {
+ if k.ID == id {
+ return k
+ }
+ }
+ return nil
+}
+
+func (s *State) mail(t int64, n, size uint64) {
+ d := Day(t)
+ m := s.Mail[d]
+ if m == nil {
+ m = &Mail{}
+ s.Mail[d] = m
+ }
+ m.Envelopes += n
+ m.Bytes += size
+}
+
+// refresh recomputes what is derived: amounts in whole units, locks' status.
+func (s *State) refresh() {
+ for _, p := range s.Payments {
+ p.Amount = s.Fmt(p.Token, p.AmountRaw)
+ }
+ for _, k := range s.Locks {
+ tok := strings.TrimSuffix(k.Token, " item")
+ if k.Item != "" {
+ k.Total, k.Paid, k.Refunded = k.TotalRaw, k.PaidRaw, k.RefundedRaw // items count in units
+ } else {
+ k.Total, k.Paid, k.Refunded = s.Fmt(tok, k.TotalRaw), s.Fmt(tok, k.PaidRaw), s.Fmt(tok, k.RefundedRaw)
+ }
+ total, paid, refunded := bigOf(k.TotalRaw), bigOf(k.PaidRaw), bigOf(k.RefundedRaw)
+ done := new(big.Int).Add(paid, refunded)
+ switch {
+ case done.Cmp(total) >= 0 && refunded.Sign() == 0:
+ k.Status = "paid"
+ case done.Cmp(total) >= 0 && paid.Sign() == 0:
+ k.Status = "refunded"
+ case done.Cmp(total) >= 0:
+ k.Status = "split"
+ case done.Sign() > 0:
+ k.Status = "partly paid"
+ case s.ToTime > k.RefundAfter:
+ k.Status = "refundable" // past its refund time, nothing claimed
+ default:
+ k.Status = "open"
+ }
+ }
+}
+
+// Fmt shows a raw amount of a token in whole units.
+func (s *State) Fmt(token, raw string) string {
+ dec := 18
+ if t := s.Tokens[token]; t != nil {
+ dec = t.Decimals
+ }
+ return FmtUnits(bigOf(raw), dec)
+}
+
+// Symbol: a token's symbol ("" for an unknown token).
+func (s *State) Symbol(token string) string {
+ if t := s.Tokens[strings.TrimSuffix(token, " item")]; t != nil {
+ return t.Symbol
+ }
+ return ""
+}
+
+// FmtUnits: v / 10^dec, without trailing zeros.
+func FmtUnits(v *big.Int, dec int) string {
+ r := new(big.Rat).SetFrac(v, new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(dec)), nil))
+ out := r.FloatString(dec)
+ if strings.Contains(out, ".") {
+ out = strings.TrimRight(strings.TrimRight(out, "0"), ".")
+ }
+ return out
+}
+
+// Day: a time's UTC date.
+func Day(t int64) string { return time.Unix(t, 0).UTC().Format("2006-01-02") }
+
+func hexOf(v any) string {
+ switch x := v.(type) {
+ case [32]byte:
+ return common.Hash(x).Hex()
+ case common.Hash:
+ return x.Hex()
+ }
+ return ""
+}
+
+func addrKey(v any) string { return strings.ToLower(v.(common.Address).Hex()) }
+
+func bigOf(s string) *big.Int {
+ v, ok := new(big.Int).SetString(s, 10)
+ if !ok {
+ return new(big.Int)
+ }
+ return v
+}
+
+func addRaw(raw string, v *big.Int) string { return new(big.Int).Add(bigOf(raw), v).String() }
+
+func mustType(t string) abi.Type {
+ ty, err := abi.NewType(t, "", nil)
+ if err != nil {
+ panic(err)
+ }
+ return ty
+}
+
+func isText(b []byte) bool {
+ if len(b) == 0 {
+ return false
+ }
+ for _, c := range string(b) {
+ if c == '�' || (c < 0x20 && c != '\n' && c != '\t') {
+ return false
+ }
+ }
+ return true
+}
+
+func clip(s string, n int) string {
+ if r := []rune(s); len(r) > n {
+ return string(r[:n]) + "…"
+ }
+ return s
+}
+
+// ErrNoNet: no network file was found.
+var ErrNoNet = errors.New("no network file: pass --net or set TERNCHAIN_NET")
diff --git a/internal/scan/scan_test.go b/internal/scan/scan_test.go
new file mode 100644
index 0000000..ee82acc
--- /dev/null
+++ b/internal/scan/scan_test.go
@@ -0,0 +1,39 @@
+package scan
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+)
+
+// A call that fails now and then is tried again; a refused range comes back
+// at once (Update asks for a smaller one); one that keeps failing gives up.
+func TestRetry(t *testing.T) {
+ backoff = time.Millisecond
+ defer func() { backoff = time.Second }()
+ ctx := context.Background()
+
+ n := 0
+ v, err := retry(ctx, func() (int, error) {
+ if n++; n < 3 {
+ return 0, errors.New(`Post "https://rpc": net/http: TLS handshake timeout`)
+ }
+ return 7, nil
+ })
+ if v != 7 || err != nil || n != 3 {
+ t.Fatalf("flaky: %d %v after %d calls", v, err, n)
+ }
+
+ n = 0
+ _, err = retry(ctx, func() (int, error) { n++; return 0, errors.New("query exceeds max block range 10000") })
+ if err == nil || n != 1 || !smaller(err) {
+ t.Fatalf("too wide: %v after %d calls", err, n)
+ }
+
+ n = 0
+ _, err = retry(ctx, func() (int, error) { n++; return 0, errors.New("502 bad gateway") })
+ if err == nil || n != tries {
+ t.Fatalf("down: %v after %d calls", err, n)
+ }
+}