@attocash/cli 0.2.2 → 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 +157 -5
  2. package/dist/application/app.d.ts +34 -3
  3. package/dist/application/app.js +142 -125
  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 +35 -0
  29. package/dist/spending/approval.js +25 -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
@@ -1,16 +1,20 @@
1
+ import { paymentTransactionMatches } from './atto-x402.js';
1
2
  import { validateDestinationBinding } from './destination.js';
2
- import { randomUUID } from 'node:crypto';
3
+ import { createHash, randomUUID } from 'node:crypto';
3
4
  import { isDeepStrictEqual } from 'node:util';
5
+ import { AttoBlock, AttoSendBlock, AttoTransaction } from '@attocash/commons-core';
4
6
  import { amountRaw } from '../domain/amount.js';
5
7
  import { AttoError } from '../domain/errors.js';
6
8
  import { paymentMetadataSchema, validatePaymentPlan } from './journal.js';
7
9
  const DAY_MS = 86_400_000;
8
10
  const POLICY_KEY = 'spending.policy';
9
11
  const RECORDS_KEY = 'spending.records';
12
+ const EXTERNAL_SECRETS_KEY = 'spending.externalSecrets';
10
13
  const REVISION_KEY = 'spending.policyRevision';
11
14
  const ACCESS_KEY = 'spending.mcpAccess';
12
15
  const PROPOSAL_KEY = 'spending.proposal';
13
16
  const POOL_KEY = 'spending.pool';
17
+ const MESSAGE_SIGNING_INDEXES_KEY = 'signing.messageIndexes';
14
18
  export class SpendLedger {
15
19
  store;
16
20
  constructor(store) {
@@ -36,14 +40,20 @@ export class SpendLedger {
36
40
  this.validatePool(pool);
37
41
  return pool;
38
42
  }
39
- proposePolicy(policy, access, wallet, pool = this.pool()) {
43
+ messageSigningIndexes() {
44
+ const indexes = this.store.get(MESSAGE_SIGNING_INDEXES_KEY) ?? [];
45
+ this.validateMessageSigningIndexes(indexes);
46
+ return indexes;
47
+ }
48
+ proposePolicy(policy, access, wallet, pool = this.pool(), messageSigningIndexes = this.messageSigningIndexes()) {
40
49
  this.validatePolicy(policy);
41
50
  this.validatePool(pool);
51
+ this.validateMessageSigningIndexes(messageSigningIndexes);
42
52
  if (access !== 'read-only' && access !== 'spend')
43
53
  throw new AttoError('INVALID_POLICY', 'Choose read-only or spend access for MCP.');
44
54
  const createdAt = Date.now();
45
55
  const proposal = {
46
- ...wallet, id: randomUUID(), policy, access, pool, createdAt, expiresAt: createdAt + DAY_MS,
56
+ ...wallet, id: randomUUID(), policy, access, pool, messageSigningIndexes: [...messageSigningIndexes], createdAt, expiresAt: createdAt + DAY_MS,
47
57
  baseRevision: this.revision(), status: 'pending',
48
58
  };
49
59
  // One immutable proposal is current per profile. A new request gets a new
@@ -68,7 +78,9 @@ export class SpendLedger {
68
78
  this.validatePolicy(proposal.policy);
69
79
  if (proposal.pool !== undefined)
70
80
  this.validatePool(proposal.pool);
71
- return proposal;
81
+ const messageSigningIndexes = proposal.messageSigningIndexes ?? [];
82
+ this.validateMessageSigningIndexes(messageSigningIndexes);
83
+ return { ...proposal, messageSigningIndexes };
72
84
  }
73
85
  catch {
74
86
  throw new AttoError('INVALID_STATE', 'The saved limit proposal is invalid.');
@@ -100,6 +112,7 @@ export class SpendLedger {
100
112
  this.store.set(ACCESS_KEY, proposal.access);
101
113
  if (proposal.pool !== undefined)
102
114
  this.store.set(POOL_KEY, proposal.pool);
115
+ this.store.set(MESSAGE_SIGNING_INDEXES_KEY, proposal.messageSigningIndexes ?? []);
103
116
  this.store.set(PROPOSAL_KEY, { ...proposal, status: 'approved', decidedAt: Date.now() });
104
117
  });
105
118
  }
@@ -124,6 +137,13 @@ export class SpendLedger {
124
137
  this.store.set(POLICY_KEY, policy);
125
138
  this.store.set(REVISION_KEY, revision + 1);
126
139
  }
140
+ validateMessageSigningIndexes(indexes) {
141
+ if (!Array.isArray(indexes) || indexes.length > 100
142
+ || indexes.some(index => !Number.isSafeInteger(index) || index < 0 || index > 0x7fff_ffff)
143
+ || new Set(indexes).size !== indexes.length) {
144
+ throw new AttoError('INVALID_POLICY', 'Message-signing indexes must be unique account indexes, up to 100.');
145
+ }
146
+ }
127
147
  assertCanReserve(raw, now = Date.now()) {
128
148
  this.assertAllowance(amountRaw(raw, 'RAW'), now, this.records());
129
149
  }
@@ -176,7 +196,8 @@ export class SpendLedger {
176
196
  || ['sourceAddress', 'network', 'metadata', 'quote', 'selection'].some(key => {
177
197
  const field = key;
178
198
  return request[field] !== undefined && !isDeepStrictEqual(request[field], existing[field]);
179
- }) || (request.plan !== undefined && !isDeepStrictEqual(this.planDefinition(request.plan), this.planDefinition(existing.plan)))) {
199
+ }) || (request.plan !== undefined && !isDeepStrictEqual(this.planDefinition(request.plan), this.planDefinition(existing.plan)))
200
+ || (request.external !== undefined && !isDeepStrictEqual(this.externalDefinition(request.external), this.externalDefinition(existing.external)))) {
180
201
  throw new AttoError('REQUEST_CONFLICT', 'This request ID already belongs to a different payment.');
181
202
  }
182
203
  return existing;
@@ -188,6 +209,58 @@ export class SpendLedger {
188
209
  return record;
189
210
  });
190
211
  }
212
+ /** Commit a Marketplace intent reservation and its exact owner/challenge binding together. */
213
+ reserveExternalChallenge(request, requirementJson, owner) {
214
+ if (!request.external || request.external.kind !== 'marketplace-intent'
215
+ || typeof requirementJson !== 'string' || Buffer.byteLength(requirementJson, 'utf8') < 1
216
+ || Buffer.byteLength(requirementJson, 'utf8') > 65_536
217
+ || createHashHex(requirementJson) !== request.external.requirementHash) {
218
+ throw new AttoError('SEND_STATE', 'The existing Marketplace intent challenge is invalid.');
219
+ }
220
+ if (typeof request.id !== 'string' || request.id.length === 0 || request.id.length > 200
221
+ || !Number.isSafeInteger(request.index) || request.index < 0 || request.index > 0x7fff_ffff
222
+ || typeof request.destination !== 'string' || !request.destination
223
+ || !Number.isSafeInteger(request.createdAt) || request.createdAt < 0) {
224
+ throw new AttoError('INVALID_REQUEST', 'Send requests require an ID, address index, destination, and timestamp.');
225
+ }
226
+ const raw = amountRaw(request.raw, 'RAW');
227
+ try {
228
+ this.validateDetails(request);
229
+ if (request.plan?.steps.some(step => step.status !== 'planned' || step.hash !== undefined))
230
+ throw new Error();
231
+ }
232
+ catch {
233
+ throw new AttoError('INVALID_REQUEST', 'The payment metadata, source, or consolidation plan is invalid.');
234
+ }
235
+ return this.store.transaction(() => {
236
+ const records = this.records();
237
+ const existing = records.find(record => record.id === request.id);
238
+ if (existing && (existing.index !== request.index || existing.destination !== request.destination || existing.raw !== raw
239
+ || ['sourceAddress', 'network', 'metadata', 'quote', 'selection'].some(key => {
240
+ const field = key;
241
+ return request[field] !== undefined && !isDeepStrictEqual(request[field], existing[field]);
242
+ }) || (request.plan !== undefined && !isDeepStrictEqual(this.planDefinition(request.plan), this.planDefinition(existing.plan)))
243
+ || !isDeepStrictEqual(this.externalDefinition(request.external), this.externalDefinition(existing.external)))) {
244
+ throw new AttoError('REQUEST_CONFLICT', 'This request ID already belongs to a different payment.');
245
+ }
246
+ const record = existing ?? { ...request, raw, status: 'reserved' };
247
+ if (!existing) {
248
+ this.assertAllowance(raw, request.createdAt, records);
249
+ records.push(record);
250
+ this.store.set(RECORDS_KEY, records);
251
+ }
252
+ const secrets = this.externalSecrets();
253
+ const current = secrets[request.id];
254
+ const boundOwner = { ...owner, paymentKind: 'marketplace-intent' };
255
+ if (current && (current.requirementJson !== requirementJson || !isDeepStrictEqual(this.ownerDefinition(current), boundOwner))) {
256
+ throw new AttoError('REQUEST_CONFLICT', 'This payment ID received a different x402 requirement or Marketplace binding.');
257
+ }
258
+ if (!current)
259
+ secrets[request.id] = { ...boundOwner, requirementJson };
260
+ this.store.set(EXTERNAL_SECRETS_KEY, secrets);
261
+ return record;
262
+ });
263
+ }
191
264
  get(id) { return this.records().find((record) => record.id === id); }
192
265
  journalGet(requestId) { return this.get(requestId); }
193
266
  journalList(options = {}) {
@@ -231,6 +304,140 @@ export class SpendLedger {
231
304
  return { ...record, hash, blockJson, status: 'signed' };
232
305
  });
233
306
  }
307
+ /** Persist the exact offered requirement before any external SEND is signed. */
308
+ externalChallenge(id, requirementJson, owner) {
309
+ if (typeof requirementJson !== 'string' || Buffer.byteLength(requirementJson, 'utf8') < 1
310
+ || Buffer.byteLength(requirementJson, 'utf8') > 65_536)
311
+ throw new AttoError('SEND_STATE', 'The x402 requirement is invalid.');
312
+ this.store.transaction(() => {
313
+ const records = this.records();
314
+ const record = records.find(value => value.id === id);
315
+ if (!record?.external || (record.external.kind !== 'marketplace-topup' && record.external.kind !== 'marketplace-intent')
316
+ || record.hash || record.status !== 'reserved')
317
+ throw new AttoError('SEND_STATE', 'This Marketplace payment no longer accepts a challenge.');
318
+ if (createHashHex(requirementJson) !== record.external.requirementHash)
319
+ throw new AttoError('SEND_STATE', 'The x402 requirement fingerprint does not match.');
320
+ const secrets = this.externalSecrets();
321
+ const current = secrets[id];
322
+ const boundOwner = { ...owner, paymentKind: record.external.kind };
323
+ if (current && (current.requirementJson !== requirementJson || !isDeepStrictEqual(this.ownerDefinition(current), boundOwner))) {
324
+ throw new AttoError('REQUEST_CONFLICT', 'This payment ID received a different x402 requirement or controller binding.');
325
+ }
326
+ if (!current) {
327
+ secrets[id] = { ...boundOwner, requirementJson };
328
+ this.store.set(EXTERNAL_SECRETS_KEY, secrets);
329
+ }
330
+ });
331
+ }
332
+ /** Exact signed bytes and the attempt fence commit atomically before HTTP submission. */
333
+ externalAttempt(id, input) {
334
+ if (!/^[A-F0-9]{64}$/.test(input.hash) || !input.blockJson || !input.transactionJson || !input.paymentJson
335
+ || !input.paymentSignature || !Number.isSafeInteger(input.attemptedAt) || input.attemptedAt < 0
336
+ || Buffer.byteLength(input.transactionJson, 'utf8') > 65_536 || Buffer.byteLength(input.paymentJson, 'utf8') > 65_536
337
+ || input.paymentSignature.length > 90_000)
338
+ throw new AttoError('SEND_STATE', 'The signed x402 payment is invalid.');
339
+ this.store.transaction(() => {
340
+ const records = this.records();
341
+ const position = records.findIndex(value => value.id === id);
342
+ const record = records[position];
343
+ if (!record?.external || (record.external.kind !== 'marketplace-topup' && record.external.kind !== 'marketplace-intent')
344
+ || record.status !== 'reserved' || record.hash)
345
+ throw new AttoError('SEND_STATE', 'This Marketplace payment cannot be assigned another SEND.');
346
+ const secrets = this.externalSecrets();
347
+ const current = secrets[id];
348
+ if (!current || createHashHex(current.requirementJson) !== record.external.requirementHash) {
349
+ throw new AttoError('SEND_STATE', 'The original x402 requirement is unavailable.');
350
+ }
351
+ let transaction;
352
+ let block;
353
+ try {
354
+ transaction = AttoTransaction.fromJson(input.transactionJson);
355
+ block = AttoBlock.fromJson(input.blockJson);
356
+ }
357
+ catch {
358
+ throw new AttoError('SEND_STATE', 'The signed x402 transaction is invalid.');
359
+ }
360
+ if (!(transaction.block instanceof AttoSendBlock) || !(block instanceof AttoSendBlock)
361
+ || transaction.hash.toString() !== input.hash || block.hash.toString() !== input.hash
362
+ || transaction.block.hash.toString() !== block.hash.toString()
363
+ || block.amount.toString() !== record.raw || block.receiverAddress.value !== record.destination
364
+ || (record.sourceAddress && block.address.value !== record.sourceAddress)
365
+ || block.network.name !== record.network
366
+ || !paymentTransactionMatches(input.paymentJson, transaction)) {
367
+ throw new AttoError('SEND_STATE', 'The signed x402 transaction does not match its request or payment envelope.');
368
+ }
369
+ const payloadBytes = Buffer.from(input.paymentSignature, 'base64');
370
+ if (payloadBytes.toString('base64') !== input.paymentSignature
371
+ || payloadBytes.toString('utf8') !== input.paymentJson) {
372
+ throw new AttoError('SEND_STATE', 'The saved x402 header does not match its payment envelope.');
373
+ }
374
+ const nextSecrets = { ...current, transactionJson: input.transactionJson,
375
+ paymentJson: input.paymentJson, paymentSignature: input.paymentSignature };
376
+ secrets[id] = nextSecrets;
377
+ records[position] = { ...record, hash: input.hash, blockJson: input.blockJson, status: 'signed',
378
+ external: { ...record.external, nativeState: 'unknown',
379
+ ...(record.external.kind === 'marketplace-intent' ? { paymentState: 'PREPARED' } : {}), attemptedAt: input.attemptedAt } };
380
+ this.validateDetails(records[position]);
381
+ this.store.set(EXTERNAL_SECRETS_KEY, secrets);
382
+ this.store.set(RECORDS_KEY, records);
383
+ });
384
+ }
385
+ externalSecretsFor(id) {
386
+ return this.externalSecrets()[id];
387
+ }
388
+ externalStatus(id, update) {
389
+ this.update(id, record => {
390
+ if (!record.external || (record.external.kind !== 'marketplace-topup' && record.external.kind !== 'marketplace-intent')) {
391
+ throw new AttoError('SEND_STATE', 'This request is not a current Marketplace payment.');
392
+ }
393
+ const external = { ...record.external, ...update };
394
+ this.validateExternal(external);
395
+ return { ...record, external };
396
+ });
397
+ }
398
+ completeExternal(id, result, publishedAt) {
399
+ this.update(id, record => {
400
+ if (!record.external || !record.hash || record.status === 'failed' || !Number.isSafeInteger(publishedAt) || publishedAt < 0) {
401
+ throw new AttoError('SEND_STATE', 'Only a recorded Marketplace SEND can be confirmed.');
402
+ }
403
+ return { ...record, status: 'published', result, publishedAt,
404
+ external: { ...record.external, nativeState: 'confirmed' } };
405
+ });
406
+ }
407
+ /** Call only after the canonical account height proves a competing block. */
408
+ rejectExternal(id, result) {
409
+ this.update(id, record => {
410
+ if (!record.external || !record.hash || record.status === 'published')
411
+ throw new AttoError('SEND_STATE', 'Only an unresolved Marketplace SEND can be rejected.');
412
+ return { ...record, status: 'failed', result,
413
+ external: { ...record.external, nativeState: 'rejected',
414
+ ...(record.external.kind === 'marketplace-intent' ? { paymentState: 'FAILED' } : {}) } };
415
+ });
416
+ }
417
+ /** Account and wallet locks must be held: only a never-signed expired challenge can release its reservation. */
418
+ expireExternalChallenge(id, now) {
419
+ return this.store.transaction(() => {
420
+ const records = this.records();
421
+ const index = records.findIndex(record => record.id === id);
422
+ const record = records[index];
423
+ const external = record?.external;
424
+ if (!record || !external || external.kind !== 'marketplace-intent' || record.status !== 'reserved'
425
+ || record.hash !== undefined || record.blockJson !== undefined || record.plan?.steps.some(step => step.hash !== undefined || step.blockJson !== undefined)
426
+ || external.nativeState !== 'challenged' || external.paymentState !== null || external.attemptedAt !== undefined
427
+ || !Number.isSafeInteger(now) || Date.parse(external.intentExpiresAt) > now)
428
+ return false;
429
+ const secrets = this.externalSecretsFor(id);
430
+ if (!secrets || secrets.paymentKind !== 'marketplace-intent' || secrets.transactionJson !== undefined
431
+ || secrets.paymentJson !== undefined || secrets.paymentSignature !== undefined)
432
+ return false;
433
+ records[index] = { ...record, status: 'failed',
434
+ result: { status: 'failed', reason: 'MARKETPLACE_CHALLENGE_EXPIRED' },
435
+ external: { ...external, marketplaceState: 'EXPIRED', paymentState: 'FAILED' } };
436
+ this.validateDetails(records[index]);
437
+ this.store.set(RECORDS_KEY, records);
438
+ return true;
439
+ });
440
+ }
234
441
  complete(id, result, publishedAt) {
235
442
  this.update(id, (record) => {
236
443
  if (record.status === 'published')
@@ -310,6 +517,12 @@ export class SpendLedger {
310
517
  return { ...record, ...(reject ? { status: 'failed' } : {}), plan: { ...record.plan, steps } };
311
518
  });
312
519
  }
520
+ /** Caller owns this account's lock; unresolved plans keep their accounts reserved. */
521
+ assertAccountAvailable(index) {
522
+ const record = this.pending().find(record => (record.plan?.indexes ?? [record.index]).includes(index));
523
+ if (record)
524
+ throw new AttoError('ACCOUNT_RESERVED', 'This account belongs to an unfinished payment. Resume that request first.', { requestId: record.id });
525
+ }
313
526
  pending() {
314
527
  return this.records().filter((record) => ['reserved', 'signed', 'unknown'].includes(record.status));
315
528
  }
@@ -320,6 +533,7 @@ export class SpendLedger {
320
533
  policy,
321
534
  mcpAccess: this.mcpAccess(),
322
535
  pool: this.pool(),
536
+ messageSigningIndexes: this.messageSigningIndexes(),
323
537
  proposal: this.proposal(),
324
538
  pendingRaw: this.pendingTotal(records).toString(),
325
539
  perRequest: policy.perRequest ? { ...policy.perRequest, limitRaw: amountRaw(policy.perRequest.amount, policy.perRequest.unit, true) } : null,
@@ -346,7 +560,7 @@ export class SpendLedger {
346
560
  throw new Error();
347
561
  if (record.status === 'published' && (!record.hash || !Number.isSafeInteger(record.publishedAt) || (record.publishedAt ?? -1) < 0))
348
562
  throw new Error();
349
- this.validateDetails(record);
563
+ this.validateDetails(record, true);
350
564
  ids.add(record.id);
351
565
  }
352
566
  return records;
@@ -417,7 +631,7 @@ export class SpendLedger {
417
631
  throw new AttoError('INVALID_POOL', 'Choose 1 to 100 distinct wallet indexes and an explicit consolidation setting.');
418
632
  }
419
633
  }
420
- validateDetails(record) {
634
+ validateDetails(record, historical = false) {
421
635
  if (record.destinationBinding !== undefined) {
422
636
  validateDestinationBinding(record.destinationBinding);
423
637
  if (record.destinationBinding.address !== record.destination || record.destinationBinding.network !== record.network)
@@ -433,6 +647,80 @@ export class SpendLedger {
433
647
  paymentMetadataSchema.parse(record.metadata);
434
648
  if (record.plan !== undefined)
435
649
  validatePaymentPlan(record.plan, record);
650
+ if (record.external !== undefined)
651
+ this.validateExternal(record.external, historical);
652
+ }
653
+ validateExternal(external, historical = false) {
654
+ if (historical && external && (external.kind === 'market-topup' || external.kind === 'market-intent')) {
655
+ if (Object.hasOwn(external, 'marketplaceState'))
656
+ throw new Error('Invalid historical external payment record.');
657
+ // Validate the old shape without replacing its stored tags or resuming its authorization.
658
+ return this.validateExternal({ ...external,
659
+ kind: external.kind === 'market-topup' ? 'marketplace-topup' : 'marketplace-intent',
660
+ marketplaceState: external.marketState });
661
+ }
662
+ if (!external || !['marketplace-topup', 'marketplace-intent'].includes(external.kind) || external.version !== 1
663
+ || !/^[A-Za-z0-9_-]{16,128}$/.test(external.paymentIdentifier)
664
+ || !['atto:live', 'atto:beta', 'atto:dev', 'atto:local'].includes(external.network)
665
+ || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(external.intentId)
666
+ || typeof external.resourceUrl !== 'string' || external.resourceUrl.length > 2048
667
+ || !/^[a-f0-9]{64}$/.test(external.requirementHash)
668
+ || typeof external.intentExpiresAt !== 'string' || !Number.isFinite(Date.parse(external.intentExpiresAt))
669
+ || !['ISSUED', 'PENDING', 'ACCEPTED', 'PUBLISHING', 'UNKNOWN', 'PROCESSED', 'SETTLED', 'REJECTED', 'CREDITED', 'EXPIRED'].includes(external.marketplaceState ?? '')
670
+ || (external.paymentState !== null && !['PREPARED', 'ATTEMPTED', 'PENDING', 'ACCEPTED', 'PUBLISHING', 'UNKNOWN', 'PROCESSED', 'SETTLED', 'REJECTED', 'CONFIRMED', 'FAILED'].includes(external.paymentState))
671
+ || !['challenged', 'unknown', 'confirmed', 'rejected'].includes(external.nativeState)
672
+ || (external.attemptedAt !== undefined && (!Number.isSafeInteger(external.attemptedAt) || external.attemptedAt < 0))
673
+ || (external.receivePending !== undefined && external.receivePending !== null && typeof external.receivePending !== 'boolean')
674
+ || (external.receiveStatus !== undefined && external.receiveStatus !== null
675
+ && !['PENDING', 'ACCEPTED', 'SETTLED', 'REJECTED'].includes(external.receiveStatus))) {
676
+ throw new Error('Invalid external payment record.');
677
+ }
678
+ if (external.nativeState === 'challenged' && external.attemptedAt !== undefined)
679
+ throw new Error('Invalid external attempt state.');
680
+ if (['unknown', 'confirmed', 'rejected'].includes(external.nativeState) && external.attemptedAt === undefined)
681
+ throw new Error('Missing external attempt marker.');
682
+ }
683
+ externalSecrets() {
684
+ const value = this.store.get(EXTERNAL_SECRETS_KEY) ?? {};
685
+ try {
686
+ if (!value || typeof value !== 'object' || Array.isArray(value))
687
+ throw new Error();
688
+ for (const [id, secret] of Object.entries(value)) {
689
+ const paymentKind = secret?.paymentKind ?? 'marketplace-topup';
690
+ const topUpOwnerInvalid = paymentKind === 'marketplace-topup' &&
691
+ (typeof secret?.accountId !== 'string' || typeof secret?.agentId !== 'string'
692
+ || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(secret.agentId)
693
+ || typeof secret?.identityId !== 'string' || !Number.isSafeInteger(secret?.controllerIndex)
694
+ || typeof secret?.controllerAddress !== 'string');
695
+ if (!id || !secret || secret.version !== 1 || !['marketplace-topup', 'marketplace-intent'].includes(paymentKind)
696
+ || (secret.paymentKind !== undefined && secret.paymentKind !== paymentKind)
697
+ || typeof secret.apiUrl !== 'string' || secret.apiUrl.length > 2048
698
+ || typeof secret.audience !== 'string' || secret.audience.length < 1 || secret.audience.length > 255
699
+ || topUpOwnerInvalid
700
+ || typeof secret.walletFingerprint !== 'string'
701
+ || (secret.controllerIndex !== undefined && (!Number.isSafeInteger(secret.controllerIndex) || secret.controllerIndex < 0 || secret.controllerIndex > 0x7fff_ffff))
702
+ || (secret.controllerAddress !== undefined && typeof secret.controllerAddress !== 'string') || typeof secret.requirementJson !== 'string'
703
+ || Buffer.byteLength(secret.requirementJson, 'utf8') > 65_536
704
+ || (secret.transactionJson !== undefined && Buffer.byteLength(secret.transactionJson, 'utf8') > 65_536)
705
+ || (secret.paymentJson !== undefined && Buffer.byteLength(secret.paymentJson, 'utf8') > 65_536)
706
+ || (secret.paymentSignature !== undefined && secret.paymentSignature.length > 90_000))
707
+ throw new Error();
708
+ }
709
+ return value;
710
+ }
711
+ catch {
712
+ throw new AttoError('INVALID_STATE', 'The private x402 payment journal is invalid. Restore verified wallet state before recovery.');
713
+ }
714
+ }
715
+ externalDefinition(external) {
716
+ if (!external)
717
+ return undefined;
718
+ const { kind, version, paymentIdentifier, network, intentId, resourceUrl, requirementHash, intentExpiresAt } = external;
719
+ return { kind, version, paymentIdentifier, network, intentId, resourceUrl, requirementHash, intentExpiresAt };
720
+ }
721
+ ownerDefinition(owner) {
722
+ const { version, paymentKind = 'marketplace-topup', apiUrl, audience, accountId, agentId, identityId, walletFingerprint, controllerIndex, controllerAddress } = owner;
723
+ return { version, paymentKind, apiUrl, audience, accountId, agentId, identityId, walletFingerprint, controllerIndex, controllerAddress };
436
724
  }
437
725
  planDefinition(plan) {
438
726
  if (!plan)
@@ -442,3 +730,6 @@ export class SpendLedger {
442
730
  })) };
443
731
  }
444
732
  }
733
+ function createHashHex(value) {
734
+ return createHash('sha256').update(value, 'utf8').digest('hex');
735
+ }
@@ -5,14 +5,82 @@ import type { MarketData } from '../pricing/market.js';
5
5
  import type { StateStore } from '../storage/state.js';
6
6
  import type { SendRequest, WalletAddress, WalletSettings } from '../wallet/types.js';
7
7
  import type { WalletWork } from '../wallet/work.js';
8
- import type { SpendLedger } from './ledger.js';
8
+ import { SpendLedger } from './ledger.js';
9
+ import { MarketplaceTopUpClient } from '../marketplace/topups.js';
9
10
  interface PaymentWallet {
10
11
  settings(): WalletSettings;
11
12
  addresses(): WalletAddress[];
12
13
  seed(): Promise<AttoSeed>;
13
14
  requireWrite(): void;
15
+ requireAccountsAvailable?(indexes: number[]): void;
14
16
  mcp: boolean;
15
17
  }
18
+ export interface MarketplaceTopUpRequest {
19
+ amount: string;
20
+ unit: 'ATTO' | 'RAW';
21
+ requestId: string;
22
+ index?: number;
23
+ }
24
+ export interface InternalMarketplacePaymentConfig {
25
+ apiUrl: string;
26
+ audience: string;
27
+ }
28
+ export interface MarketplacePayIntentRequest {
29
+ requestId: string;
30
+ intentId: string;
31
+ amountAtomic: string;
32
+ paymentIdentifier: string;
33
+ paymentRequired: string;
34
+ apiUrl: string;
35
+ audience: string;
36
+ resourceUrl: string;
37
+ expiresAt: string;
38
+ index?: number;
39
+ }
40
+ /** Canonical private-child DTOs; public wallet projections retain their normal presentation metadata. */
41
+ export interface MarketplaceIntentPayment {
42
+ requestId: string;
43
+ intentId: string;
44
+ paymentIdentifier: string;
45
+ network: string;
46
+ amountAtomic: string;
47
+ payer: string;
48
+ hash: string;
49
+ paymentSignature: string;
50
+ paymentState: 'READY';
51
+ reused: boolean;
52
+ nativeState?: 'unknown' | 'confirmed';
53
+ }
54
+ interface MarketplaceIntentFailureIdentity {
55
+ requestId: string;
56
+ intentId: string;
57
+ paymentIdentifier: string;
58
+ network: string;
59
+ amountAtomic: string;
60
+ payer: string;
61
+ paymentState: 'FAILED';
62
+ }
63
+ export type MarketplaceIntentPaymentFailure = MarketplaceIntentFailureIdentity & ({
64
+ hash: string;
65
+ nativeState: 'rejected';
66
+ failureReason: 'NATIVE_TRANSACTION_REJECTED';
67
+ } | {
68
+ hash: null;
69
+ nativeState: 'challenged';
70
+ failureReason: 'MARKETPLACE_CHALLENGE_EXPIRED';
71
+ });
72
+ export interface MarketplaceIntentPendingSignature {
73
+ requestId: string;
74
+ intentId: string;
75
+ network: string;
76
+ amountAtomic: string;
77
+ paymentState: 'PENDING_SIGNATURE';
78
+ nativeState: 'challenged';
79
+ }
80
+ export type MarketplaceIntentPaymentStatus = {
81
+ requestId: string;
82
+ paymentState: 'NOT_FOUND';
83
+ } | MarketplaceIntentPayment | MarketplaceIntentPaymentFailure | MarketplaceIntentPendingSignature;
16
84
  /** Owns payment selection, reservations, publication and recovery as one workflow. */
17
85
  export declare class Payments {
18
86
  private readonly store;
@@ -22,15 +90,47 @@ export declare class Payments {
22
90
  private readonly work;
23
91
  private readonly retry?;
24
92
  private readonly onDestination?;
25
- constructor(store: StateStore, ledger: SpendLedger, wallet: PaymentWallet, market: MarketData, work: WalletWork, retry?: SendRetry | undefined, onDestination?: ((binding: DestinationBinding) => void) | undefined);
93
+ private readonly topUps?;
94
+ private readonly internalMarketplacePayment?;
95
+ constructor(store: StateStore, ledger: SpendLedger, wallet: PaymentWallet, market: MarketData, work: WalletWork, retry?: SendRetry | undefined, onDestination?: ((binding: DestinationBinding) => void) | undefined, topUps?: MarketplaceTopUpClient | undefined, internalMarketplacePayment?: InternalMarketplacePaymentConfig | undefined);
26
96
  private reader;
27
97
  private indexes;
28
98
  private result;
29
99
  private paymentResult;
30
100
  private checkRequest;
31
101
  private requireApproved;
32
- /** Caller owns this account's lock; unresolved plans keep their accounts reserved. */
33
- requireAvailable(index: number): void;
102
+ marketplaceTopUp(request: MarketplaceTopUpRequest): Promise<unknown>;
103
+ marketplaceTopUpStatus(requestId: string): Promise<unknown>;
104
+ /** Sign an existing Marketplace x402 intent. This private-child path never creates or submits an intent. */
105
+ marketplacePayIntent(request: MarketplacePayIntentRequest): Promise<MarketplaceIntentPaymentStatus>;
106
+ /** Private Marketplace child recovery returns the original saved signature and never signs a replacement. */
107
+ marketplacePayIntentStatus(requestId: string): Promise<MarketplaceIntentPaymentStatus>;
108
+ private validateMarketplaceIntentRequest;
109
+ private checkMarketplaceIntentBinding;
110
+ private checkMarketplaceIntentOwner;
111
+ private savedMarketplaceIntentRequirement;
112
+ private prepareMarketplaceIntent;
113
+ private marketplaceIntentResult;
114
+ private topUpNetwork;
115
+ private reserveMarketplaceTopUp;
116
+ private resumeMarketplaceTopUp;
117
+ private runMarketplaceTopUp;
118
+ private prepareAndSubmitMarketplaceTopUp;
119
+ private refreshMarketplaceStatus;
120
+ private saveMarketplaceStatus;
121
+ private reconcileMarketplaceSend;
122
+ /** Caller holds this account's lock; the wallet lock makes the no-candidate check and release atomic. */
123
+ private expireUnsignedMarketplaceIntent;
124
+ private reconcileMarketplaceIntents;
125
+ private hasUnconfirmedMarketplacePayment;
126
+ private marketplaceFundingUsable;
127
+ private marketplaceStatusProjection;
128
+ private marketplaceTopUpResult;
129
+ private isLegacyCreditedMarketplaceTopUp;
130
+ private legacyMarketplaceTopUpResult;
131
+ private unreservedMarketplaceStatus;
132
+ private checkMarketplaceTopUpRequest;
133
+ private checkMarketplaceOwner;
34
134
  send(request: SendRequest): Promise<unknown>;
35
135
  private checkAccount;
36
136
  private resume;
@@ -39,7 +139,7 @@ export declare class Payments {
39
139
  private executeStep;
40
140
  private publish;
41
141
  private pendingReceivable;
42
- reconcile(): Promise<void>;
142
+ reconcile(candidateIndexes?: number[]): Promise<void>;
43
143
  private reconcileRecord;
44
144
  poolStatus(): Promise<{
45
145
  pool: import("../wallet/types.js").AccountPool;