@attocash/cli 0.6.0 → 0.8.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.
@@ -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;