@outpost-protocol/core 0.1.0 → 0.2.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.
package/dist/wallet.js CHANGED
@@ -92,6 +92,12 @@ class BoundedSignedOrderLru {
92
92
  size() {
93
93
  return this.map.size;
94
94
  }
95
+ entries() {
96
+ return Array.from(this.map.values(), (rec) => cloneSignedOrderRecord(rec));
97
+ }
98
+ clear() {
99
+ this.map.clear();
100
+ }
95
101
  }
96
102
  function clonePocketRecord(record) {
97
103
  return {
@@ -130,9 +136,12 @@ export class InMemoryWalletStorage {
130
136
  existing.vaultId === cloned.vaultId &&
131
137
  existing.pocketId === cloned.pocketId &&
132
138
  existing.epoch === cloned.epoch) {
139
+ const prevSpent = existing.estimatedSpent ?? 0n;
140
+ const nextSpent = cloned.estimatedSpent ?? 0n;
133
141
  const merged = {
134
142
  ...cloned,
135
143
  localSeq: Math.max(existing.localSeq, cloned.localSeq),
144
+ estimatedSpent: prevSpent > nextSpent ? prevSpent : nextSpent,
136
145
  anchor: {
137
146
  ledgerSeq: Math.max(existing.anchor.ledgerSeq, cloned.anchor.ledgerSeq),
138
147
  timestamp: Math.max(existing.anchor.timestamp, cloned.anchor.timestamp),
@@ -142,10 +151,13 @@ export class InMemoryWalletStorage {
142
151
  this.onPersist?.({ op: "savePocket", pocketKey, localSeq: merged.localSeq });
143
152
  return;
144
153
  }
145
- this.pockets.set(pocketKey, cloned);
154
+ this.pockets.set(pocketKey, {
155
+ ...cloned,
156
+ estimatedSpent: cloned.estimatedSpent ?? 0n,
157
+ });
146
158
  this.onPersist?.({ op: "savePocket", pocketKey, localSeq: cloned.localSeq });
147
159
  }
148
- async burnNextSeq(pocketKey) {
160
+ async burnNextSeq(pocketKey, costDelta) {
149
161
  const existing = this.pockets.get(pocketKey);
150
162
  if (!existing) {
151
163
  throw new Error(`Pocket not found: ${pocketKey}`);
@@ -153,8 +165,18 @@ export class InMemoryWalletStorage {
153
165
  if (existing.localSeq >= MAX_U32) {
154
166
  throw new Error(`Pocket ${pocketKey} sequence counter exhausted (u32::MAX)`);
155
167
  }
168
+ const delta = costDelta ?? 0n;
169
+ assertBigInt(delta, "costDelta");
170
+ if (delta < 0n) {
171
+ throw new Error(`costDelta must be >= 0, got ${delta}`);
172
+ }
156
173
  const nextSeq = existing.localSeq + 1;
157
- const updated = { ...existing, localSeq: nextSeq };
174
+ const nextSpent = (existing.estimatedSpent ?? 0n) + delta;
175
+ const updated = {
176
+ ...existing,
177
+ localSeq: nextSeq,
178
+ estimatedSpent: nextSpent,
179
+ };
158
180
  this.pockets.set(pocketKey, updated);
159
181
  this.onPersist?.({ op: "burnNextSeq", pocketKey, localSeq: nextSeq });
160
182
  return nextSeq;
@@ -173,6 +195,44 @@ export class InMemoryWalletStorage {
173
195
  this.onPersist?.({ op: "advanceSeq", pocketKey, localSeq: newSeq });
174
196
  return newSeq;
175
197
  }
198
+ async syncEstimatedSpent(pocketKey, cumulativeSpent) {
199
+ assertBigInt(cumulativeSpent, "cumulativeSpent");
200
+ if (cumulativeSpent < 0n || cumulativeSpent > MAX_U64) {
201
+ throw new RangeError(`cumulativeSpent out of u64 range: ${cumulativeSpent}`);
202
+ }
203
+ const existing = this.pockets.get(pocketKey);
204
+ if (!existing) {
205
+ throw new Error(`Pocket not found: ${pocketKey}`);
206
+ }
207
+ const current = existing.estimatedSpent ?? 0n;
208
+ if (cumulativeSpent <= current) {
209
+ return current;
210
+ }
211
+ const updated = { ...existing, estimatedSpent: cumulativeSpent };
212
+ this.pockets.set(pocketKey, updated);
213
+ this.onPersist?.({ op: "syncEstimatedSpent", pocketKey, localSeq: updated.localSeq });
214
+ return cumulativeSpent;
215
+ }
216
+ exportSnapshot() {
217
+ const pockets = {};
218
+ for (const [k, v] of this.pockets.entries()) {
219
+ pockets[k] = clonePocketRecord(v);
220
+ }
221
+ return {
222
+ pockets,
223
+ signedOrders: this.signedOrders.entries(),
224
+ };
225
+ }
226
+ importSnapshot(snapshot) {
227
+ this.pockets.clear();
228
+ this.signedOrders.clear();
229
+ for (const [k, v] of Object.entries(snapshot.pockets)) {
230
+ this.pockets.set(k, clonePocketRecord(v));
231
+ }
232
+ for (const ord of snapshot.signedOrders) {
233
+ this.signedOrders.set(ord);
234
+ }
235
+ }
176
236
  async updateAnchor(pocketKey, anchor) {
177
237
  assertU32(anchor.ledgerSeq, "anchor.ledgerSeq");
178
238
  assertU32(anchor.timestamp, "anchor.timestamp");
@@ -247,6 +307,8 @@ export class OfflineWallet {
247
307
  tokenResolver;
248
308
  defaultClockCone;
249
309
  fallbackSignedOrders = new BoundedSignedOrderLru(DEFAULT_MAX_SIGNED_ORDERS_LRU);
310
+ /** Bounded fallback spent tracker for legacy custom WalletStorage adapters ignoring burnNextSeq's costDelta. */
311
+ fallbackEstimatedSpent = new Map();
250
312
  /** R5-H13: Per-pocket FIFO async mutex serializing registerPocket, signVaultIntent, resyncFromLatestCert, and refreshAnchor. */
251
313
  pocketLocks = new Map();
252
314
  constructor(storage, tokenResolverOrOptions) {
@@ -293,6 +355,23 @@ export class OfflineWallet {
293
355
  this.fallbackSignedOrders.set(record);
294
356
  }
295
357
  }
358
+ effectiveEstimatedSpent(pocketKey, pocket) {
359
+ const stored = pocket.estimatedSpent ?? 0n;
360
+ const fallback = this.fallbackEstimatedSpent.get(pocketKey) ?? 0n;
361
+ return stored > fallback ? stored : fallback;
362
+ }
363
+ setFallbackEstimatedSpent(pocketKey, spent) {
364
+ const prev = this.fallbackEstimatedSpent.get(pocketKey) ?? 0n;
365
+ const next = spent > prev ? spent : prev;
366
+ this.fallbackEstimatedSpent.delete(pocketKey);
367
+ this.fallbackEstimatedSpent.set(pocketKey, next);
368
+ while (this.fallbackEstimatedSpent.size > 1_024) {
369
+ const oldest = this.fallbackEstimatedSpent.keys().next().value;
370
+ if (oldest === undefined)
371
+ break;
372
+ this.fallbackEstimatedSpent.delete(oldest);
373
+ }
374
+ }
296
375
  /**
297
376
  * Register an onboarded `UserVault` pocket into atomic wallet storage.
298
377
  * Performs 0-RPC 108-byte `VaultFactory` vault ID derivation and validates all invariants.
@@ -340,11 +419,17 @@ export class OfflineWallet {
340
419
  const resolvedToken = resolver.resolve(params.token, params.networkHint);
341
420
  const initialSeq = params.initialSeq ?? 0;
342
421
  assertU32(initialSeq, "initialSeq");
422
+ const initialEstimatedSpent = params.initialEstimatedSpent ?? 0n;
423
+ assertBigInt(initialEstimatedSpent, "initialEstimatedSpent");
424
+ if (initialEstimatedSpent < 0n || initialEstimatedSpent > params.epochTotalDeposited) {
425
+ throw new Error(`initialEstimatedSpent (${initialEstimatedSpent}) must be in 0..=${params.epochTotalDeposited}`);
426
+ }
343
427
  const pocketKey = makePocketKey(derived.contractId, params.pocketId, params.epoch);
344
428
  return this.withPocketLock(pocketKey, async () => {
345
429
  // M-NEW-5 & R5-H13: Guard against regressing localSeq or mutating immutable epoch parameters on re-registration!
346
430
  const existing = await this.storage.getPocket(pocketKey);
347
431
  let effectiveLocalSeq = initialSeq;
432
+ let effectiveEstimatedSpent = initialEstimatedSpent;
348
433
  let effectiveAnchor = { ...params.anchor };
349
434
  if (existing !== undefined) {
350
435
  if (existing.networkHint !== params.networkHint ||
@@ -370,6 +455,9 @@ export class OfflineWallet {
370
455
  throw new Error(`Cannot re-register existing pocket ${pocketKey} with different exitDelaySecs`);
371
456
  }
372
457
  effectiveLocalSeq = Math.max(existing.localSeq, initialSeq);
458
+ const existingSpent = this.effectiveEstimatedSpent(pocketKey, existing);
459
+ effectiveEstimatedSpent =
460
+ existingSpent > initialEstimatedSpent ? existingSpent : initialEstimatedSpent;
373
461
  effectiveAnchor = {
374
462
  ledgerSeq: Math.max(existing.anchor.ledgerSeq, params.anchor.ledgerSeq),
375
463
  timestamp: Math.max(existing.anchor.timestamp, params.anchor.timestamp),
@@ -396,14 +484,38 @@ export class OfflineWallet {
396
484
  exitDelaySecs: params.exitDelaySecs,
397
485
  anchor: effectiveAnchor,
398
486
  localSeq: effectiveLocalSeq,
487
+ estimatedSpent: effectiveEstimatedSpent,
399
488
  };
400
489
  await this.storage.savePocket(pocketKey, record);
490
+ if (effectiveEstimatedSpent > 0n) {
491
+ this.setFallbackEstimatedSpent(pocketKey, effectiveEstimatedSpent);
492
+ }
401
493
  return { pocketKey, record };
402
494
  });
403
495
  }
404
496
  async getPocket(pocketKey) {
405
497
  return this.storage.getPocket(pocketKey);
406
498
  }
499
+ /**
500
+ * Return the current running spend budget for a registered pocket.
501
+ */
502
+ async getPocketBudget(pocketKey) {
503
+ const pocket = await this.storage.getPocket(pocketKey);
504
+ if (!pocket) {
505
+ throw new Error(`Pocket not found: ${pocketKey}`);
506
+ }
507
+ const estimatedSpent = this.effectiveEstimatedSpent(pocketKey, pocket);
508
+ const remainingBudget = pocket.epochTotalDeposited > estimatedSpent
509
+ ? pocket.epochTotalDeposited - estimatedSpent
510
+ : 0n;
511
+ return {
512
+ pocketKey,
513
+ epochTotalDeposited: pocket.epochTotalDeposited,
514
+ estimatedSpent,
515
+ remainingBudget,
516
+ localSeq: pocket.localSeq,
517
+ };
518
+ }
407
519
  /**
408
520
  * Cryptographically verify a `t`-of-`n` witness-signed `"SMW1_FRESH"` checkpoint and
409
521
  * monotonically advance the pocket's local L1 anchor via `storage.updateAnchor` (`M-NEW-5`).
@@ -690,6 +802,15 @@ export class OfflineWallet {
690
802
  throw new Error(`DUPLICATE_ORDER_ID: orderId ${orderId} for recipient ${recipientStrKey} was already signed at seq=${priorOrder.seq} with different parameters (prior amount=${priorOrder.amount}, maxTip=${priorOrder.maxTip}; requested amount=${amount}, maxTip=${maxTip})`);
691
803
  }
692
804
  }
805
+ // Enforce running cumulative pocket budget STRICTLY BEFORE burning localSeq (`0.2.0`)
806
+ const currentEstimatedSpent = this.effectiveEstimatedSpent(params.pocketKey, pocket);
807
+ if (!params.skipSpentBudgetCheck &&
808
+ currentEstimatedSpent + totalWorstCaseCost > pocket.epochTotalDeposited) {
809
+ const remaining = pocket.epochTotalDeposited > currentEstimatedSpent
810
+ ? pocket.epochTotalDeposited - currentEstimatedSpent
811
+ : 0n;
812
+ throw new Error(`INSUFFICIENT_POCKET_BUDGET: intent cost (${totalWorstCaseCost}) plus already signed spend (${currentEstimatedSpent}) exceeds pocket epochTotalDeposited (${pocket.epochTotalDeposited}); remaining budget is ${remaining}`);
813
+ }
693
814
  // Validate all dual-clock policy parameters STRICTLY BEFORE burning localSeq (AUD-WAL-02)
694
815
  const safetyMarginSecs = assertNonNegativeSafeInt(params.safetyMarginSecs ?? DEFAULT_SAFETY_MARGIN_SECS, "safetyMarginSecs");
695
816
  if (safetyMarginSecs < DEFAULT_SAFETY_MARGIN_SECS) {
@@ -760,9 +881,11 @@ export class OfflineWallet {
760
881
  assertU32(expiryLedger, "expiryLedger");
761
882
  // -------------------------------------------------------------------------
762
883
  // BURN-BEFORE-DISPLAY (SPEC §4.2 P-06):
763
- // Atomically increment and persist `local_seq += 1` STRICTLY BEFORE signing!
884
+ // Atomically increment and persist `local_seq += 1` (and running `estimatedSpent`)
885
+ // STRICTLY BEFORE signing!
764
886
  // -------------------------------------------------------------------------
765
- const seq = await this.storage.burnNextSeq(params.pocketKey);
887
+ const seq = await this.storage.burnNextSeq(params.pocketKey, totalWorstCaseCost);
888
+ this.setFallbackEstimatedSpent(params.pocketKey, currentEstimatedSpent + totalWorstCaseCost);
766
889
  params.beforeSignHook?.(seq);
767
890
  const intentDigest = computeIntentDigest({
768
891
  networkId,
@@ -930,6 +1053,14 @@ export class OfflineWallet {
930
1053
  if (verifiedWitnessIndices.length < pocket.witnessThreshold) {
931
1054
  throw new Error(`latestCert verified only ${verifiedWitnessIndices.length} witness signatures, need >= ${pocket.witnessThreshold}`);
932
1055
  }
1056
+ // Monotonically advance running estimatedSpent from verified quorum cumulativeSpent
1057
+ const prevSpent = this.effectiveEstimatedSpent(pocketKey, pocket);
1058
+ if (cert.cumulativeSpent > prevSpent) {
1059
+ if (this.storage.syncEstimatedSpent) {
1060
+ await this.storage.syncEstimatedSpent(pocketKey, cert.cumulativeSpent);
1061
+ }
1062
+ this.setFallbackEstimatedSpent(pocketKey, cert.cumulativeSpent);
1063
+ }
933
1064
  const previousSeq = pocket.localSeq;
934
1065
  if (intent.seq <= previousSeq) {
935
1066
  return {
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Portable JSON WalletStorage serializer and persistent adapter (`@outpost-protocol/core`).
3
+ *
4
+ * Designed for mobile WebViews (Capacitor Preferences, Expo SecureStore, MMKV, SQLite),
5
+ * browser extensions (`chrome.storage.local` / IndexedDB), Electron, and Node.js.
6
+ *
7
+ * SECURITY NOTE: Serialized snapshots include each pocket's 32-byte `deviceSecretKey`.
8
+ * Always store the serialized JSON string in encrypted platform storage (iOS Keychain,
9
+ * Android Keystore, Expo SecureStore, or encrypted SQLite).
10
+ */
11
+ import { type DepositAnchor, type PocketRecord, type SignedOrderRecord, type WalletStorage } from "./wallet.js";
12
+ import { type NetworkHint } from "./xdr.js";
13
+ export declare const WALLET_STATE_SCHEMA_VERSION: 1;
14
+ export declare const MAX_SERIALIZED_POCKETS = 1024;
15
+ export declare const MAX_SERIALIZED_SIGNED_ORDERS = 2048;
16
+ export interface WalletStateSnapshot {
17
+ readonly pockets: Readonly<Record<string, PocketRecord>>;
18
+ /** Ordered oldest-to-newest to preserve bounded LRU recency across restarts. */
19
+ readonly signedOrders: readonly SignedOrderRecord[];
20
+ }
21
+ export interface SerializedWireAddressV1 {
22
+ readonly type: "account" | "contract";
23
+ readonly rawHex: string;
24
+ }
25
+ export type SerializedWireTokenV1 = {
26
+ readonly kind: "native_xlm";
27
+ } | {
28
+ readonly kind: "canonical_usdc";
29
+ } | {
30
+ readonly kind: "canonical_eurc";
31
+ } | {
32
+ readonly kind: "custom";
33
+ readonly contractIdHex: string;
34
+ };
35
+ export interface SerializedPocketRecordV1 {
36
+ readonly networkHint: NetworkHint;
37
+ readonly networkPassphrase?: string;
38
+ readonly factoryVer: number;
39
+ readonly factoryId: string;
40
+ readonly owner: SerializedWireAddressV1;
41
+ readonly vaultId: string;
42
+ readonly pocketId: number;
43
+ readonly epoch: number;
44
+ readonly token: SerializedWireTokenV1;
45
+ readonly tokenContractId: string;
46
+ readonly deviceSecretKeyHex: string;
47
+ readonly devicePubkeyHex: string;
48
+ readonly witnessesHex: readonly string[];
49
+ readonly witnessThreshold: number;
50
+ readonly epochTotalDeposited: string;
51
+ readonly exitDelaySecs: string;
52
+ readonly anchor: DepositAnchor;
53
+ readonly localSeq: number;
54
+ readonly estimatedSpent: string;
55
+ }
56
+ export interface SerializedSignedOrderRecordV1 {
57
+ readonly pocketKey: string;
58
+ readonly recipientStrKey: string;
59
+ readonly orderId: string;
60
+ readonly seq: number;
61
+ readonly tokenContractId: string;
62
+ readonly amount: string;
63
+ readonly maxTip: string;
64
+ readonly effectiveNowTs: number;
65
+ readonly intentDigestHex: string;
66
+ readonly encoded: string;
67
+ }
68
+ export interface SerializedWalletStateV1 {
69
+ readonly version: typeof WALLET_STATE_SCHEMA_VERSION;
70
+ readonly pockets: Readonly<Record<string, SerializedPocketRecordV1>>;
71
+ readonly signedOrders: readonly SerializedSignedOrderRecordV1[];
72
+ }
73
+ /**
74
+ * Serialize a `WalletStateSnapshot` (`pockets` + `signedOrders`) to canonical versioned JSON.
75
+ */
76
+ export declare function serializeWalletState(snapshot: WalletStateSnapshot): string;
77
+ /**
78
+ * Deserialize and strictly validate a versioned JSON wallet snapshot produced by
79
+ * `serializeWalletState`. Fails closed on unknown schema versions, invalid key lengths,
80
+ * corrupted keypairs, prototype-pollution keys, or cap violations.
81
+ */
82
+ export declare function deserializeWalletState(json: string): WalletStateSnapshot;
83
+ /**
84
+ * Minimal string persistence backend for `JsonWalletStorage`.
85
+ * Plug in Capacitor Preferences, Expo SecureStore, SQLite, MMKV, `localStorage`, or Node `fs`.
86
+ */
87
+ export interface JsonWalletStorageAdapter {
88
+ load(): Promise<string | null | undefined> | string | null | undefined;
89
+ save(serializedJson: string): Promise<void> | void;
90
+ }
91
+ export interface JsonWalletStorageOptions {
92
+ readonly adapter: JsonWalletStorageAdapter;
93
+ readonly maxSignedOrders?: number;
94
+ }
95
+ /**
96
+ * Durable `WalletStorage` backed by any string key-value persistence adapter (`JsonWalletStorageAdapter`).
97
+ *
98
+ * Guarantees:
99
+ * - Hydrates lazily on first read/write (or explicitly via `await storage.hydrate()`).
100
+ * - Serializes all mutations through a strict FIFO async mutex so concurrent writes never race.
101
+ * - Durably invokes `adapter.save(serialized)` BEFORE resolving `burnNextSeq` (preserving the
102
+ * burn-before-display invariant across crashes).
103
+ * - Rolls back in-memory state if `adapter.save(...)` throws (`AGENTS.md` §1.1).
104
+ */
105
+ export declare class JsonWalletStorage implements WalletStorage {
106
+ private readonly adapter;
107
+ private readonly maxSignedOrders;
108
+ private inner;
109
+ private hydrated;
110
+ private hydratePromise?;
111
+ private writeChain;
112
+ constructor(options: JsonWalletStorageOptions);
113
+ /**
114
+ * Explicitly hydrate from the underlying adapter (idempotent; also called automatically on first access).
115
+ */
116
+ hydrate(): Promise<void>;
117
+ private runSerializedMutation;
118
+ exportJson(): Promise<string>;
119
+ getPocket(pocketKey: string): Promise<PocketRecord | undefined>;
120
+ savePocket(pocketKey: string, record: PocketRecord): Promise<void>;
121
+ burnNextSeq(pocketKey: string, costDelta?: bigint): Promise<number>;
122
+ advanceSeq(pocketKey: string, newSeq: number): Promise<number>;
123
+ syncEstimatedSpent(pocketKey: string, cumulativeSpent: bigint): Promise<bigint>;
124
+ updateAnchor(pocketKey: string, anchor: DepositAnchor): Promise<void>;
125
+ listPocketKeys(): Promise<string[]>;
126
+ getSignedOrder(pocketKey: string, recipientStrKey: string, orderId: bigint): Promise<SignedOrderRecord | undefined>;
127
+ saveSignedOrder(record: SignedOrderRecord): Promise<void>;
128
+ }