@attocash/cli 0.2.3 → 0.3.0

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 (137) hide show
  1. package/README.md +148 -7
  2. package/dist/application/app.d.ts +34 -3
  3. package/dist/application/app.js +138 -126
  4. package/dist/application/operations.d.ts +3 -0
  5. package/dist/application/operations.js +30 -8
  6. package/dist/cli/cli.d.ts +1 -0
  7. package/dist/cli/cli.js +101 -13
  8. package/dist/cli/onboarding.d.ts +13 -0
  9. package/dist/cli/onboarding.js +99 -2
  10. package/dist/cli/output.js +18 -2
  11. package/dist/doctor/profile.js +2 -1
  12. package/dist/internal-marketplace.d.ts +25 -0
  13. package/dist/internal-marketplace.js +50 -0
  14. package/dist/marketplace/approval-files.d.ts +3 -0
  15. package/dist/marketplace/approval-files.js +97 -0
  16. package/dist/marketplace/approval-preview.d.ts +2 -0
  17. package/dist/marketplace/approval-preview.js +86 -0
  18. package/dist/marketplace/proof-approval.d.ts +82 -0
  19. package/dist/marketplace/proof-approval.js +671 -0
  20. package/dist/marketplace/topups.d.ts +82 -0
  21. package/dist/marketplace/topups.js +485 -0
  22. package/dist/network/batching.d.ts +2 -0
  23. package/dist/network/batching.js +23 -0
  24. package/dist/network/entry.d.ts +2 -0
  25. package/dist/network/entry.js +35 -0
  26. package/dist/network/reader.d.ts +2 -0
  27. package/dist/network/reader.js +125 -37
  28. package/dist/spending/approval.d.ts +5 -0
  29. package/dist/spending/approval.js +2 -0
  30. package/dist/spending/atto-x402.d.ts +31 -0
  31. package/dist/spending/atto-x402.js +174 -0
  32. package/dist/spending/ledger.d.ts +74 -2
  33. package/dist/spending/ledger.js +298 -7
  34. package/dist/spending/payments.d.ts +105 -5
  35. package/dist/spending/payments.js +795 -11
  36. package/dist/storage/recovery-seed.d.ts +13 -0
  37. package/dist/storage/recovery-seed.js +93 -0
  38. package/dist/storage/state.d.ts +4 -0
  39. package/dist/storage/state.js +32 -2
  40. package/dist/wallet/receive.d.ts +39 -0
  41. package/dist/wallet/receive.js +264 -0
  42. package/dist/wallet/signing.d.ts +1 -0
  43. package/dist/wallet/signing.js +37 -21
  44. package/dist/wallet/types.d.ts +1 -0
  45. package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs +1922 -1918
  46. package/node_modules/@attocash/commons-core/Kotlin-DateTime-library-kotlinx-datetime.mjs.map +1 -1
  47. package/node_modules/@attocash/commons-core/README.md +9 -0
  48. package/node_modules/@attocash/commons-core/commons-commons-core.d.mts +10 -0
  49. package/node_modules/@attocash/commons-core/commons-commons-core.mjs +2543 -2434
  50. package/node_modules/@attocash/commons-core/commons-commons-core.mjs.map +1 -1
  51. package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs +4695 -4227
  52. package/node_modules/@attocash/commons-core/kotlin-kotlin-stdlib.mjs.map +1 -1
  53. package/node_modules/@attocash/commons-core/kotlin_org_jetbrains_kotlin_kotlin_dom_api_compat.mjs.map +1 -1
  54. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs +60 -60
  55. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-bytestring.mjs.map +1 -1
  56. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs +651 -631
  57. package/node_modules/@attocash/commons-core/kotlinx-io-kotlinx-io-core.mjs.map +1 -1
  58. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs +2294 -2295
  59. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-core.mjs.map +1 -1
  60. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  61. package/node_modules/@attocash/commons-core/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  62. package/node_modules/@attocash/commons-core/package.json +1 -1
  63. package/node_modules/@attocash/commons-node/commons-commons-node.d.mts +1 -0
  64. package/node_modules/@attocash/commons-node/commons-commons-node.mjs +873 -847
  65. package/node_modules/@attocash/commons-node/commons-commons-node.mjs.map +1 -1
  66. package/node_modules/@attocash/commons-node/kotlin-logging.mjs +109 -109
  67. package/node_modules/@attocash/commons-node/kotlin-logging.mjs.map +1 -1
  68. package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  69. package/node_modules/@attocash/commons-node/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  70. package/node_modules/@attocash/commons-node/package.json +3 -3
  71. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.d.mts +1 -0
  72. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs +674 -640
  73. package/node_modules/@attocash/commons-node-remote/commons-commons-node-remote.mjs.map +1 -1
  74. package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs +109 -109
  75. package/node_modules/@attocash/commons-node-remote/kotlin-logging.mjs.map +1 -1
  76. package/node_modules/@attocash/commons-node-remote/kotlinx-browser.mjs.map +1 -1
  77. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  78. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  79. package/node_modules/@attocash/commons-node-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  80. package/node_modules/@attocash/commons-node-remote/package.json +4 -4
  81. package/node_modules/@attocash/commons-transport/commons-commons-transport.d.mts +1 -0
  82. package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs +52 -51
  83. package/node_modules/@attocash/commons-transport/commons-commons-transport.mjs.map +1 -1
  84. package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs +13 -13
  85. package/node_modules/@attocash/commons-transport/kotlinx-atomicfu.mjs.map +1 -1
  86. package/node_modules/@attocash/commons-transport/kotlinx-browser.mjs.map +1 -1
  87. package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs +2639 -2608
  88. package/node_modules/@attocash/commons-transport/kotlinx-coroutines-core.mjs.map +1 -1
  89. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  90. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  91. package/node_modules/@attocash/commons-transport/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  92. package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs +411 -196
  93. package/node_modules/@attocash/commons-transport/ktor-ktor-client-content-negotiation.mjs.map +1 -1
  94. package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs +2115 -1976
  95. package/node_modules/@attocash/commons-transport/ktor-ktor-client-core.mjs.map +1 -1
  96. package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs +7 -7
  97. package/node_modules/@attocash/commons-transport/ktor-ktor-events.mjs.map +1 -1
  98. package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs +385 -384
  99. package/node_modules/@attocash/commons-transport/ktor-ktor-http-cio.mjs.map +1 -1
  100. package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs +1261 -1185
  101. package/node_modules/@attocash/commons-transport/ktor-ktor-http.mjs.map +1 -1
  102. package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs +668 -656
  103. package/node_modules/@attocash/commons-transport/ktor-ktor-io.mjs.map +1 -1
  104. package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs +89 -0
  105. package/node_modules/@attocash/commons-transport/ktor-ktor-openapi-schema.mjs.map +1 -0
  106. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs +9 -9
  107. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx-json.mjs.map +1 -1
  108. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs +120 -128
  109. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization-kotlinx.mjs.map +1 -1
  110. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs +46 -49
  111. package/node_modules/@attocash/commons-transport/ktor-ktor-serialization.mjs.map +1 -1
  112. package/node_modules/@attocash/commons-transport/ktor-ktor-sse.mjs.map +1 -1
  113. package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs +1041 -985
  114. package/node_modules/@attocash/commons-transport/ktor-ktor-utils.mjs.map +1 -1
  115. package/node_modules/@attocash/commons-transport/ktor-ktor-websocket-serialization.mjs.map +1 -1
  116. package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs +530 -455
  117. package/node_modules/@attocash/commons-transport/ktor-ktor-websockets.mjs.map +1 -1
  118. package/node_modules/@attocash/commons-transport/package.json +4 -4
  119. package/node_modules/@attocash/commons-worker/commons-commons-worker.d.mts +1 -0
  120. package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs +230 -226
  121. package/node_modules/@attocash/commons-worker/commons-commons-worker.mjs.map +1 -1
  122. package/node_modules/@attocash/commons-worker/kotlin-logging.mjs +109 -109
  123. package/node_modules/@attocash/commons-worker/kotlin-logging.mjs.map +1 -1
  124. package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  125. package/node_modules/@attocash/commons-worker/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  126. package/node_modules/@attocash/commons-worker/package.json +3 -3
  127. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.d.mts +1 -0
  128. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs +91 -86
  129. package/node_modules/@attocash/commons-worker-remote/commons-commons-worker-remote.mjs.map +1 -1
  130. package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs +109 -109
  131. package/node_modules/@attocash/commons-worker-remote/kotlin-logging.mjs.map +1 -1
  132. package/node_modules/@attocash/commons-worker-remote/kotlinx-browser.mjs.map +1 -1
  133. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json-io.mjs.map +1 -1
  134. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs +1732 -1701
  135. package/node_modules/@attocash/commons-worker-remote/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  136. package/node_modules/@attocash/commons-worker-remote/package.json +4 -4
  137. package/package.json +9 -5
@@ -5,6 +5,8 @@ import { AccountHeightSearch, HeightSearch } from '@attocash/commons-node';
5
5
  import { AttoNodeClientAsyncBuilder } from '@attocash/commons-node-remote';
6
6
  import { AttoError } from '../domain/errors.js';
7
7
  import { amountRaw } from '../domain/amount.js';
8
+ import { publicEntry } from './entry.js';
9
+ import { resolveNodeBatchSize } from './batching.js';
8
10
  // Ktor's Node engine uses require while Commons is imported as ESM.
9
11
  Object.assign(globalThis, { require: createRequire(import.meta.url) });
10
12
  const MAX_RESPONSE_BYTES = 1024 * 1024;
@@ -24,9 +26,9 @@ export function publicModel(model) {
24
26
  if (model === null || model === undefined)
25
27
  return null;
26
28
  if (typeof model === 'object' && 'toJson' in model && typeof model.toJson === 'function') {
27
- return jsonExact(model.toJson());
29
+ return publicEntry(jsonExact(model.toJson()));
28
30
  }
29
- return jsonExact(JSON.stringify(model, (_key, value) => typeof value === 'bigint' ? value.toString() : value));
31
+ return publicEntry(jsonExact(JSON.stringify(model, (_key, value) => typeof value === 'bigint' ? value.toString() : value)));
30
32
  }
31
33
  export function parseAddress(value) {
32
34
  try {
@@ -94,11 +96,11 @@ export class NodeReader {
94
96
  this.settings = settings;
95
97
  this.headers = headers;
96
98
  }
97
- async request(path, signal, firstEvent) {
99
+ async request(path, signal, firstEvent, body) {
98
100
  try {
99
101
  const response = await fetch(`${this.settings.nodeUrl.replace(/\/$/, '')}/${path}`, {
100
- redirect: 'error', signal,
101
- headers: { ...this.headers, accept: firstEvent ? 'application/x-ndjson' : 'application/json' },
102
+ redirect: 'error', signal, ...(body ? { method: 'POST', body } : {}),
103
+ headers: { ...this.headers, ...(body ? { 'content-type': 'application/json' } : {}), accept: firstEvent ? 'application/x-ndjson' : 'application/json' },
102
104
  });
103
105
  if (!response.ok) {
104
106
  await response.body?.cancel();
@@ -116,11 +118,11 @@ export class NodeReader {
116
118
  }
117
119
  // Commons' Promise reads do not expose cancellation or HTTP status; finite
118
120
  // lookups retain those caller contracts here.
119
- async get(path, parse, signal, firstEvent = false) {
121
+ async get(path, parse, signal, firstEvent = false, requestBody) {
120
122
  const timeout = AbortSignal.timeout(10_000);
121
123
  const combined = signal ? AbortSignal.any([signal, timeout]) : timeout;
122
124
  try {
123
- const response = await this.request(path, combined, firstEvent);
125
+ const response = await this.request(path, combined, firstEvent, requestBody);
124
126
  let body = '';
125
127
  const decoder = new TextDecoder();
126
128
  let size = 0;
@@ -171,6 +173,32 @@ export class NodeReader {
171
173
  account(address, signal) {
172
174
  return this.get(`accounts/${parseAddress(address).publicKey}`, AttoAccount.fromJson, signal);
173
175
  }
176
+ async accounts(addresses, signal) {
177
+ const batchSize = resolveNodeBatchSize(this.settings);
178
+ const canonical = addresses.map(value => parseAddress(value).value);
179
+ const unique = [...new Set(canonical)];
180
+ const accounts = new Map();
181
+ for (let offset = 0; offset < unique.length; offset += batchSize) {
182
+ const batch = unique.slice(offset, offset + batchSize);
183
+ const result = await this.get('accounts', text => {
184
+ const values = jsonExact(text);
185
+ if (!Array.isArray(values))
186
+ throw new Error();
187
+ return values.map(value => AttoAccount.fromJson(JSON.stringify(value)));
188
+ }, signal, false, JSON.stringify({ addresses: batch }));
189
+ if (!result)
190
+ throw new AttoError('NODE_HTTP_ERROR', 'The node returned HTTP 404.', { httpStatus: 404 });
191
+ for (const account of result) {
192
+ if (!batch.includes(account.address.value) || accounts.has(account.address.value)) {
193
+ throw new AttoError('INVALID_NODE_RESPONSE', 'The node returned an unexpected account.');
194
+ }
195
+ accounts.set(account.address.value, account);
196
+ }
197
+ }
198
+ if (signal?.aborted)
199
+ throw new AttoError('CANCELLED', 'The network request was cancelled.');
200
+ return canonical.map(address => accounts.get(address) ?? null);
201
+ }
174
202
  async now(signal) {
175
203
  const requested = AttoInstant.Companion.now().toString();
176
204
  const result = await this.get(`instants/${encodeURIComponent(requested)}`, text => {
@@ -195,6 +223,25 @@ export class NodeReader {
195
223
  }
196
224
  async stream(filter, onEvent, signal) {
197
225
  const normalized = normalizeFilter(filter);
226
+ const batchSize = resolveNodeBatchSize(this.settings);
227
+ if (!normalized.addresses || normalized.addresses.length <= batchSize) {
228
+ return this.subscription(normalized, onEvent, signal);
229
+ }
230
+ const stopped = new AbortController();
231
+ const combined = AbortSignal.any([signal, stopped.signal]);
232
+ const subscriptions = [];
233
+ for (let offset = 0; offset < normalized.addresses.length; offset += batchSize) {
234
+ subscriptions.push(this.subscription({ ...normalized, addresses: normalized.addresses.slice(offset, offset + batchSize) }, onEvent, combined));
235
+ }
236
+ try {
237
+ await Promise.all(subscriptions);
238
+ }
239
+ finally {
240
+ stopped.abort();
241
+ await Promise.allSettled(subscriptions);
242
+ }
243
+ }
244
+ async subscription(normalized, onEvent, signal, ranges) {
198
245
  if (signal.aborted)
199
246
  return;
200
247
  const builder = new AttoNodeClientAsyncBuilder(this.settings.nodeUrl);
@@ -249,16 +296,17 @@ export class NodeReader {
249
296
  else {
250
297
  const from = toAttoHeight(normalized.fromHeight ?? '1');
251
298
  const to = normalized.toHeight ? toAttoHeight(normalized.toHeight) : undefined;
252
- const search = addresses && !one ? HeightSearch.Companion.fromArray(addresses.map(address => new AccountHeightSearch(address, from, to))) : undefined;
299
+ const search = ranges ? HeightSearch.Companion.fromArray(ranges)
300
+ : addresses && !one ? HeightSearch.Companion.fromArray(addresses.map(address => new AccountHeightSearch(address, from, to))) : undefined;
253
301
  if (normalized.event === 'entry') {
254
302
  job = hash ? client.onAccountEntryByHash(hash, emit, complete)
255
- : one ? client.onAccountEntryByPublicKey(one.publicKey, from, to, emit, complete)
303
+ : one && !ranges ? client.onAccountEntryByPublicKey(one.publicKey, from, to, emit, complete)
256
304
  : search ? client.onAccountEntryByHeightSearch(search, emit, complete)
257
305
  : client.onAccountEntryAll(emit, complete);
258
306
  }
259
307
  else {
260
308
  job = hash ? client.onTransactionByHash(hash, emit, complete)
261
- : one ? client.onTransactionByPublicKey(one.publicKey, from, to, emit, complete)
309
+ : one && !ranges ? client.onTransactionByPublicKey(one.publicKey, from, to, emit, complete)
262
310
  : search ? client.onTransactionByHeightSearch(search, emit, complete)
263
311
  : client.onTransactionAll(emit, complete);
264
312
  }
@@ -283,6 +331,7 @@ export class NodeReader {
283
331
  }
284
332
  async list(request, signal) {
285
333
  const filter = normalizeFilter(request);
334
+ const batchSize = resolveNodeBatchSize(this.settings);
286
335
  const limit = request.limit ?? 100;
287
336
  const timeoutMs = request.timeoutMs ?? 3_000;
288
337
  if (!Number.isInteger(limit) || limit < 1 || limit > 1000 || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 60_000) {
@@ -322,36 +371,75 @@ export class NodeReader {
322
371
  }
323
372
  }
324
373
  try {
325
- while (cursor.addressIndex < addresses.length && !combined.aborted) {
326
- const index = cursor.addressIndex;
327
- const address = addresses[index];
328
- if (cursor.upper[index] === null) {
329
- const current = await this.account(address, combined);
330
- const currentHeight = current ? BigInt(String(current.height)) : 0n;
331
- cursor.upper[index] = (filter.toHeight && BigInt(filter.toHeight) < currentHeight ? BigInt(filter.toHeight) : currentHeight).toString();
332
- }
333
- const upper = cursor.upper[index];
334
- if (BigInt(cursor.nextHeight) <= BigInt(upper)) {
335
- await this.stream({ ...filter, addresses: [address], fromHeight: cursor.nextHeight, toHeight: upper }, model => {
336
- const position = eventPosition(model);
337
- if (!position || position.address !== address || BigInt(position.height) > BigInt(upper))
338
- throw new AttoError('INVALID_NODE_RESPONSE', 'The node returned an event outside the requested account range.');
339
- if (BigInt(position.height) < BigInt(cursor.nextHeight))
340
- return;
341
- // Each account stream is height ordered. Never advance over a missing block.
342
- if (position.height !== cursor.nextHeight)
343
- throw new AttoError('HISTORY_GAP', 'The node returned a gap in account history. Retry with a fully synchronized node.');
344
- items.push(publicModel(model));
345
- cursor.nextHeight = (BigInt(position.height) + 1n).toString();
346
- if (items.length === limit)
347
- done.abort();
348
- }, combined);
349
- }
350
- if (BigInt(cursor.nextHeight) > BigInt(upper)) {
374
+ const advance = () => {
375
+ while (cursor.addressIndex < addresses.length && cursor.upper[cursor.addressIndex] !== null && BigInt(cursor.nextHeight) > BigInt(cursor.upper[cursor.addressIndex])) {
351
376
  cursor.addressIndex++;
352
377
  cursor.nextHeight = filter.fromHeight;
353
378
  }
354
- else if (!combined.aborted) {
379
+ };
380
+ advance();
381
+ while (cursor.addressIndex < addresses.length && !combined.aborted) {
382
+ if (cursor.upper[cursor.addressIndex] === null) {
383
+ // Persist each nearby batch before requesting more heads. A small page
384
+ // need not read every selected account, and a timeout keeps prior work.
385
+ const unresolved = addresses.slice(cursor.addressIndex, cursor.addressIndex + batchSize)
386
+ .map((address, offset) => ({ address, index: cursor.addressIndex + offset }))
387
+ .filter(({ index }) => cursor.upper[index] === null);
388
+ const heads = await this.accounts(unresolved.map(({ address }) => address), combined);
389
+ heads.forEach((account, offset) => {
390
+ const currentHeight = account ? BigInt(String(account.height)) : 0n;
391
+ cursor.upper[unresolved[offset].index] = (filter.toHeight && BigInt(filter.toHeight) < currentHeight ? BigInt(filter.toHeight) : currentHeight).toString();
392
+ });
393
+ advance();
394
+ if (cursor.addressIndex === addresses.length)
395
+ break;
396
+ if (cursor.upper[cursor.addressIndex] === null)
397
+ continue;
398
+ }
399
+ let capacity = limit - items.length;
400
+ const planned = [];
401
+ for (let index = cursor.addressIndex; index < addresses.length && capacity > 0 && planned.length < batchSize; index++) {
402
+ if (cursor.upper[index] === null)
403
+ break;
404
+ const from = BigInt(index === cursor.addressIndex ? cursor.nextHeight : filter.fromHeight);
405
+ const upper = BigInt(cursor.upper[index]);
406
+ if (from > upper)
407
+ continue;
408
+ const count = upper - from + 1n < BigInt(capacity) ? upper - from + 1n : BigInt(capacity);
409
+ planned.push({ index, from, to: from + count - 1n, next: from, pending: new Map() });
410
+ capacity -= Number(count);
411
+ }
412
+ const ranges = planned.map(range => new AccountHeightSearch(parseAddress(addresses[range.index]), toAttoHeight(range.from.toString()), toAttoHeight(range.to.toString())));
413
+ await this.subscription(filter, model => {
414
+ const position = eventPosition(model);
415
+ const range = position && planned.find(range => addresses[range.index] === position.address);
416
+ if (!position || !range || BigInt(position.height) < range.from || BigInt(position.height) > range.to) {
417
+ throw new AttoError('INVALID_NODE_RESPONSE', 'The node returned an event outside the requested account range.');
418
+ }
419
+ if (BigInt(position.height) < range.next)
420
+ return;
421
+ if (BigInt(position.height) !== range.next)
422
+ throw new AttoError('HISTORY_GAP', 'The node returned a gap in account history. Retry with a fully synchronized node.');
423
+ range.next++;
424
+ range.pending.set(position.height, model);
425
+ // Commit only the contiguous address-ordered prefix. Later-address
426
+ // records remain uncommitted and are safely replayed after a timeout.
427
+ while (cursor.addressIndex < addresses.length) {
428
+ const current = planned.find(range => range.index === cursor.addressIndex);
429
+ const next = current?.pending.get(cursor.nextHeight);
430
+ if (!next)
431
+ break;
432
+ current.pending.delete(cursor.nextHeight);
433
+ items.push(publicModel(next));
434
+ cursor.nextHeight = (BigInt(cursor.nextHeight) + 1n).toString();
435
+ advance();
436
+ if (items.length === limit) {
437
+ done.abort();
438
+ break;
439
+ }
440
+ }
441
+ }, combined, ranges);
442
+ if (!combined.aborted && planned.some(range => range.next <= range.to)) {
355
443
  throw new AttoError('HISTORY_GAP', 'The node closed the stream before the requested history was complete.');
356
444
  }
357
445
  }
@@ -5,10 +5,15 @@ export declare function approvalInstructions(proposal: LimitsProposal, current:
5
5
  access: McpAccess;
6
6
  policy: SpendingPolicy;
7
7
  pool: AccountPool;
8
+ messageSigningIndexes: number[];
8
9
  }): {
9
10
  method: string;
10
11
  instructions: string;
11
12
  changes: {
13
+ messageSigningIndexes?: {
14
+ from: number[];
15
+ to: number[];
16
+ } | undefined;
12
17
  pool?: {
13
18
  from: AccountPool;
14
19
  to: AccountPool;
@@ -13,6 +13,8 @@ export function approvalInstructions(proposal, current) {
13
13
  ...(current.access !== proposal.access ? { access: { from: current.access, to: proposal.access } } : {}),
14
14
  ...(!isDeepStrictEqual(current.policy, proposal.policy) ? { policy: { from: current.policy, to: proposal.policy } } : {}),
15
15
  ...(!isDeepStrictEqual(current.pool, pool) ? { pool: { from: current.pool, to: pool } } : {}),
16
+ ...(!isDeepStrictEqual(current.messageSigningIndexes, proposal.messageSigningIndexes ?? [])
17
+ ? { messageSigningIndexes: { from: current.messageSigningIndexes, to: proposal.messageSigningIndexes ?? [] } } : {}),
16
18
  },
17
19
  shell,
18
20
  commands: {
@@ -0,0 +1,31 @@
1
+ import { AttoTransaction } from '@attocash/commons-core';
2
+ export type AttoPaymentNetwork = 'atto:live' | 'atto:beta' | 'atto:dev' | 'atto:local';
3
+ export interface AttoExactRequirement {
4
+ rawJson: string;
5
+ resource: Record<string, unknown>;
6
+ accepted: Record<string, unknown>;
7
+ network: AttoPaymentNetwork;
8
+ amountRaw: string;
9
+ payTo: string;
10
+ maxTimeoutSeconds: number;
11
+ resourceUrl: string;
12
+ identifierSchema: Record<string, unknown>;
13
+ extensions: Record<string, unknown>;
14
+ fingerprint: string;
15
+ }
16
+ export declare function parseAttoExactRequirement(input: {
17
+ header: string;
18
+ apiUrl: string;
19
+ intentId: string;
20
+ network: AttoPaymentNetwork;
21
+ amountRaw: string;
22
+ }): AttoExactRequirement;
23
+ export declare function paymentPayload(requirement: AttoExactRequirement, paymentIdentifier: string, transaction: AttoTransaction): {
24
+ json: string;
25
+ header: string;
26
+ };
27
+ /** Bind the parsed wire SEND to the complete native transaction, including signature and work. */
28
+ export declare function paymentTransactionMatches(paymentJson: string, transaction: AttoTransaction): boolean;
29
+ /** Retained journals may contain the previous numeric envelope; recover its exact bytes without rewriting it. */
30
+ export declare function savedPaymentMatches(requirement: AttoExactRequirement, paymentIdentifier: string, transaction: AttoTransaction, paymentJson: string, paymentSignature: string): boolean;
31
+ export declare function paymentDeadline(transaction: AttoTransaction, maxTimeoutSeconds: number, intentExpiresAt: string): bigint;
@@ -0,0 +1,174 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { AttoSendBlock, AttoTransaction } from '@attocash/commons-core';
3
+ import { AttoError } from '../domain/errors.js';
4
+ import { parseAddress } from '../network/reader.js';
5
+ const MAX_REQUIRED_BYTES = 65_536;
6
+ const MAX_HEADER_CHARS = 90_000;
7
+ function object(value) {
8
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
9
+ ? value : undefined;
10
+ }
11
+ function decodeBase64(value, maxBytes) {
12
+ if (value.length < 1 || value.length > MAX_HEADER_CHARS || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value)) {
13
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid payment challenge.');
14
+ }
15
+ const bytes = Buffer.from(value, 'base64');
16
+ if (bytes.length < 1 || bytes.length > maxBytes || bytes.toString('base64') !== value) {
17
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid payment challenge.');
18
+ }
19
+ try {
20
+ return new TextDecoder('utf-8', { fatal: true }).decode(bytes);
21
+ }
22
+ catch {
23
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid payment challenge.');
24
+ }
25
+ }
26
+ export function parseAttoExactRequirement(input) {
27
+ const rawJson = decodeBase64(input.header, MAX_REQUIRED_BYTES);
28
+ let decoded;
29
+ try {
30
+ decoded = JSON.parse(rawJson);
31
+ }
32
+ catch {
33
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid payment challenge.');
34
+ }
35
+ const requirement = object(decoded);
36
+ const resource = object(requirement?.resource);
37
+ const accepts = requirement?.accepts;
38
+ const accepted = Array.isArray(accepts) && accepts.length === 1 ? object(accepts[0]) : undefined;
39
+ const extra = object(accepted?.extra);
40
+ const extensions = object(requirement?.extensions);
41
+ const identifier = object(extensions?.['payment-identifier']);
42
+ const identifierInfo = object(identifier?.info);
43
+ const identifierSchema = object(identifier?.schema);
44
+ const resourceUrl = resource?.url;
45
+ const expected = new URL(`${input.apiUrl.replace(/\/+$/, '')}/${input.intentId}`);
46
+ if (!requirement || requirement.x402Version !== 2 || !resource || typeof resourceUrl !== 'string'
47
+ || !accepted || accepted.scheme !== 'exact' || accepted.network !== input.network
48
+ || accepted.amount !== input.amountRaw || accepted.asset !== 'atto'
49
+ || typeof accepted.payTo !== 'string' || !Number.isSafeInteger(accepted.maxTimeoutSeconds)
50
+ || accepted.maxTimeoutSeconds < 1 || accepted.maxTimeoutSeconds > 3600
51
+ || (accepted.extra !== undefined && !extra)
52
+ || (extra && Object.hasOwn(extra, 'assetTransferMethod') && extra.assetTransferMethod !== 'native')
53
+ || (extra && Object.hasOwn(extra, 'paymentFlow') && extra.paymentFlow !== 'authorization')
54
+ || identifierInfo?.required !== true || !identifierSchema) {
55
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an unsupported ATTO payment challenge.');
56
+ }
57
+ let offered;
58
+ try {
59
+ offered = new URL(resourceUrl);
60
+ }
61
+ catch {
62
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid payment resource.');
63
+ }
64
+ if (offered.origin !== expected.origin || offered.pathname !== expected.pathname || offered.search || offered.hash
65
+ || offered.username || offered.password) {
66
+ throw new AttoError('MARKETPLACE_RESOURCE_MISMATCH', 'Marketplace offered a payment resource outside the configured top-up origin and intent.');
67
+ }
68
+ let payTo;
69
+ try {
70
+ payTo = parseAddress(accepted.payTo).value;
71
+ }
72
+ catch {
73
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid ATTO deposit address.');
74
+ }
75
+ if (payTo !== accepted.payTo)
76
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned a noncanonical ATTO deposit address.');
77
+ return {
78
+ rawJson,
79
+ resource,
80
+ accepted,
81
+ network: input.network,
82
+ amountRaw: input.amountRaw,
83
+ payTo,
84
+ maxTimeoutSeconds: accepted.maxTimeoutSeconds,
85
+ resourceUrl: offered.toString(),
86
+ identifierSchema,
87
+ extensions: extensions,
88
+ fingerprint: createHash('sha256').update(rawJson, 'utf8').digest('hex'),
89
+ };
90
+ }
91
+ /** Build the x402 string profile directly from exact Commons values, leaving native JSON untouched. */
92
+ function wireTransaction(transaction) {
93
+ const block = transaction.block;
94
+ if (!(block instanceof AttoSendBlock))
95
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'An ATTO payment must be a native SEND.');
96
+ return { block: { type: 'SEND', network: block.network.name, version: Number(block.version.toString()),
97
+ algorithm: block.algorithm.name, address: block.address.value, height: block.height.toString(),
98
+ balance: block.balance.toString(), timestamp: block.timestamp.toEpochMilliseconds().toString(),
99
+ previous: block.previous.toString(), receiverAddress: block.receiverAddress.value, amount: block.amount.toString() },
100
+ signature: transaction.signature.toString(), work: transaction.work.toString() };
101
+ }
102
+ function echoedExtensions(requirement, paymentIdentifier) {
103
+ const identifier = object(requirement.extensions['payment-identifier']);
104
+ const info = object(identifier.info);
105
+ if (Object.hasOwn(info, 'id') && info.id !== paymentIdentifier) {
106
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'The offered payment identifier differs from the original operation.');
107
+ }
108
+ return { ...requirement.extensions, 'payment-identifier': { ...identifier, info: { ...info, id: paymentIdentifier } } };
109
+ }
110
+ export function paymentPayload(requirement, paymentIdentifier, transaction) {
111
+ const json = JSON.stringify({ x402Version: 2, resource: requirement.resource, accepted: requirement.accepted,
112
+ payload: { transaction: wireTransaction(transaction) }, extensions: echoedExtensions(requirement, paymentIdentifier) });
113
+ const header = Buffer.from(json, 'utf8').toString('base64');
114
+ if (Buffer.byteLength(json, 'utf8') > MAX_REQUIRED_BYTES || header.length > MAX_HEADER_CHARS) {
115
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'The ATTO payment payload exceeds the supported size.');
116
+ }
117
+ return { json, header };
118
+ }
119
+ /** Bind the parsed wire SEND to the complete native transaction, including signature and work. */
120
+ export function paymentTransactionMatches(paymentJson, transaction) {
121
+ try {
122
+ const payment = object(JSON.parse(paymentJson));
123
+ const wire = object(object(payment?.payload)?.transaction);
124
+ const block = object(wire?.block);
125
+ const native = transaction.block;
126
+ if (!wire || !block || !(native instanceof AttoSendBlock) || block.type !== 'SEND'
127
+ || block.address !== native.address.value || block.receiverAddress !== native.receiverAddress.value
128
+ || block.algorithm !== native.algorithm.name || block.version !== Number(native.version.toString()))
129
+ return false;
130
+ const expectedBlock = object(wireTransaction(transaction).block);
131
+ for (const field of ['height', 'balance', 'amount', 'timestamp']) {
132
+ const value = block[field];
133
+ if (value !== expectedBlock[field])
134
+ return false;
135
+ if (typeof value !== 'string' || !(field === 'timestamp' ? /^(?:0|-?[1-9][0-9]*)$/ : /^(?:0|[1-9][0-9]*)$/).test(value))
136
+ return false;
137
+ }
138
+ const compatibility = { publicKey: native.publicKey.toString(), receiverAlgorithm: native.receiverAlgorithm.name,
139
+ receiverPublicKey: native.receiverPublicKey.toString() };
140
+ for (const [key, expected] of Object.entries(compatibility)) {
141
+ if (Object.hasOwn(block, key) && block[key] !== expected)
142
+ return false;
143
+ }
144
+ const decoded = AttoTransaction.fromJson(JSON.stringify({ ...wire, block: { ...block, ...compatibility } }));
145
+ return decoded.hash.toString() === transaction.hash.toString()
146
+ && decoded.signature.toString() === transaction.signature.toString() && decoded.work.toString() === transaction.work.toString()
147
+ && Buffer.from(decoded.toByteArray()).equals(Buffer.from(transaction.toByteArray()));
148
+ }
149
+ catch {
150
+ return false;
151
+ }
152
+ }
153
+ /** Retained journals may contain the previous numeric envelope; recover its exact bytes without rewriting it. */
154
+ export function savedPaymentMatches(requirement, paymentIdentifier, transaction, paymentJson, paymentSignature) {
155
+ if (Buffer.from(paymentJson, 'utf8').toString('base64') !== paymentSignature)
156
+ return false;
157
+ const legacy = `{"x402Version":2,"resource":${JSON.stringify(requirement.resource)},"accepted":${JSON.stringify(requirement.accepted)},"payload":{"transaction":${transaction.toJson()}},"extensions":{"payment-identifier":{"schema":${JSON.stringify(requirement.identifierSchema)},"info":{"required":true,"id":${JSON.stringify(paymentIdentifier)}}}}}`;
158
+ if (paymentJson === legacy)
159
+ return true;
160
+ try {
161
+ return paymentPayload(requirement, paymentIdentifier, transaction).json === paymentJson;
162
+ }
163
+ catch {
164
+ return false;
165
+ }
166
+ }
167
+ export function paymentDeadline(transaction, maxTimeoutSeconds, intentExpiresAt) {
168
+ const timeoutDeadline = BigInt(transaction.block.timestamp.toEpochMilliseconds()) + BigInt(maxTimeoutSeconds) * 1000n;
169
+ const expiry = Date.parse(intentExpiresAt);
170
+ if (!Number.isSafeInteger(expiry) || expiry < 0)
171
+ throw new AttoError('MARKETPLACE_PROTOCOL', 'Marketplace returned an invalid top-up expiry.');
172
+ const intentDeadline = BigInt(expiry);
173
+ return timeoutDeadline < intentDeadline ? timeoutDeadline : intentDeadline;
174
+ }
@@ -1,3 +1,4 @@
1
+ import { type AttoPaymentNetwork } from './atto-x402.js';
1
2
  import { type DestinationBinding } from './destination.js';
2
3
  import type { StateStore } from '../storage/state.js';
3
4
  import type { AccountPool, SpendingPolicy } from '../wallet/types.js';
@@ -21,8 +22,49 @@ export interface SendRecord {
21
22
  quote?: unknown;
22
23
  selection?: 'automatic' | 'explicit';
23
24
  plan?: PaymentPlan;
25
+ external?: ExternalPaymentRecord | LegacyExternalPaymentRecord;
24
26
  }
25
- export type SendReservation = Pick<SendRecord, 'id' | 'index' | 'destination' | 'raw' | 'createdAt'> & Partial<Pick<SendRecord, 'sourceAddress' | 'network' | 'metadata' | 'quote' | 'selection' | 'plan' | 'destinationBinding'>>;
27
+ export interface ExternalPaymentRecord {
28
+ kind: 'marketplace-topup' | 'marketplace-intent';
29
+ version: 1;
30
+ paymentIdentifier: string;
31
+ network: AttoPaymentNetwork;
32
+ intentId: string;
33
+ resourceUrl: string;
34
+ requirementHash: string;
35
+ intentExpiresAt: string;
36
+ marketplaceState: 'ISSUED' | 'PENDING' | 'ACCEPTED' | 'PUBLISHING' | 'UNKNOWN' | 'PROCESSED' | 'SETTLED' | 'REJECTED' | 'CREDITED' | 'EXPIRED';
37
+ paymentState: 'PREPARED' | 'ATTEMPTED' | 'PENDING' | 'ACCEPTED' | 'PUBLISHING' | 'UNKNOWN' | 'PROCESSED' | 'SETTLED' | 'REJECTED' | 'CONFIRMED' | 'FAILED' | null;
38
+ nativeState: 'challenged' | 'unknown' | 'confirmed' | 'rejected';
39
+ attemptedAt?: number;
40
+ receivePending?: boolean | null;
41
+ receiveStatus?: 'PENDING' | 'ACCEPTED' | 'SETTLED' | 'REJECTED' | null;
42
+ }
43
+ /** Historical wallet accounting only; these records cannot authorize current Marketplace payments. */
44
+ interface LegacyExternalPaymentRecord extends Omit<ExternalPaymentRecord, 'kind' | 'marketplaceState'> {
45
+ kind: 'market-topup' | 'market-intent';
46
+ marketState: ExternalPaymentRecord['marketplaceState'];
47
+ marketplaceState?: never;
48
+ }
49
+ export interface ExternalPaymentSecrets {
50
+ version: 1;
51
+ paymentKind?: 'marketplace-topup' | 'marketplace-intent';
52
+ apiUrl: string;
53
+ audience: string;
54
+ accountId?: string;
55
+ agentId?: string;
56
+ identityId?: string;
57
+ walletFingerprint: string;
58
+ controllerIndex?: number;
59
+ controllerAddress?: string;
60
+ requirementJson: string;
61
+ transactionJson?: string;
62
+ paymentJson?: string;
63
+ paymentSignature?: string;
64
+ }
65
+ export type SendReservation = Pick<SendRecord, 'id' | 'index' | 'destination' | 'raw' | 'createdAt'> & Partial<Pick<SendRecord, 'sourceAddress' | 'network' | 'metadata' | 'quote' | 'selection' | 'plan' | 'destinationBinding'>> & {
66
+ external?: ExternalPaymentRecord;
67
+ };
26
68
  export type McpAccess = 'read-only' | 'spend';
27
69
  export interface ProposalWallet {
28
70
  directory: string;
@@ -39,6 +81,7 @@ export interface LimitsProposal extends ProposalWallet {
39
81
  status: 'pending' | 'approved' | 'rejected';
40
82
  decidedAt?: number;
41
83
  pool?: AccountPool;
84
+ messageSigningIndexes?: number[];
42
85
  }
43
86
  export declare class SpendLedger {
44
87
  private readonly store;
@@ -47,18 +90,22 @@ export declare class SpendLedger {
47
90
  setPolicy(policy: SpendingPolicy): void;
48
91
  mcpAccess(): McpAccess;
49
92
  pool(): AccountPool;
50
- proposePolicy(policy: SpendingPolicy, access: McpAccess, wallet: ProposalWallet, pool?: AccountPool): LimitsProposal;
93
+ messageSigningIndexes(): number[];
94
+ proposePolicy(policy: SpendingPolicy, access: McpAccess, wallet: ProposalWallet, pool?: AccountPool, messageSigningIndexes?: number[]): LimitsProposal;
51
95
  proposal(): LimitsProposal | null;
52
96
  reviewProposal(id: string, wallet: ProposalWallet): LimitsProposal;
53
97
  approveProposal(id: string, wallet: ProposalWallet): void;
54
98
  rejectProposal(id: string, wallet: ProposalWallet): void;
55
99
  private revision;
56
100
  private replacePolicy;
101
+ private validateMessageSigningIndexes;
57
102
  assertCanReserve(raw: string, now?: number): void;
58
103
  /** Recheck the current policy before signing without charging this reservation twice. */
59
104
  assertReservationAllowed(id: string, now?: number): void;
60
105
  private assertAllowance;
61
106
  reserve(request: SendReservation): SendRecord;
107
+ /** Commit a Marketplace intent reservation and its exact owner/challenge binding together. */
108
+ reserveExternalChallenge(request: SendReservation, requirementJson: string, owner: Omit<ExternalPaymentSecrets, 'requirementJson' | 'transactionJson' | 'paymentJson' | 'paymentSignature' | 'paymentKind'>): SendRecord;
62
109
  get(id: string): SendRecord | undefined;
63
110
  journalGet(requestId: string): SendRecord | undefined;
64
111
  journalList(options?: {
@@ -70,6 +117,24 @@ export declare class SpendLedger {
70
117
  nextCursor?: string;
71
118
  };
72
119
  signed(id: string, hash: string, blockJson: string): void;
120
+ /** Persist the exact offered requirement before any external SEND is signed. */
121
+ externalChallenge(id: string, requirementJson: string, owner: Omit<ExternalPaymentSecrets, 'requirementJson' | 'transactionJson' | 'paymentJson' | 'paymentSignature' | 'paymentKind'>): void;
122
+ /** Exact signed bytes and the attempt fence commit atomically before HTTP submission. */
123
+ externalAttempt(id: string, input: {
124
+ hash: string;
125
+ blockJson: string;
126
+ transactionJson: string;
127
+ paymentJson: string;
128
+ paymentSignature: string;
129
+ attemptedAt: number;
130
+ }): void;
131
+ externalSecretsFor(id: string): ExternalPaymentSecrets | undefined;
132
+ externalStatus(id: string, update: Partial<Pick<ExternalPaymentRecord, 'marketplaceState' | 'paymentState' | 'receivePending' | 'receiveStatus'>>): void;
133
+ completeExternal(id: string, result: unknown, publishedAt: number): void;
134
+ /** Call only after the canonical account height proves a competing block. */
135
+ rejectExternal(id: string, result: unknown): void;
136
+ /** Account and wallet locks must be held: only a never-signed expired challenge can release its reservation. */
137
+ expireExternalChallenge(id: string, now: number): boolean;
73
138
  complete(id: string, result: unknown, publishedAt: number): void;
74
139
  uncertain(id: string): void;
75
140
  fail(id: string): void;
@@ -82,11 +147,14 @@ export declare class SpendLedger {
82
147
  * The pinned plan cannot complete; retain all step evidence in the failed parent. */
83
148
  stepReject(id: string, stepId: string): void;
84
149
  private updateStep;
150
+ /** Caller owns this account's lock; unresolved plans keep their accounts reserved. */
151
+ assertAccountAvailable(index: number): void;
85
152
  pending(): SendRecord[];
86
153
  usage(now?: number): {
87
154
  policy: SpendingPolicy;
88
155
  mcpAccess: McpAccess;
89
156
  pool: AccountPool;
157
+ messageSigningIndexes: number[];
90
158
  proposal: LimitsProposal | null;
91
159
  pendingRaw: string;
92
160
  perRequest: {
@@ -114,5 +182,9 @@ export declare class SpendLedger {
114
182
  private validatePolicy;
115
183
  private validatePool;
116
184
  private validateDetails;
185
+ private validateExternal;
186
+ private externalSecrets;
187
+ private externalDefinition;
188
+ private ownerDefinition;
117
189
  private planDefinition;
118
190
  }