@attocash/cli 0.6.0 → 0.7.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.
@@ -0,0 +1,122 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { z } from 'zod';
4
+ import { AttoError } from '../domain/errors.js';
5
+ import { parseJsonObject } from './strict-json.js';
6
+ const hash = z.string().regex(/^[a-fA-F0-9]{64}$/);
7
+ const integer = z.string().regex(/^(0|[1-9][0-9]*)$/);
8
+ const termsSchema = z.strictObject({ paymentId: z.string().uuid(), purpose: z.enum(['PUBLICATION_FEE', 'SHOP_ORDER', 'TASK_MILESTONE', 'BUYER_REFUND']),
9
+ sourceReference: z.string().min(1).max(512), ownerAccountId: z.string().uuid(), asset: z.enum(['ATTO', 'XNO']), network: z.string(),
10
+ senderAddress: z.string().min(1).max(160), recipientAddress: z.string().min(1).max(160), amountAtomic: z.string().regex(/^[1-9][0-9]{0,38}$/),
11
+ termsHash: hash, versionHash: hash, baselineHeight: integer, baselineFrontier: hash.nullable() });
12
+ export const MARKETPLACE_BINDING = 'marketplace-binding';
13
+ function invalid(message = 'The x402 offer differs from the frozen Marketplace payment.') { throw new AttoError('PAYMENT_PROTOCOL', message); }
14
+ function object(value) { if (!value || typeof value !== 'object' || Array.isArray(value))
15
+ invalid(); return value; }
16
+ export function decodePaymentHeader(header) {
17
+ if (typeof header !== 'string' || header.length < 1 || header.length > 90_000 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(header))
18
+ invalid('Invalid x402 header.');
19
+ const bytes = Buffer.from(header, 'base64');
20
+ if (bytes.length > 65_536 || bytes.toString('base64') !== header)
21
+ invalid('Invalid x402 header.');
22
+ try {
23
+ return parseJsonObject(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
24
+ }
25
+ catch {
26
+ return invalid('Invalid x402 JSON.');
27
+ }
28
+ }
29
+ export function parseRelayOffer(request, allowExpired = false, now = Date.now()) {
30
+ const terms = termsSchema.parse(request.terms);
31
+ let origin;
32
+ try {
33
+ origin = new URL(request.origin);
34
+ }
35
+ catch {
36
+ return invalid();
37
+ }
38
+ if (origin.origin !== request.origin || origin.username || origin.password || origin.pathname !== '/' || origin.search || origin.hash
39
+ || !/^https?:$/.test(origin.protocol) || (origin.protocol === 'http:' && !['localhost', '127.0.0.1', '[::1]'].includes(origin.hostname))
40
+ || typeof request.audience !== 'string' || request.audience.length < 1 || request.audience.length > 255
41
+ || request.requestId !== terms.paymentId || !/^[A-Za-z0-9_-]{16,128}$/.test(request.requestId))
42
+ invalid();
43
+ if (terms.asset === 'ATTO' ? !/^atto:(live|beta|dev|local)$/.test(terms.network) || BigInt(terms.amountAtomic) > (1n << 64n) - 1n
44
+ : !/^nano:(mainnet|dev)$/.test(terms.network) || BigInt(terms.amountAtomic) > (1n << 128n) - 1n)
45
+ invalid();
46
+ const raw = decodePaymentHeader(request.paymentRequired), resource = object(raw.resource);
47
+ if (raw.x402Version !== 2 || resource.url !== `${request.origin}/v1/agent/payments/${terms.paymentId}`
48
+ || !Array.isArray(raw.accepts) || raw.accepts.length !== 1)
49
+ invalid();
50
+ const accepted = object(raw.accepts[0]);
51
+ if (accepted.scheme !== 'exact' || accepted.network !== terms.network || accepted.asset !== (terms.asset === 'ATTO' ? 'atto' : 'XNO')
52
+ || accepted.payTo !== terms.recipientAddress || accepted.amount !== terms.amountAtomic
53
+ || accepted.maxTimeoutSeconds !== (terms.asset === 'ATTO' ? 60 : 300))
54
+ invalid();
55
+ if (terms.asset === 'ATTO' && !isDeepStrictEqual(accepted.extra, { assetTransferMethod: 'native', paymentFlow: 'authorization' }))
56
+ invalid();
57
+ // Nano proposal3432@96f65c29 does not declare transfer-method/flow metadata.
58
+ if (terms.asset === 'XNO' && accepted.extra !== undefined)
59
+ invalid('Unsupported Nano x402 profile metadata.');
60
+ const extensions = object(raw.extensions);
61
+ if (Object.keys(extensions).sort().join(',') !== 'marketplace-binding,payment-identifier')
62
+ invalid('Unsupported x402 extension.');
63
+ const identifier = object(extensions['payment-identifier']), idInfo = object(identifier.info);
64
+ object(identifier.schema);
65
+ if (idInfo.required !== true || Object.keys(idInfo).some(key => !['required', 'id'].includes(key))
66
+ || (idInfo.id !== undefined && idInfo.id !== request.requestId))
67
+ invalid();
68
+ const binding = object(extensions[MARKETPLACE_BINDING]), info = object(binding.info);
69
+ object(binding.schema);
70
+ const { offerExpiresAt, ...boundTerms } = info;
71
+ if (!isDeepStrictEqual(boundTerms, { required: true, version: 1, ...terms }) || Object.keys(binding).sort().join(',') !== 'info,schema'
72
+ || typeof offerExpiresAt !== 'string' || !/^\d{4}-\d\d-\d\dT/.test(offerExpiresAt))
73
+ invalid();
74
+ const expiresAt = Date.parse(offerExpiresAt);
75
+ if (!Number.isSafeInteger(expiresAt) || (!allowExpired && expiresAt <= now))
76
+ invalid('The unused x402 offer expired. Recover the original request before preparing a replacement.');
77
+ return { header: request.paymentRequired, raw, terms, expiresAt };
78
+ }
79
+ /** Only an unused, expired offer window can change; every other offered byte remains semantically identical. */
80
+ export function validateRelayOfferRefresh(previous, next, now = Date.now()) {
81
+ const definition = (request) => ({ requestId: request.requestId, origin: request.origin, audience: request.audience, terms: request.terms, index: request.index });
82
+ const oldOffer = parseRelayOffer(previous, true, now), freshOffer = parseRelayOffer(next, false, now);
83
+ const withoutWindow = (offer) => {
84
+ const extensions = object(offer.raw.extensions), binding = object(extensions[MARKETPLACE_BINDING]);
85
+ const { offerExpiresAt: _unused, ...info } = object(binding.info);
86
+ return { ...offer.raw, extensions: { ...extensions, [MARKETPLACE_BINDING]: { ...binding, info } } };
87
+ };
88
+ if (oldOffer.expiresAt > now || freshOffer.expiresAt <= oldOffer.expiresAt || !isDeepStrictEqual(definition(previous), definition(next))
89
+ || !isDeepStrictEqual(withoutWindow(oldOffer), withoutWindow(freshOffer)))
90
+ invalid('Only an expired unused offer window may be refreshed for the original payment.');
91
+ }
92
+ export function relayEvidenceBinding(terms, transactionHash) {
93
+ return createHash('sha256').update(['Marketplace payment evidence v1', terms.paymentId, terms.versionHash, terms.termsHash,
94
+ terms.ownerAccountId, terms.network, terms.senderAddress, terms.recipientAddress, terms.amountAtomic, transactionHash.toLowerCase()].join('\n')).digest('hex');
95
+ }
96
+ export function validateRelayProof(offer, transactionHash, audience, proof, allowExpired = false, now = Date.now()) {
97
+ const parsed = z.strictObject({ challengeId: z.string().uuid(), message: z.string().min(1).max(4096), signature: z.string().regex(/^[a-fA-F0-9]{128}$/) }).safeParse(proof);
98
+ if (!parsed.success)
99
+ invalid('Invalid payment proof.');
100
+ const lines = proof.message.split('\n'), p = offer.terms;
101
+ if (lines.length !== 10 || /[\r\0]/.test(proof.message) || lines[0] !== `${p.asset === 'ATTO' ? '' : 'Nano '}Marketplace Agent Controller Proof v1`
102
+ || lines[1] !== `Audience: ${audience}` || lines[2] !== `Network: ${p.asset === 'ATTO' ? 'live' : p.network}`
103
+ || lines[3] !== `Address: ${p.senderAddress}` || lines[4] !== 'Purpose: payment evidence' || lines[5] !== `Request ID: ${proof.challengeId}`
104
+ || lines[6] !== `Binding Hash: ${relayEvidenceBinding(p, transactionHash)}` || !/^Nonce: [a-f0-9]{64}$/.test(lines[7])
105
+ || !lines[8].startsWith('Issued At: ') || !lines[9].startsWith('Expiration Time: '))
106
+ invalid('Payment proof differs from the original candidate or audience.');
107
+ const issued = Date.parse(lines[8].slice(11)), expires = Date.parse(lines[9].slice(17));
108
+ if (!Number.isSafeInteger(issued) || !Number.isSafeInteger(expires) || expires <= issued || expires - issued > 300_000
109
+ || (!allowExpired && (issued > now + 30_000 || expires <= now)))
110
+ invalid('Payment proof expired or has invalid timing.');
111
+ }
112
+ export function relayPaymentPayload(offer, requestId, payload, proof) {
113
+ const extensions = object(offer.raw.extensions), identifier = object(extensions['payment-identifier']), binding = object(extensions[MARKETPLACE_BINDING]);
114
+ const raw = { x402Version: 2, resource: offer.raw.resource, accepted: offer.raw.accepts[0], payload,
115
+ extensions: { ...extensions, 'payment-identifier': { ...identifier, info: { ...object(identifier.info), id: requestId } },
116
+ [MARKETPLACE_BINDING]: { ...binding, proof } } };
117
+ const json = JSON.stringify(raw);
118
+ if (Buffer.byteLength(json) > 65_536)
119
+ invalid('The x402 payload exceeds its byte limit.');
120
+ return Buffer.from(json).toString('base64');
121
+ }
122
+ export function relayProofFromHeader(header) { return object(object(decodePaymentHeader(header).extensions)[MARKETPLACE_BINDING]).proof; }
@@ -0,0 +1,2 @@
1
+ /** JSON.parse semantics with duplicate-field rejection, bounded depth, and no trailing tokens. */
2
+ export declare function parseJsonObject(text: string): Record<string, unknown>;
@@ -0,0 +1,96 @@
1
+ const MAX_JSON_BYTES = 1_000_000;
2
+ function objectValue(value) {
3
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
4
+ throw new Error('Expected a JSON object');
5
+ return value;
6
+ }
7
+ /** JSON.parse semantics with duplicate-field rejection, bounded depth, and no trailing tokens. */
8
+ export function parseJsonObject(text) {
9
+ if (Buffer.byteLength(text, 'utf8') > MAX_JSON_BYTES)
10
+ throw new Error('JSON input exceeds its byte limit');
11
+ // JSON.parse performs complete syntax validation. The second pass checks the
12
+ // source keys before duplicate names can be discarded by object construction.
13
+ const result = objectValue(JSON.parse(text));
14
+ let offset = 0;
15
+ const primitive = /(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/y;
16
+ const whitespace = () => { while (/[\x20\x09\x0a\x0d]/.test(text[offset] ?? '!'))
17
+ offset++; };
18
+ const quoted = () => {
19
+ whitespace();
20
+ if (text[offset] !== '"')
21
+ throw new Error('Invalid JSON string');
22
+ const start = offset++;
23
+ // Whole-document JSON.parse already validated escapes; locate only the token boundary.
24
+ while (offset < text.length) {
25
+ const character = text[offset++];
26
+ if (character === '\\')
27
+ offset++;
28
+ else if (character === '"')
29
+ return JSON.parse(text.slice(start, offset));
30
+ }
31
+ throw new Error('Invalid JSON string');
32
+ };
33
+ const scan = (depth) => {
34
+ if (depth > 64)
35
+ throw new Error('JSON nesting exceeds its limit');
36
+ whitespace();
37
+ const character = text[offset];
38
+ if (character === '{') {
39
+ offset++;
40
+ whitespace();
41
+ if (text[offset] === '}') {
42
+ offset++;
43
+ return;
44
+ }
45
+ const keys = new Set();
46
+ while (true) {
47
+ const key = quoted();
48
+ if (keys.has(key))
49
+ throw new Error('Duplicate JSON field');
50
+ keys.add(key);
51
+ whitespace();
52
+ if (text[offset++] !== ':')
53
+ throw new Error('Invalid JSON object');
54
+ scan(depth + 1);
55
+ whitespace();
56
+ if (text[offset] === '}') {
57
+ offset++;
58
+ return;
59
+ }
60
+ if (text[offset++] !== ',')
61
+ throw new Error('Invalid JSON object');
62
+ }
63
+ }
64
+ if (character === '[') {
65
+ offset++;
66
+ whitespace();
67
+ if (text[offset] === ']') {
68
+ offset++;
69
+ return;
70
+ }
71
+ while (true) {
72
+ scan(depth + 1);
73
+ whitespace();
74
+ if (text[offset] === ']') {
75
+ offset++;
76
+ return;
77
+ }
78
+ if (text[offset++] !== ',')
79
+ throw new Error('Invalid JSON array');
80
+ }
81
+ }
82
+ if (character === '"') {
83
+ quoted();
84
+ return;
85
+ }
86
+ primitive.lastIndex = offset;
87
+ if (!primitive.exec(text))
88
+ throw new Error('Invalid JSON value');
89
+ offset = primitive.lastIndex;
90
+ };
91
+ scan(0);
92
+ whitespace();
93
+ if (offset !== text.length)
94
+ throw new Error('Trailing JSON input');
95
+ return result;
96
+ }
@@ -20,6 +20,8 @@ export declare function parseAttoExactRequirement(input: {
20
20
  network: AttoPaymentNetwork;
21
21
  amountRaw: string;
22
22
  }): AttoExactRequirement;
23
+ /** Build the x402 string profile directly from exact Commons values, leaving native JSON untouched. */
24
+ export declare function wireTransaction(transaction: AttoTransaction): Record<string, unknown>;
23
25
  export declare function paymentPayload(requirement: AttoExactRequirement, paymentIdentifier: string, transaction: AttoTransaction): {
24
26
  json: string;
25
27
  header: string;
@@ -89,7 +89,7 @@ export function parseAttoExactRequirement(input) {
89
89
  };
90
90
  }
91
91
  /** Build the x402 string profile directly from exact Commons values, leaving native JSON untouched. */
92
- function wireTransaction(transaction) {
92
+ export function wireTransaction(transaction) {
93
93
  const block = transaction.block;
94
94
  if (!(block instanceof AttoSendBlock))
95
95
  throw new AttoError('MARKETPLACE_PROTOCOL', 'An ATTO payment must be a native SEND.');
@@ -13,6 +13,8 @@ export interface ConsolidationStep {
13
13
  status: PaymentStepStatus;
14
14
  hash?: string;
15
15
  blockJson?: string;
16
+ transactionJson?: string;
17
+ candidateBinding?: string;
16
18
  result?: unknown;
17
19
  publishedAt?: number;
18
20
  }
@@ -26,3 +28,10 @@ export declare function validatePaymentPlan(plan: PaymentPlan, parent: {
26
28
  index: number;
27
29
  sourceAddress?: string;
28
30
  }): void;
31
+ /** Optional for released block-only journals; new candidates retain exact native bytes. */
32
+ export declare function validateNativeCandidate(record: {
33
+ hash?: string;
34
+ blockJson?: string;
35
+ transactionJson?: string;
36
+ candidateBinding?: string;
37
+ }): void;
@@ -37,6 +37,7 @@ export function validatePaymentPlan(plan, parent) {
37
37
  if (accountAddresses.has(step.index) && accountAddresses.get(step.index) !== step.sourceAddress)
38
38
  throw new Error('Inconsistent step account.');
39
39
  accountAddresses.set(step.index, step.sourceAddress);
40
+ validateNativeCandidate(step);
40
41
  if (step.hash !== undefined && (typeof step.hash !== 'string' || !step.hash || typeof step.blockJson !== 'string' || !step.blockJson))
41
42
  throw new Error('Invalid recorded step.');
42
43
  if (['signed', 'published', 'unknown'].includes(step.status) && !step.hash)
@@ -67,3 +68,13 @@ export function validatePaymentPlan(plan, parent) {
67
68
  if (sentRaw !== receivedRaw || [...steps.values()].some(step => step.kind === 'send' && !received.has(step.id)))
68
69
  throw new Error('Incomplete consolidation plan.');
69
70
  }
71
+ /** Optional for released block-only journals; new candidates retain exact native bytes. */
72
+ export function validateNativeCandidate(record) {
73
+ if (record.transactionJson === undefined && record.candidateBinding === undefined)
74
+ return;
75
+ if (!record.hash || !record.blockJson || typeof record.transactionJson !== 'string'
76
+ || Buffer.byteLength(record.transactionJson, 'utf8') < 1 || Buffer.byteLength(record.transactionJson, 'utf8') > 65_536
77
+ || typeof record.candidateBinding !== 'string' || !/^[a-f0-9]{64}$/.test(record.candidateBinding)) {
78
+ throw new Error('Invalid retained native candidate.');
79
+ }
80
+ }
@@ -1,4 +1,5 @@
1
1
  import { type AttoPaymentNetwork } from './atto-x402.js';
2
+ import { type RelayRecord } from '../marketplace/relay.js';
2
3
  import { type DestinationBinding } from './destination.js';
3
4
  import type { StateStore } from '../storage/state.js';
4
5
  import type { AccountPool, SpendingPolicy } from '../wallet/types.js';
@@ -14,6 +15,8 @@ export interface SendRecord {
14
15
  status: 'reserved' | 'signed' | 'published' | 'unknown' | 'failed';
15
16
  hash?: string;
16
17
  blockJson?: string;
18
+ transactionJson?: string;
19
+ candidateBinding?: string;
17
20
  result?: unknown;
18
21
  publishedAt?: number;
19
22
  sourceAddress?: string;
@@ -23,6 +26,7 @@ export interface SendRecord {
23
26
  selection?: 'automatic' | 'explicit';
24
27
  plan?: PaymentPlan;
25
28
  external?: ExternalPaymentRecord | LegacyExternalPaymentRecord;
29
+ relay?: RelayRecord;
26
30
  }
27
31
  export interface ExternalPaymentRecord {
28
32
  kind: 'marketplace-topup' | 'marketplace-intent';
@@ -62,7 +66,7 @@ export interface ExternalPaymentSecrets {
62
66
  paymentJson?: string;
63
67
  paymentSignature?: string;
64
68
  }
65
- export type SendReservation = Pick<SendRecord, 'id' | 'index' | 'destination' | 'raw' | 'createdAt'> & Partial<Pick<SendRecord, 'sourceAddress' | 'network' | 'metadata' | 'quote' | 'selection' | 'plan' | 'destinationBinding'>> & {
69
+ export type SendReservation = Pick<SendRecord, 'id' | 'index' | 'destination' | 'raw' | 'createdAt'> & Partial<Pick<SendRecord, 'sourceAddress' | 'network' | 'metadata' | 'quote' | 'selection' | 'plan' | 'destinationBinding' | 'relay'>> & {
66
70
  external?: ExternalPaymentRecord;
67
71
  };
68
72
  export type McpAccess = 'read-only' | 'spend';
@@ -116,7 +120,11 @@ export declare class SpendLedger {
116
120
  items: SendRecord[];
117
121
  nextCursor?: string;
118
122
  };
119
- signed(id: string, hash: string, blockJson: string): void;
123
+ signed(id: string, hash: string, blockJson: string, transactionJson?: string, candidateBinding?: string): void;
124
+ /** The exact final header is immutable before any caller may submit it to Market. */
125
+ authorizeRelay(id: string, paymentSignature: string): void;
126
+ /** Caller holds the same account/wallet locks used by signing and candidate persistence. */
127
+ refreshUnusedRelay(id: string, relay: RelayRecord): void;
120
128
  /** Persist the exact offered requirement before any external SEND is signed. */
121
129
  externalChallenge(id: string, requirementJson: string, owner: Omit<ExternalPaymentSecrets, 'requirementJson' | 'transactionJson' | 'paymentJson' | 'paymentSignature' | 'paymentKind'>): void;
122
130
  /** Exact signed bytes and the attempt fence commit atomically before HTTP submission. */
@@ -140,7 +148,7 @@ export declare class SpendLedger {
140
148
  fail(id: string): void;
141
149
  /** Caller must first prove a different canonical block at this block's height. */
142
150
  reject(id: string): void;
143
- stepSigned(id: string, stepId: string, hash: string, blockJson: string): void;
151
+ stepSigned(id: string, stepId: string, hash: string, blockJson: string, transactionJson?: string, candidateBinding?: string): void;
144
152
  stepComplete(id: string, stepId: string, result: unknown, publishedAt: number): void;
145
153
  stepUncertain(id: string, stepId: string): void;
146
154
  /** Caller must prove this internal block conflicts with the canonical chain.
@@ -1,11 +1,12 @@
1
1
  import { paymentTransactionMatches } from './atto-x402.js';
2
+ import { parseRelayOffer, validateRelayOfferRefresh } from '../marketplace/relay.js';
2
3
  import { validateDestinationBinding } from './destination.js';
3
4
  import { createHash, randomUUID } from 'node:crypto';
4
5
  import { isDeepStrictEqual } from 'node:util';
5
6
  import { AttoBlock, AttoSendBlock, AttoTransaction } from '@attocash/commons-core';
6
7
  import { amountRaw } from '../domain/amount.js';
7
8
  import { AttoError } from '../domain/errors.js';
8
- import { paymentMetadataSchema, validatePaymentPlan } from './journal.js';
9
+ import { paymentMetadataSchema, validatePaymentPlan, validateNativeCandidate } from './journal.js';
9
10
  const DAY_MS = 86_400_000;
10
11
  const POLICY_KEY = 'spending.policy';
11
12
  const RECORDS_KEY = 'spending.records';
@@ -196,7 +197,8 @@ export class SpendLedger {
196
197
  || ['sourceAddress', 'network', 'metadata', 'quote', 'selection'].some(key => {
197
198
  const field = key;
198
199
  return request[field] !== undefined && !isDeepStrictEqual(request[field], existing[field]);
199
- }) || (request.plan !== undefined && !isDeepStrictEqual(this.planDefinition(request.plan), this.planDefinition(existing.plan)))
200
+ }) || (request.relay !== undefined && !isDeepStrictEqual({ ...existing.relay, paymentSignature: undefined }, { ...request.relay, paymentSignature: undefined }))
201
+ || (request.plan !== undefined && !isDeepStrictEqual(this.planDefinition(request.plan), this.planDefinition(existing.plan)))
200
202
  || (request.external !== undefined && !isDeepStrictEqual(this.externalDefinition(request.external), this.externalDefinition(existing.external)))) {
201
203
  throw new AttoError('REQUEST_CONFLICT', 'This request ID already belongs to a different payment.');
202
204
  }
@@ -292,16 +294,38 @@ export class SpendLedger {
292
294
  nextCursor: Buffer.from(JSON.stringify({ version: 1, before: items.at(-1).id, status: options.status ?? null })).toString('base64url'),
293
295
  } : {}) };
294
296
  }
295
- signed(id, hash, blockJson) {
297
+ signed(id, hash, blockJson, transactionJson, candidateBinding) {
296
298
  this.update(id, (record) => {
297
- if (record.status === 'published' || record.status === 'failed' || (record.hash && record.hash !== hash)) {
299
+ if (record.status === 'published' || record.status === 'failed' || (record.hash && (record.hash !== hash || record.blockJson !== blockJson))
300
+ || (record.transactionJson !== undefined && (record.transactionJson !== transactionJson || record.candidateBinding !== candidateBinding))) {
298
301
  throw new AttoError('SEND_STATE', 'This payment cannot be assigned a new block.');
299
302
  }
300
303
  if (!hash || !blockJson)
301
304
  throw new AttoError('SEND_STATE', 'A signed payment requires its block hash and block.');
302
305
  if (record.plan?.steps.some(step => step.status !== 'published'))
303
306
  throw new AttoError('SEND_STATE', 'Complete every consolidation step before signing the external payment.');
304
- return { ...record, hash, blockJson, status: 'signed' };
307
+ return { ...record, hash, blockJson, ...(transactionJson !== undefined ? { transactionJson, candidateBinding } : {}), status: 'signed' };
308
+ });
309
+ }
310
+ /** The exact final header is immutable before any caller may submit it to Market. */
311
+ authorizeRelay(id, paymentSignature) {
312
+ this.update(id, record => {
313
+ if (!record.relay || !record.transactionJson || !record.hash || record.status === 'failed'
314
+ || (record.relay.paymentSignature !== undefined && record.relay.paymentSignature !== paymentSignature)) {
315
+ throw new AttoError('REQUEST_CONFLICT', 'The original relay payment cannot be replaced.');
316
+ }
317
+ return { ...record, relay: { ...record.relay, paymentSignature } };
318
+ });
319
+ }
320
+ /** Caller holds the same account/wallet locks used by signing and candidate persistence. */
321
+ refreshUnusedRelay(id, relay) {
322
+ this.update(id, record => {
323
+ if (!record.relay || record.status !== 'reserved' || record.hash !== undefined || record.blockJson !== undefined
324
+ || record.transactionJson !== undefined || record.candidateBinding !== undefined || record.relay.paymentSignature !== undefined
325
+ || record.plan?.steps.some(step => step.hash !== undefined))
326
+ throw new AttoError('REQUEST_CONFLICT', 'A retained native candidate can never accept another offer window.');
327
+ validateRelayOfferRefresh(record.relay, relay);
328
+ return { ...record, relay };
305
329
  });
306
330
  }
307
331
  /** Persist the exact offered requirement before any external SEND is signed. */
@@ -466,14 +490,15 @@ export class SpendLedger {
466
490
  return { ...record, status: 'failed' };
467
491
  });
468
492
  }
469
- stepSigned(id, stepId, hash, blockJson) {
493
+ stepSigned(id, stepId, hash, blockJson, transactionJson, candidateBinding) {
470
494
  this.updateStep(id, stepId, (step, position, plan) => {
471
495
  if (step.status === 'published' || step.status === 'failed' || !hash || !blockJson
472
496
  || (step.hash !== undefined && (step.hash !== hash || step.blockJson !== blockJson))
497
+ || (step.transactionJson !== undefined && (step.transactionJson !== transactionJson || step.candidateBinding !== candidateBinding))
473
498
  || plan.steps.slice(0, position).some(previous => previous.status !== 'published')) {
474
499
  throw new AttoError('SEND_STATE', 'This consolidation step cannot be assigned a new block.');
475
500
  }
476
- return { ...step, hash, blockJson, status: 'signed' };
501
+ return { ...step, hash, blockJson, ...(transactionJson !== undefined ? { transactionJson, candidateBinding } : {}), status: 'signed' };
477
502
  });
478
503
  }
479
504
  stepComplete(id, stepId, result, publishedAt) {
@@ -632,6 +657,7 @@ export class SpendLedger {
632
657
  }
633
658
  }
634
659
  validateDetails(record, historical = false) {
660
+ validateNativeCandidate(record);
635
661
  if (record.destinationBinding !== undefined) {
636
662
  validateDestinationBinding(record.destinationBinding);
637
663
  if (record.destinationBinding.address !== record.destination || record.destinationBinding.network !== record.network)
@@ -649,6 +675,15 @@ export class SpendLedger {
649
675
  validatePaymentPlan(record.plan, record);
650
676
  if (record.external !== undefined)
651
677
  this.validateExternal(record.external, historical);
678
+ if (record.relay !== undefined) {
679
+ if (record.external || record.relay.version !== 1 || record.id !== record.relay.requestId || record.relay.index !== record.index || record.plan?.steps.length
680
+ || record.sourceAddress !== record.relay.terms.senderAddress || record.destination !== record.relay.terms.recipientAddress
681
+ || record.raw !== record.relay.terms.amountAtomic || record.relay.terms.asset !== 'ATTO'
682
+ || `atto:${record.network?.toLowerCase()}` !== record.relay.terms.network
683
+ || (record.relay.paymentSignature !== undefined && (typeof record.relay.paymentSignature !== 'string' || record.relay.paymentSignature.length > 90_000)))
684
+ throw new Error('Invalid relay payment.');
685
+ parseRelayOffer(record.relay, true);
686
+ }
652
687
  }
653
688
  validateExternal(external, historical = false) {
654
689
  if (historical && external && (external.kind === 'market-topup' || external.kind === 'market-intent')) {
@@ -6,7 +6,6 @@ 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
8
  import { SpendLedger } from './ledger.js';
9
- import { MarketplaceTopUpClient } from '../marketplace/topups.js';
10
9
  interface PaymentWallet {
11
10
  settings(): WalletSettings;
12
11
  addresses(): WalletAddress[];
@@ -90,47 +89,13 @@ export declare class Payments {
90
89
  private readonly work;
91
90
  private readonly retry?;
92
91
  private readonly onDestination?;
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);
92
+ constructor(store: StateStore, ledger: SpendLedger, wallet: PaymentWallet, market: MarketData, work: WalletWork, retry?: SendRetry | undefined, onDestination?: ((binding: DestinationBinding) => void) | undefined);
96
93
  private reader;
97
94
  private indexes;
98
95
  private result;
99
96
  private paymentResult;
100
97
  private checkRequest;
101
98
  private requireApproved;
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;
134
99
  send(request: SendRequest): Promise<unknown>;
135
100
  private checkAccount;
136
101
  private resume;
@@ -138,6 +103,14 @@ export declare class Payments {
138
103
  private execute;
139
104
  private executeStep;
140
105
  private publish;
106
+ private candidateBinding;
107
+ private checkBlock;
108
+ private retainedTransaction;
109
+ private replay;
110
+ prepareRelay(input: Record<string, unknown>): Promise<unknown>;
111
+ private relayResult;
112
+ relayStatus(input: Record<string, unknown>): Promise<unknown>;
113
+ authorizeRelay(input: Record<string, unknown>): Promise<unknown>;
141
114
  private pendingReceivable;
142
115
  reconcile(candidateIndexes?: number[]): Promise<void>;
143
116
  private reconcileRecord;