@artblocks/abx-sdk 0.1.0-alpha.2 → 0.1.0-alpha.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) hide show
  1. package/README.md +131 -0
  2. package/dist/abi/generated.d.ts +8502 -129
  3. package/dist/abi/generated.d.ts.map +1 -1
  4. package/dist/abi/generated.js +40 -22
  5. package/dist/abi/generated.js.map +1 -1
  6. package/dist/abi/index.d.ts +2645 -168
  7. package/dist/abi/index.d.ts.map +1 -1
  8. package/dist/abi/index.js +34 -7
  9. package/dist/abi/index.js.map +1 -1
  10. package/dist/anchors.d.ts +266 -0
  11. package/dist/anchors.d.ts.map +1 -0
  12. package/dist/anchors.js +653 -0
  13. package/dist/anchors.js.map +1 -0
  14. package/dist/chains.d.ts +15 -9
  15. package/dist/chains.d.ts.map +1 -1
  16. package/dist/chains.js +19 -15
  17. package/dist/chains.js.map +1 -1
  18. package/dist/chunks.d.ts +53 -23
  19. package/dist/chunks.d.ts.map +1 -1
  20. package/dist/chunks.js +68 -6
  21. package/dist/chunks.js.map +1 -1
  22. package/dist/clients.d.ts +23 -11
  23. package/dist/clients.d.ts.map +1 -1
  24. package/dist/clients.js +17 -18
  25. package/dist/clients.js.map +1 -1
  26. package/dist/create2.d.ts +85 -1
  27. package/dist/create2.d.ts.map +1 -1
  28. package/dist/create2.js +159 -2
  29. package/dist/create2.js.map +1 -1
  30. package/dist/creator-token.d.ts +132 -0
  31. package/dist/creator-token.d.ts.map +1 -0
  32. package/dist/creator-token.js +183 -0
  33. package/dist/creator-token.js.map +1 -0
  34. package/dist/deploy.d.ts +234 -14
  35. package/dist/deploy.d.ts.map +1 -1
  36. package/dist/deploy.js +289 -111
  37. package/dist/deploy.js.map +1 -1
  38. package/dist/deployments.d.ts +12 -0
  39. package/dist/deployments.d.ts.map +1 -1
  40. package/dist/deployments.js +155 -28
  41. package/dist/deployments.js.map +1 -1
  42. package/dist/deps.d.ts +122 -5
  43. package/dist/deps.d.ts.map +1 -1
  44. package/dist/deps.js +248 -6
  45. package/dist/deps.js.map +1 -1
  46. package/dist/env.d.ts.map +1 -1
  47. package/dist/env.js +8 -0
  48. package/dist/env.js.map +1 -1
  49. package/dist/errors.d.ts +94 -0
  50. package/dist/errors.d.ts.map +1 -0
  51. package/dist/errors.js +126 -0
  52. package/dist/errors.js.map +1 -0
  53. package/dist/execute.d.ts +115 -0
  54. package/dist/execute.d.ts.map +1 -0
  55. package/dist/execute.js +142 -0
  56. package/dist/execute.js.map +1 -0
  57. package/dist/gateways.d.ts +79 -0
  58. package/dist/gateways.d.ts.map +1 -0
  59. package/dist/gateways.js +156 -0
  60. package/dist/gateways.js.map +1 -0
  61. package/dist/generator-document.d.ts +58 -0
  62. package/dist/generator-document.d.ts.map +1 -0
  63. package/dist/generator-document.js +124 -0
  64. package/dist/generator-document.js.map +1 -0
  65. package/dist/generator.d.ts +43 -1
  66. package/dist/generator.d.ts.map +1 -1
  67. package/dist/generator.js +29 -0
  68. package/dist/generator.js.map +1 -1
  69. package/dist/index.d.ts +17 -3
  70. package/dist/index.d.ts.map +1 -1
  71. package/dist/index.js +17 -3
  72. package/dist/index.js.map +1 -1
  73. package/dist/inspect.d.ts +48 -0
  74. package/dist/inspect.d.ts.map +1 -0
  75. package/dist/inspect.js +295 -0
  76. package/dist/inspect.js.map +1 -0
  77. package/dist/migrate.d.ts +41 -0
  78. package/dist/migrate.d.ts.map +1 -0
  79. package/dist/migrate.js +140 -0
  80. package/dist/migrate.js.map +1 -0
  81. package/dist/mime.d.ts +11 -0
  82. package/dist/mime.d.ts.map +1 -0
  83. package/dist/mime.js +40 -0
  84. package/dist/mime.js.map +1 -0
  85. package/dist/node.d.ts +10 -0
  86. package/dist/node.d.ts.map +1 -0
  87. package/dist/node.js +24 -0
  88. package/dist/node.js.map +1 -0
  89. package/dist/onchain-uri.d.ts +110 -0
  90. package/dist/onchain-uri.d.ts.map +1 -0
  91. package/dist/onchain-uri.js +273 -0
  92. package/dist/onchain-uri.js.map +1 -0
  93. package/dist/ops.d.ts +507 -14
  94. package/dist/ops.d.ts.map +1 -1
  95. package/dist/ops.js +848 -32
  96. package/dist/ops.js.map +1 -1
  97. package/dist/probe.d.ts +29 -0
  98. package/dist/probe.d.ts.map +1 -1
  99. package/dist/probe.js +104 -9
  100. package/dist/probe.js.map +1 -1
  101. package/dist/reconstruct.d.ts +92 -2
  102. package/dist/reconstruct.d.ts.map +1 -1
  103. package/dist/reconstruct.js +378 -93
  104. package/dist/reconstruct.js.map +1 -1
  105. package/dist/resume.d.ts +96 -0
  106. package/dist/resume.d.ts.map +1 -0
  107. package/dist/resume.js +95 -0
  108. package/dist/resume.js.map +1 -0
  109. package/dist/script-chunks.d.ts +24 -0
  110. package/dist/script-chunks.d.ts.map +1 -0
  111. package/dist/script-chunks.js +63 -0
  112. package/dist/script-chunks.js.map +1 -0
  113. package/dist/service.d.ts +188 -9
  114. package/dist/service.d.ts.map +1 -1
  115. package/dist/service.js +228 -18
  116. package/dist/service.js.map +1 -1
  117. package/dist/spine.d.ts +31 -4
  118. package/dist/spine.d.ts.map +1 -1
  119. package/dist/spine.js +0 -0
  120. package/dist/spine.js.map +1 -1
  121. package/dist/staging.d.ts +124 -0
  122. package/dist/staging.d.ts.map +1 -0
  123. package/dist/staging.js +134 -0
  124. package/dist/staging.js.map +1 -0
  125. package/dist/tokendata.d.ts +62 -2
  126. package/dist/tokendata.d.ts.map +1 -1
  127. package/dist/tokendata.js +79 -17
  128. package/dist/tokendata.js.map +1 -1
  129. package/dist/tokens.d.ts +94 -0
  130. package/dist/tokens.d.ts.map +1 -0
  131. package/dist/tokens.js +296 -0
  132. package/dist/tokens.js.map +1 -0
  133. package/dist/types.d.ts +60 -3
  134. package/dist/types.d.ts.map +1 -1
  135. package/dist/util.d.ts +74 -0
  136. package/dist/util.d.ts.map +1 -0
  137. package/dist/util.js +106 -0
  138. package/dist/util.js.map +1 -0
  139. package/package.json +10 -2
@@ -1,6 +1,8 @@
1
1
  import { concat as concatHex, keccak256, parseEventLogs, } from 'viem';
2
- import { oneOfOneImageAbi, oneOfOneImageFactoryAbi, seriesCodeAbi, spineEventAbi } from './abi/index.js';
2
+ import { oneOfOneEditionAbi, oneOfOneImageAbi, oneOfOneImageFactoryAbi, seriesCodeAbi, spineEventAbi } from './abi/index.js';
3
3
  import { AUTH_OPTIONS, decodeTag, DELEGATE_REGISTRY_DEFAULT, extensionName, EXTENSION_ID, PARAM_TYPES, SPINE_EVENT_DOC, } from './spine.js';
4
+ import { AbxSdkError } from './errors.js';
5
+ import { readEnv } from './util.js';
4
6
  /**
5
7
  * Rebuild a project's full state from the chain alone — the canonical replay.
6
8
  *
@@ -13,9 +15,12 @@ import { AUTH_OPTIONS, decodeTag, DELEGATE_REGISTRY_DEFAULT, extensionName, EXTE
13
15
  export async function reconstructProject(client, opts) {
14
16
  const { address, fromBlock, factory } = opts;
15
17
  const toBlockNum = opts.toBlock === 'latest' || opts.toBlock === undefined ? await client.getBlockNumber() : opts.toBlock;
16
- const rawLogs = await getLogsAdaptive(client, address, fromBlock, toBlockNum);
18
+ const rawLogs = await getLogsAdaptive(client, address, fromBlock, toBlockNum, {
19
+ maxChunks: opts.maxChunks,
20
+ range: opts.getLogsRange,
21
+ });
17
22
  const events = decodedToSpineEvents(parseEventLogs({ abi: spineEventAbi, logs: rawLogs })).sort(byOrder);
18
- return assembleState(client, address, events, foldSpine(events), fromBlock, toBlockNum, factory);
23
+ return assembleState(client, address, events, foldSpine(events), fromBlock, toBlockNum, factory, !!opts.readUriDocuments);
19
24
  }
20
25
  /**
21
26
  * The same state, but resumed from a prior reconstruction's checkpoint — so a
@@ -33,11 +38,29 @@ export async function reconstructIncremental(client, prior, opts = {}) {
33
38
  const priorTo = BigInt(prior.toBlock);
34
39
  const origin = BigInt(prior.deployBlock ?? prior.fromBlock);
35
40
  const resumeFrom = priorTo + 1n > origin ? priorTo + 1n : origin;
36
- let fresh = [];
41
+ let rawLogs = [];
37
42
  if (head >= resumeFrom) {
38
- const rawLogs = await getLogsAdaptive(client, address, resumeFrom, head);
39
- fresh = decodedToSpineEvents(parseEventLogs({ abi: spineEventAbi, logs: rawLogs }));
43
+ rawLogs = await getLogsAdaptive(client, address, resumeFrom, head, {
44
+ maxChunks: opts.maxChunks,
45
+ range: opts.getLogsRange,
46
+ });
40
47
  }
48
+ const toBlock = head >= priorTo ? head : priorTo;
49
+ return reconstructFromLogs(client, prior, rawLogs, { factory, readUriDocuments: opts.readUriDocuments, toBlock });
50
+ }
51
+ /**
52
+ * The fold / head-read half of {@link reconstructIncremental}, given logs the caller already
53
+ * fetched. A multi-address watch loop (`getLogs({address: Address[]})`) holds each touched
54
+ * project's delta; this consumes it so that loop is the only `eth_getLogs`. Folding stays here.
55
+ *
56
+ * `toBlock` is the inclusive scan head those logs cover — required even when `logs` is empty,
57
+ * so a quiet window still advances the checkpoint to the range the caller scanned, and so a
58
+ * caller that scanned a capped window (not chain head) cannot stamp `toBlock` past the last
59
+ * log they actually held.
60
+ */
61
+ export async function reconstructFromLogs(client, prior, logs, opts) {
62
+ const factory = opts.factory ?? prior.factory ?? undefined;
63
+ const fresh = decodedToSpineEvents(parseEventLogs({ abi: spineEventAbi, logs: logs }));
41
64
  // Merge the prior log with the freshly-fetched tail, de-duping by position so an
42
65
  // overlapping/duplicate re-run can't double-count, then fold the complete spine.
43
66
  const seen = new Set();
@@ -50,8 +73,13 @@ export async function reconstructIncremental(client, prior, opts = {}) {
50
73
  all.push(ev);
51
74
  }
52
75
  all.sort(byOrder);
53
- const toBlock = head >= priorTo ? head : priorTo;
54
- return assembleState(client, address, all, foldSpine(all), BigInt(prior.fromBlock), toBlock, factory);
76
+ // Chunk content has no log (too large); `ScriptUpdated` is the ping. A Transfer currently
77
+ // used to re-download every chunk. Keep the prior digest unless that ping is in `fresh`.
78
+ const scriptTouched = fresh.some((e) => e.name === 'ScriptUpdated');
79
+ const reuseScript = !scriptTouched && prior.script?.digest != null ? prior.script : undefined;
80
+ const priorTo = BigInt(prior.toBlock);
81
+ const toBlock = opts.toBlock >= priorTo ? opts.toBlock : priorTo;
82
+ return assembleState(client, prior.address, all, foldSpine(all), BigInt(prior.fromBlock), toBlock, factory, !!opts.readUriDocuments, reuseScript);
55
83
  }
56
84
  /** Turn decoded viem logs into the canonical, serializable {@link SpineEvent} list. */
57
85
  function decodedToSpineEvents(decoded) {
@@ -78,6 +106,41 @@ function tokenIn(tokens, id) {
78
106
  }
79
107
  return t;
80
108
  }
109
+ /**
110
+ * Fold one ERC-1155 transfer leg (a `TransferSingle`, or one element of a `TransferBatch`) into
111
+ * an id's per-id supply counter + holder balances. Mint = `from` the zero address (supply +=
112
+ * amount); burn = `to` the zero address (supply -= amount); a transfer between two live holders
113
+ * touches no supply, only balances — mirrors `AbxErc1155Base._afterTokenTransfer`'s own
114
+ * if/else-if exactly. `minted` is recomputed as `supply > 0` on every leg (never just latched
115
+ * true) because — unlike a 721 token, which has no burn in this spine — an edition id CAN return
116
+ * to zero supply and mint again.
117
+ */
118
+ function applyEditionTransfer(tokens, id, from, to, amount) {
119
+ const t = tokenIn(tokens, id);
120
+ if (isZeroAddr(from))
121
+ t.supply = (BigInt(t.supply ?? '0') + amount).toString();
122
+ else if (isZeroAddr(to))
123
+ t.supply = (BigInt(t.supply ?? '0') - amount).toString();
124
+ t.minted = BigInt(t.supply ?? '0') > 0n;
125
+ adjustHolderBalance(t, from, -amount);
126
+ adjustHolderBalance(t, to, amount);
127
+ }
128
+ /**
129
+ * Adjust one token's per-holder balance by `delta`. The zero address is never a real holder
130
+ * (a mint's `from` / a burn's `to`) and is skipped. A balance that reaches zero is deleted
131
+ * rather than kept at `"0"` — {@link TokenState.holders} lists only CURRENT holders.
132
+ */
133
+ function adjustHolderBalance(t, addr, delta) {
134
+ if (isZeroAddr(addr) || delta === 0n)
135
+ return;
136
+ if (!t.holders)
137
+ t.holders = {};
138
+ const bal = BigInt(t.holders[addr] ?? '0') + delta;
139
+ if (bal <= 0n)
140
+ delete t.holders[addr];
141
+ else
142
+ t.holders[addr] = bal.toString();
143
+ }
81
144
  const isZeroAddr = (v) => {
82
145
  try {
83
146
  return BigInt(v ?? '0') === 0n;
@@ -106,6 +169,7 @@ export function foldSpine(events) {
106
169
  collectionFields: new Map(),
107
170
  collectionLocked: new Set(),
108
171
  maxInvocations: null,
172
+ defaultMaxSupply: null,
109
173
  minter: null,
110
174
  paused: false,
111
175
  primaryPayee: null,
@@ -113,6 +177,7 @@ export function foldSpine(events) {
113
177
  contractParams: new Map(),
114
178
  paramSchemas: new Map(),
115
179
  paramHooks: null,
180
+ paramHooksFrozen: false,
116
181
  delegateRegistry: undefined,
117
182
  seedSource: null,
118
183
  scriptLocked: false,
@@ -152,6 +217,35 @@ export function foldSpine(events) {
152
217
  t.minted = true; // mint signal
153
218
  break;
154
219
  }
220
+ case 'TransferSingle': {
221
+ applyEditionTransfer(fold.tokens, String(a.id ?? '0'), a.from, a.to, BigInt(a.amount ?? '0'));
222
+ break;
223
+ }
224
+ case 'TransferBatch': {
225
+ const ids = parseStringArray(a.ids);
226
+ const amounts = parseStringArray(a.amounts);
227
+ const from = a.from;
228
+ const to = a.to;
229
+ for (let i = 0; i < ids.length; i++) {
230
+ applyEditionTransfer(fold.tokens, ids[i], from, to, BigInt(amounts[i] ?? '0'));
231
+ }
232
+ break;
233
+ }
234
+ case 'MaxSupplyUpdated': {
235
+ const t = tokenIn(fold.tokens, String(a.id ?? '0'));
236
+ t.maxSupply = String(a.cap ?? '0');
237
+ // An override latches: it is what makes a `'0'` cap "closed forever" rather than "open",
238
+ // and what puts the monotonic never-increase rule in force for this id.
239
+ t.maxSupplyOverridden = true;
240
+ break;
241
+ }
242
+ // The collection-wide default, announced once at `initialize`. Last-writer-wins for the same
243
+ // reason as every other Register 2 setter, even though only one is emitted today. Without
244
+ // this case the event reached the ABI and stopped there: an id inheriting a non-zero default
245
+ // has no `MaxSupplyUpdated` of its own, so the fold reported it uncapped.
246
+ case 'DefaultMaxSupplySet':
247
+ fold.defaultMaxSupply = String(a.cap ?? '0');
248
+ break;
155
249
  case 'TokenFieldSet': {
156
250
  const id = String(a.tokenId ?? '0');
157
251
  const field = decodeTag((a.field ?? '0x'));
@@ -242,6 +336,7 @@ export function foldSpine(events) {
242
336
  configureHook: z(a.configureHook),
243
337
  augmentHook: z(a.augmentHook),
244
338
  transferHook: z(a.transferHook),
339
+ locked: false, // resolved from `paramHooksFrozen` at assembly — order-independent
245
340
  };
246
341
  break;
247
342
  }
@@ -254,6 +349,11 @@ export function foldSpine(events) {
254
349
  case 'ScriptLocked':
255
350
  fold.scriptLocked = true;
256
351
  break;
352
+ // A one-way lock like ScriptLocked/DependenciesLocked, and the one a BUYER cares about: after
353
+ // this the transfer hook (which can veto a transfer or a mint) can never be re-pointed.
354
+ case 'ParamHooksFrozen':
355
+ fold.paramHooksFrozen = true;
356
+ break;
257
357
  case 'DependencyUpdated': {
258
358
  const idx = Number(a.index ?? 0);
259
359
  const raw = (a.ref ?? '0x');
@@ -285,7 +385,7 @@ export function foldSpine(events) {
285
385
  return fold;
286
386
  }
287
387
  /** Build the full {@link ProjectState} from a fold + provenance, then overlay head reads. */
288
- async function assembleState(client, address, events, fold, fromBlock, toBlock, factory) {
388
+ async function assembleState(client, address, events, fold, fromBlock, toBlock, factory, readUriDocuments = false, reuseScript) {
289
389
  // ensure a TokenState exists for every token referenced by on-chain fields/locks/params
290
390
  // (a deployed-but-unminted token can carry fields before any Transfer)
291
391
  for (const id of fold.tokenFields.keys())
@@ -307,7 +407,9 @@ async function assembleState(client, address, events, fold, fromBlock, toBlock,
307
407
  t.params = [...params.values()];
308
408
  }
309
409
  // A contract is a Series if it enabled the supply-cap extension; a Series that also
310
- // speaks Params is a code project (SeriesCode's composition).
410
+ // speaks Params is a code project (SeriesCode's composition). `maxInvocations` is shared,
411
+ // unchanged, with the ERC-1155 editions family (EditionImage/EditionCode compose it too), so
412
+ // `isSeries` alone doesn't distinguish 721 from 1155 — `hasEditionSupply` does that.
311
413
  const isSeries = fold.extById.has(EXTENSION_ID.maxInvocations.toLowerCase());
312
414
  const has = (id) => fold.extById.has(id.toLowerCase());
313
415
  const hasParams = has(EXTENSION_ID.params);
@@ -315,6 +417,22 @@ async function assembleState(client, address, events, fold, fromBlock, toBlock,
315
417
  const hasScript = has(EXTENSION_ID.onChainScript);
316
418
  const hasDependencies = has(EXTENSION_ID.dependencies);
317
419
  const hasSeedSource = has(EXTENSION_ID.seedSource);
420
+ // Edition Supply is the ONLY extension id new to the 1155 family — its presence is the
421
+ // discriminator between the 721 ladder (1of1/series/code) and the 1155 one
422
+ // (1of1-edition/edition/edition-code); every other extension id is shared, unchanged.
423
+ const hasEditionSupply = has(EXTENSION_ID.editionSupply);
424
+ // The collection-wide per-id default, behind the same gate as every other extension-scoped field
425
+ // (one gate, read twice: here and on `state.defaultMaxSupply` below).
426
+ const defaultCap = hasEditionSupply ? fold.defaultMaxSupply : null;
427
+ // An id with no `MaxSupplyUpdated` of its own inherits that default, exactly as `maxSupply(id)`
428
+ // does on chain. The fold used to stop at the per-id event, so every `--copies N` edition — which
429
+ // sets the cap at `initialize` and never calls `setMaxSupply` — reported *uncapped* here while the
430
+ // head read said N. See {@link TokenState.maxSupply}.
431
+ if (defaultCap !== null) {
432
+ for (const t of fold.tokens.values())
433
+ if (t.maxSupply === undefined)
434
+ t.maxSupply = defaultCap;
435
+ }
318
436
  const state = {
319
437
  address,
320
438
  chainId: client.chain?.id ?? 0,
@@ -335,15 +453,25 @@ async function assembleState(client, address, events, fold, fromBlock, toBlock,
335
453
  royalty: fold.royalty,
336
454
  collectionFields: [...fold.collectionFields.values()],
337
455
  lockedCollectionFields: [...fold.collectionLocked],
338
- contractType: fold.deployBlock !== null ? (isSeries ? (hasParams ? 'code' : 'series') : '1of1') : undefined,
456
+ contractType: fold.deployBlock === null
457
+ ? undefined
458
+ : hasEditionSupply
459
+ ? hasParams ? 'edition-code' : isSeries ? 'edition' : '1of1-edition'
460
+ : isSeries ? (hasParams ? 'code' : 'series') : '1of1',
339
461
  maxInvocations: fold.maxInvocations,
462
+ defaultMaxSupply: defaultCap,
340
463
  minter: fold.minter,
341
464
  paused: fold.paused,
342
465
  primaryPayee: fold.primaryPayee,
343
466
  contractParams: hasParams ? [...fold.contractParams.values()] : undefined,
344
467
  paramSchemas: hasConfigurableParams ? [...fold.paramSchemas.values()] : undefined,
345
468
  paramHooks: hasConfigurableParams
346
- ? (fold.paramHooks ?? { configureHook: null, augmentHook: null, transferHook: null })
469
+ ? {
470
+ ...(fold.paramHooks ?? { configureHook: null, augmentHook: null, transferHook: null }),
471
+ // Read off the separate fold flag rather than the HooksConfigured branch, so a freeze
472
+ // survives regardless of event order (a project may freeze hooks it never set).
473
+ locked: fold.paramHooksFrozen,
474
+ }
347
475
  : null,
348
476
  // absence of the event ⇒ the canonical delegate.xyz default (the emit-non-default rule)
349
477
  delegateRegistry: hasConfigurableParams
@@ -369,13 +497,16 @@ async function assembleState(client, address, events, fold, fromBlock, toBlock,
369
497
  reconstructedAt: new Date().toISOString(),
370
498
  rpcUrl: client.transport?.url,
371
499
  };
372
- await applyHeadReads(client, state, factory);
500
+ await applyHeadReads(client, state, factory, readUriDocuments, reuseScript);
373
501
  return state;
374
502
  }
375
- /** Default safety cap on chunk count; raise via ABX_GETLOGS_MAX_CHUNKS (the CLI's --yes does). */
503
+ /** Default safety cap on chunk count; raise via the `maxChunks` opt (or ABX_GETLOGS_MAX_CHUNKS —
504
+ * the CLI's --yes sets that). */
376
505
  const DEFAULT_MAX_CHUNKS = 3000;
377
- function maxChunks() {
378
- const v = Number(process.env.ABX_GETLOGS_MAX_CHUNKS);
506
+ function resolveMaxChunks(override) {
507
+ if (override !== undefined && override > 0)
508
+ return override;
509
+ const v = Number(readEnv('ABX_GETLOGS_MAX_CHUNKS'));
379
510
  return Number.isFinite(v) && v > 0 ? v : DEFAULT_MAX_CHUNKS;
380
511
  }
381
512
  /** Does this error look like an RPC rejecting the block range (vs a real failure)? */
@@ -384,7 +515,7 @@ export function isGetLogsRangeError(err) {
384
515
  return /block range|range should work|too large|out of bounds|response size|query returned more|results|limited|\d+\s*block|exceeds|max(imum)?\b/.test(m);
385
516
  }
386
517
  /** Thrown when a reconstruction would need more getLogs requests than the cap allows. */
387
- export class GetLogsScanTooLargeError extends Error {
518
+ export class GetLogsScanTooLargeError extends AbxSdkError {
388
519
  spanBlocks;
389
520
  window;
390
521
  estimatedRequests;
@@ -439,121 +570,275 @@ export async function discoverDeployBlock(client, address, toBlock) {
439
570
  }
440
571
  }
441
572
  /**
442
- * Pull a contract's logs over a block range, adapting to RPC range caps. Providers
443
- * cap `eth_getLogs` very differently and the numbers change, so we don't hard-code a
444
- * window: try the whole range, and when the RPC rejects it, halve the window and
445
- * sweep — adopting the smaller window for the rest of the run. So reconstruction is a
446
- * single request on a generous RPC, still completes on a constrained one, and (for a
447
- * 1/1, whose events cluster at the deploy block) stays cheap. `ABX_GETLOGS_RANGE`
448
- * overrides the starting window.
573
+ * Ordinary RPC tiers cap how many addresses one `eth_getLogs` filter may carry.
574
+ * This is an RPC-tier opinion, not a protocol constant — callers with a dedicated
575
+ * node can raise it; `0` disables splitting (one filter for the whole list).
576
+ */
577
+ export const DEFAULT_GETLOGS_ADDRESS_BATCH = 1000;
578
+ /**
579
+ * Pull logs over a block range, adapting to RPC range caps — and, when `address` is
580
+ * a list, splitting that list so a registered-set watch scan stays one code path for
581
+ * self-host and hosted. Providers cap `eth_getLogs` very differently and the numbers
582
+ * change, so we don't hard-code a window: try the whole range, and when the RPC
583
+ * rejects it, halve the window and sweep. `ABX_GETLOGS_RANGE` overrides the starting
584
+ * window. Address-list chunking is a separate cap (`addressBatch`); 5000-block
585
+ * per-tick windows belong to the caller (the watcher), not here.
449
586
  *
450
587
  * Once the working window is known we estimate the whole job *before* grinding it: if
451
588
  * it would exceed the cap, we stop early (only the probe calls spent) and throw
452
589
  * {@link GetLogsScanTooLargeError} so the caller can offer the real fix (a higher-range
453
590
  * RPC) or an explicit opt-in to chunk through it.
454
591
  */
455
- async function getLogsAdaptive(client, address, fromBlock, toBlock) {
592
+ export async function getLogsAdaptive(client, address, fromBlock, toBlock, opts = {}) {
593
+ const addrs = (Array.isArray(address) ? address : [address]);
594
+ if (addrs.length === 0)
595
+ return [];
596
+ const batchSize = opts.addressBatch === 0 ? addrs.length : Math.max(1, opts.addressBatch ?? DEFAULT_GETLOGS_ADDRESS_BATCH);
597
+ const batches = [];
598
+ for (let i = 0; i < addrs.length; i += batchSize)
599
+ batches.push(addrs.slice(i, i + batchSize));
456
600
  const span = toBlock - fromBlock + 1n;
457
- const envRange = process.env.ABX_GETLOGS_RANGE;
458
- let window = envRange && BigInt(envRange) > 0n ? BigInt(envRange) : span;
601
+ const envRange = readEnv('ABX_GETLOGS_RANGE');
602
+ const startWindow = opts.range && opts.range > 0n ? opts.range : envRange && BigInt(envRange) > 0n ? BigInt(envRange) : span;
459
603
  const out = [];
460
- let start = fromBlock;
461
604
  let estimated = false;
462
- while (start <= toBlock) {
463
- const end = start + window - 1n < toBlock ? start + window - 1n : toBlock;
464
- let logs;
605
+ for (const batch of batches) {
606
+ const filter = batch.length === 1 ? batch[0] : batch;
607
+ let window = startWindow;
608
+ let start = fromBlock;
609
+ while (start <= toBlock) {
610
+ const end = start + window - 1n < toBlock ? start + window - 1n : toBlock;
611
+ let logs;
612
+ try {
613
+ logs = (await client.getLogs({ address: filter, fromBlock: start, toBlock: end }));
614
+ }
615
+ catch (err) {
616
+ if (isGetLogsRangeError(err) && window > 1n) {
617
+ window = window > 2n ? window / 2n : 1n; // RPC rejected this window — shrink and retry
618
+ continue;
619
+ }
620
+ throw err; // genuine failure, or already at one block per call
621
+ }
622
+ out.push(...logs);
623
+ start = end + 1n;
624
+ // Window now proven. Estimate the whole job once (range chunks × address batches)
625
+ // and bail *before* grinding if absurd.
626
+ if (!estimated) {
627
+ estimated = true;
628
+ const remaining = toBlock - start + 1n;
629
+ const perBatch = (remaining > 0n ? Number(remaining / window) + 1 : 0) + 1; // +1 for the chunk just done
630
+ const need = perBatch * batches.length;
631
+ const cap = resolveMaxChunks(opts.maxChunks);
632
+ if (need > cap)
633
+ throw new GetLogsScanTooLargeError(span, window, need, cap);
634
+ }
635
+ }
636
+ }
637
+ return out;
638
+ }
639
+ /**
640
+ * How many unbounded reads (`tokenURI`, `contractURI`, a script chunk) ride one aggregate. Small on
641
+ * purpose: on the on-chain lane each of these can return tens of KB *assembled at read*, and the
642
+ * cap that matters is the node's per-`eth_call` budget for the aggregate, not the leg count. A
643
+ * whole-chunk failure still recovers via the per-leg retry below, so this only sets how often that
644
+ * costs an extra round trip.
645
+ */
646
+ const HEAVY_READ_CHUNK = 2;
647
+ /**
648
+ * Multicall in chunks, tolerating per-leg failure — and, when a whole chunk comes back failed,
649
+ * retrying its legs individually before believing it.
650
+ *
651
+ * The retry is the point, and it exists to tell apart two failure modes that an aggregate throwing
652
+ * cannot distinguish on its own:
653
+ *
654
+ * 1. **Over budget.** `allowFailure: true` reports per-leg failures, but a multicall is ONE
655
+ * `eth_call`: if the aggregate exceeds the node's gas or response cap, the *whole* batch fails
656
+ * and every leg in it reports failure — including legs that answer fine on their own. Batching a
657
+ * cheap read beside an expensive one therefore turns the expensive one's cost into the cheap
658
+ * one's failure. Re-asking each leg alone, with no aggregate overhead, recovers this: the calls
659
+ * were always fine, only their batching was too big.
660
+ * 2. **No multicall3 on this chain.** If the aggregate fails because there's no multicall3
661
+ * deployment to call at all, *every* multicall — including a single-leg one — fails the identical
662
+ * way. Re-asking through `client.multicall` again, at any width, reproduces the same failure, so
663
+ * the retry must go through a call shape that has no multicall3 dependency: `client.readContract`.
664
+ * Skipping this means a chain lacking multicall3 reads back as "the contract answered nothing" —
665
+ * indistinguishable from a real revert — which is exactly the silent-blank-identity bug this
666
+ * retry was reported to have.
667
+ *
668
+ * So the fallback always resolves each leg with `readContract`, never with a smaller `multicall`.
669
+ * `readContract` throws on revert where multicall's `allowFailure` returns a `status: 'failure'`
670
+ * result instead, so a per-leg throw here is caught and mapped back to `null` — a genuine revert on
671
+ * one leg must still read as "that leg has no answer," matching the aggregate's own contract,
672
+ * whichever call shape actually answered it.
673
+ */
674
+ export async function multicallChunked(client, contracts, chunkSize) {
675
+ const out = new Array(contracts.length).fill(null);
676
+ const runAggregate = async (legs) => {
465
677
  try {
466
- logs = (await client.getLogs({ address, fromBlock: start, toBlock: end }));
678
+ const res = (await client.multicall({ contracts: legs, allowFailure: true }));
679
+ return res.map((r) => (r.status === 'success' ? r.result : null));
467
680
  }
468
- catch (err) {
469
- if (isGetLogsRangeError(err) && window > 1n) {
470
- window = window > 2n ? window / 2n : 1n; // RPC rejected this window — shrink and retry
471
- continue;
472
- }
473
- throw err; // genuine failure, or already at one block per call
681
+ catch {
682
+ return legs.map(() => null); // the aggregate itself failed
474
683
  }
475
- out.push(...logs);
476
- start = end + 1n;
477
- // Window now proven. Estimate the whole job once and bail *before* grinding if absurd.
478
- if (!estimated) {
479
- estimated = true;
480
- const remaining = toBlock - start + 1n;
481
- const need = (remaining > 0n ? Number(remaining / window) + 1 : 0) + 1; // +1 for the chunk just done
482
- const cap = maxChunks();
483
- if (need > cap)
484
- throw new GetLogsScanTooLargeError(span, window, need, cap);
684
+ };
685
+ const readOne = async (leg) => {
686
+ try {
687
+ return await client.readContract(leg);
688
+ }
689
+ catch {
690
+ return null; // a genuine revert — or the fallback itself failing — reads the same as unreadable
691
+ }
692
+ };
693
+ for (let i = 0; i < contracts.length; i += chunkSize) {
694
+ const legs = contracts.slice(i, i + chunkSize);
695
+ let vals = await runAggregate(legs);
696
+ // Every leg failed: the aggregate itself is the likely cause (too costly, or no multicall3 to
697
+ // call at all), not the individual reads. Re-ask one at a time via `readContract` — never via
698
+ // `multicall` again, even for a lone leg — so the batch degrades to what genuinely can't be
699
+ // read, whether the original cause was cost or an absent multicall3. (A chunk can land at width
700
+ // 1 too, e.g. the last chunk of an odd-length list — that leg is exactly as exposed to "no
701
+ // multicall3 here" as any other, so it gets the same fallback, not a pass.)
702
+ if (vals.every((v) => v === null)) {
703
+ vals = await Promise.all(legs.map(readOne));
485
704
  }
705
+ for (let k = 0; k < vals.length; k++)
706
+ out[i + k] = vals[k];
486
707
  }
487
708
  return out;
488
709
  }
489
- /** Multicall the read surface to resolve current string values + trust facts. */
490
- async function applyHeadReads(client, state, factory) {
710
+ /**
711
+ * Head-read the values the spine only pings (name/symbol/contractURI/tokenURI) plus the trust and
712
+ * URI-lane facts, and fold them into state.
713
+ *
714
+ * **Reads are split by cost class, and that split is load-bearing.** These used to be one multicall,
715
+ * which was correct for an off-chain project (every return is a short string) and quietly wrong for
716
+ * the flagship on-chain lane: there, `tokenURI(id)` *assembles the whole metadata document
717
+ * on-chain*, tens of KB per token. Four such legs in one aggregate already exceed a public node's
718
+ * `eth_call` budget, so the batch failed whole — and took `name`, `symbol`, `contractURI`,
719
+ * `isAbxClone`, and, worst, `tokenURIRenderer` down with it. A resolver then believed a
720
+ * fully-on-chain 32-token collection had no name, no canonical proof, and **was not in the
721
+ * on-chain-URI lane at all.** Reproduced on Base Sepolia at `0xB844…5E56`: 4 legs → 0/8 succeeded,
722
+ * while `name()` answered `"ABXdoku"` on its own.
723
+ *
724
+ * So: the cheap fixed reads — the ones that decide the project's identity and lane — go in one
725
+ * batch of their own and can never be collateral damage.
726
+ *
727
+ * **The unbounded pair (`contractURI` + one `tokenURI` per token) is diagnostic and opt-in
728
+ * (`readUriDocuments`, default `false`) — skipped ENTIRELY unless requested, not just best-effort.**
729
+ * Two independent reasons, not one:
730
+ *
731
+ * 1. **Size.** A real 32-token fully-on-chain project measured at 13.4 MB of serialized
732
+ * `ProjectState`, of which 99.8% was `tokens[].tokenURI` — ~313 KB/token, re-fetched on *every*
733
+ * reconstruct, full or incremental, to fold a single new mint. `contractURI` is the same shape at
734
+ * collection scope (~1 KB there, but proportionally as dominant once `tokenURI` is out of the
735
+ * picture). (abx-services 2026-08-05 projection memo, `docs/11`.)
736
+ * 2. **No settled value.** A renderer that composes these on demand can change them with **no log at
737
+ * all** — the refresh trigger here is `getLogs`, and there is no event for "the composed document
738
+ * changed." A value with no settled state and no change signal cannot be cached correctly at any
739
+ * refresh cadence: too eager and every tick looks different (a real incident); too lazy and the
740
+ * cached copy silently rots. The only correct move is not to cache it — read it live when someone
741
+ * actually wants to display it (`nothing served depends on it`, the one exception being a fresh
742
+ * `abx demo` read-back, which asks for it explicitly).
743
+ */
744
+ async function applyHeadReads(client, state, factory, readUriDocuments = false, reuseScript) {
491
745
  const token = { address: state.address, abi: oneOfOneImageAbi };
492
746
  const tokenIds = state.tokens.map((t) => t.tokenId);
747
+ // The edition family (ERC-1155) shares every cheap fixed-return name with the 721 superset ABI
748
+ // used below (name/symbol/owner/tokenURIRenderer/tokenURILocked/contractURIRenderer/
749
+ // contractURILocked/contractURI — same signatures on both standards), EXCEPT the per-token URI
750
+ // getter: editions expose `uri(id)`, not `tokenURI(id)` (ERC-1155 has no `tokenURI`). Encode
751
+ // that one leg against an edition ABI instead; the field name on `TokenState` stays `tokenURI`
752
+ // either way (it's the resolved metadata pointer regardless of which standard produced it).
753
+ const isEdition = state.contractType === '1of1-edition' || state.contractType === 'edition' || state.contractType === 'edition-code';
754
+ const uriAbi = isEdition ? oneOfOneEditionAbi : oneOfOneImageAbi;
755
+ const uriFn = isEdition ? 'uri' : 'tokenURI';
756
+ // ── cheap, fixed-size returns: identity, trust, the URI lane, the script count ──
493
757
  // Mixed-ABI multicall — type it loosely; results are validated per-call below.
494
- const contracts = [
758
+ const cheap = [
495
759
  { ...token, functionName: 'name' },
496
760
  { ...token, functionName: 'symbol' },
497
761
  { ...token, functionName: 'owner' },
498
- { ...token, functionName: 'contractURI' },
499
- ...tokenIds.map((id) => ({ ...token, functionName: 'tokenURI', args: [BigInt(id)] })),
762
+ { ...token, functionName: 'tokenURIRenderer' },
763
+ { ...token, functionName: 'tokenURILocked' },
764
+ { ...token, functionName: 'contractURIRenderer' },
765
+ { ...token, functionName: 'contractURILocked' },
500
766
  ];
767
+ const factoryIdx = cheap.length;
501
768
  if (factory) {
502
- contracts.push({ address: factory, abi: oneOfOneImageFactoryAbi, functionName: 'isAbxClone', args: [state.address] }, { address: factory, abi: oneOfOneImageFactoryAbi, functionName: 'implementation' });
769
+ cheap.push({ address: factory, abi: oneOfOneImageFactoryAbi, functionName: 'isAbxClone', args: [state.address] }, { address: factory, abi: oneOfOneImageFactoryAbi, functionName: 'implementation' });
503
770
  }
504
- // URI resolution config (the off-chain↔on-chain toggle + freeze)
505
- const cfgBase = contracts.length;
506
- contracts.push({ ...token, functionName: 'tokenURIRenderer' }, { ...token, functionName: 'tokenURILocked' }, { ...token, functionName: 'contractURIRenderer' }, { ...token, functionName: 'contractURILocked' });
507
771
  // On-chain script: chunk content is too large to log, so the count is a head read.
508
- const scriptIdx = contracts.length;
509
- if (state.script) {
510
- contracts.push({ address: state.address, abi: seriesCodeAbi, functionName: 'scriptChunkCount' });
772
+ // Skip when the caller already holds a digest and `fresh` had no `ScriptUpdated` —
773
+ // a Transfer must not re-download every chunk.
774
+ const keepPriorScript = !!(state.script && reuseScript?.digest != null);
775
+ const scriptIdx = cheap.length;
776
+ if (state.script && !keepPriorScript) {
777
+ cheap.push({ address: state.address, abi: seriesCodeAbi, functionName: 'scriptChunkCount' });
511
778
  }
512
- const results = (await client.multicall({
513
- contracts: contracts,
514
- allowFailure: true,
515
- }));
516
- const val = (i) => (results[i]?.status === 'success' ? results[i].result : null);
779
+ // ── unbounded returns: each one may assemble a whole document on-chain ──
780
+ // `contractURI` first so a huge per-token tokenURI can never cost us the collection's own URI.
781
+ // `contractURI` itself is standard-neutral (ContractURI is reused as-is on the edition family),
782
+ // so only the per-token leg switches ABI/function name (see `uriAbi`/`uriFn` above).
783
+ //
784
+ // Skipped ENTIRELY when `readUriDocuments` is false (the default) — not requested at reduced
785
+ // width, not requested-then-discarded: no `eth_call` for either leg. `state.contractURI` and
786
+ // every `tok.tokenURI` stay `null`, same as an off-chain project with nothing to read.
787
+ const heavy = readUriDocuments
788
+ ? [
789
+ { ...token, functionName: 'contractURI' },
790
+ ...tokenIds.map((id) => ({ address: state.address, abi: uriAbi, functionName: uriFn, args: [BigInt(id)] })),
791
+ ]
792
+ : [];
793
+ const [cheapVals, heavyVals] = await Promise.all([
794
+ multicallChunked(client, cheap, cheap.length), // one batch: all short returns
795
+ readUriDocuments ? multicallChunked(client, heavy, HEAVY_READ_CHUNK) : Promise.resolve([]),
796
+ ]);
797
+ const val = (i) => cheapVals[i] ?? null;
517
798
  state.name = val(0) ?? null;
518
799
  state.symbol = val(1) ?? null;
519
800
  state.owner = val(2) ?? state.owner;
520
- state.contractURI = val(3) ?? null;
521
- tokenIds.forEach((id, k) => {
522
- const tok = state.tokens.find((t) => t.tokenId === id);
523
- if (tok)
524
- tok.tokenURI = val(4 + k) ?? null;
525
- });
801
+ const nonZero = (a) => a && a !== '0x0000000000000000000000000000000000000000' ? a : null;
802
+ state.tokenURIRenderer = nonZero(val(3));
803
+ state.tokenURILocked = val(4) ?? null;
804
+ state.contractURIRenderer = nonZero(val(5));
805
+ state.contractURILocked = val(6) ?? null;
526
806
  if (factory) {
527
- const base = 4 + tokenIds.length;
528
- state.isCanonical = val(base) ?? null;
529
- state.implementation = val(base + 1) ?? null;
807
+ state.isCanonical = cheapVals[factoryIdx] ?? null;
808
+ state.implementation = cheapVals[factoryIdx + 1] ?? null;
530
809
  }
531
- const nonZero = (a) => a && a !== '0x0000000000000000000000000000000000000000' ? a : null;
532
- state.tokenURIRenderer = nonZero(val(cfgBase));
533
- state.tokenURILocked = val(cfgBase + 1) ?? null;
534
- state.contractURIRenderer = nonZero(val(cfgBase + 2));
535
- state.contractURILocked = val(cfgBase + 3) ?? null;
536
- if (state.script) {
537
- const count = val(scriptIdx);
810
+ // `tok.tokenURI` is already `null` from `tokenIn` — only overwrite it when we actually asked.
811
+ if (readUriDocuments) {
812
+ state.contractURI = heavyVals[0] ?? null;
813
+ tokenIds.forEach((id, k) => {
814
+ const tok = state.tokens.find((t) => t.tokenId === id);
815
+ if (tok)
816
+ tok.tokenURI = heavyVals[1 + k] ?? null;
817
+ });
818
+ }
819
+ if (state.script && keepPriorScript) {
820
+ state.script.chunkCount = reuseScript.chunkCount;
821
+ state.script.digest = reuseScript.digest;
822
+ }
823
+ else if (state.script) {
824
+ const count = cheapVals[scriptIdx] ?? null;
538
825
  state.script.chunkCount = count === null ? null : Number(count);
539
826
  // digest = keccak over the concatenated chunks — the content half of effect inputsHash
540
- // values. Chunks are few and bounded (~24 KB each), so this is a cheap second multicall.
827
+ // values. Chunks are bounded (~24 KB each) but there can be many, and the same aggregate cap
828
+ // applies, so they read through the chunked path too.
541
829
  const n = state.script.chunkCount ?? 0;
542
830
  if (n > 0) {
543
- const chunkReads = (await client.multicall({
544
- contracts: Array.from({ length: n }, (_, i) => ({
545
- address: state.address,
546
- abi: seriesCodeAbi,
547
- functionName: 'scriptChunk',
548
- args: [BigInt(i)],
549
- })),
550
- allowFailure: true,
551
- }));
831
+ const chunkReads = await multicallChunked(client, Array.from({ length: n }, (_, i) => ({
832
+ address: state.address,
833
+ abi: seriesCodeAbi,
834
+ functionName: 'scriptChunk',
835
+ args: [BigInt(i)],
836
+ })), HEAVY_READ_CHUNK);
552
837
  const parts = [];
553
838
  for (const r of chunkReads) {
554
- if (r.status !== 'success')
839
+ if (r === null)
555
840
  return; // partial read — leave digest unset rather than wrong
556
- parts.push(r.result);
841
+ parts.push(r);
557
842
  }
558
843
  state.script.digest = keccak256(concatHex(parts));
559
844
  }