wallet-kit / test / types / consumer.ts
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
/**
 * TS smoke-compile of the exported API. Compiled by `npm run check`, never
 * executed. It is the tripwire for two things at once: `.d.ts` drift, and
 * :advanced rename breakage — every name below has to survive the Closure
 * compiler under the spelling written here.
 *
 * It walks the whole story banca and an embedding app will walk: quote, link,
 * pay, settle, fold, export.
 */

import {
  AMT_MAX,
  AMT_MIN,
  CTX_MAX,
  CUR_RE,
  CODE_RE,
  DECLINE_REASONS,
  DIGEST_RE,
  DOM_PAY_ISS,
  DOM_PAY_LOCK,
  DOM_PAY_REL,
  DOM_PAY_ORD,
  DOM_PAY_RCP,
  DOM_PAY_REQ,
  LEDGER_KEY_PREFIX,
  LedgerStore,
  MAX_ARTIFACT_BYTES,
  MAX_SETTLEMENT_BYTES,
  MAX_TTL_MS,
  MEMO_MAX,
  NEUTRAL_BANKER,
  NEUTRAL_CODE,
  NEUTRAL_UNIT,
  ORDER_ID_RE,
  ORDER_TTL_MS,
  PAY_BASE_URL,
  PAY_FRAGMENT_KEY,
  PUB_RE,
  REQ_TTL_MS,
  SIG_RE,
  SKEW_MS,
  bankerOf,
  buildOrder,
  buildPayRequest,
  buildIssuanceReceipt,
  buildLock,
  buildLockReceipt,
  buildRelease,
  buildSettlement,
  expired,
  isNeutralUnit,
  isPayableCurrency,
  issuanceKey,
  issuancePreimage,
  issuanceShape,
  hashlockMatches,
  lockId,
  lockPreimage,
  lockReceiptKey,
  lockReceiptPreimage,
  lockReceiptShape,
  lockShape,
  newHashlock,
  orderId,
  orderPreimage,
  orderShape,
  parseCurrency,
  parsePayFragment,
  payRequestPreimage,
  payRequestShape,
  payRequestUrl,
  receiptKey,
  sanitizeCtx,
  sanitizeMemo,
  settlementPreimage,
  settlementShape,
  unsignedIssuance,
  unsignedLock,
  unsignedLockReceipt,
  unsignedRelease,
  releasePreimage,
  releaseShape,
  unsignedOrder,
  unsignedPayRequest,
  unsignedSettlement,
  verifyIssuanceReceipt,
  verifyLock,
  verifyLockReceipt,
  verifyRelease,
  verifyOrder,
  verifyPayRequest,
  verifySettlement,
} from "ardegazu-wallet-kit";
import type {
  CurrencyBalance,
  Hashlock,
  IssuanceReceipt,
  LockOrder,
  LockReceipt,
  Release,
  Decline,
  DeclineReason,
  AdmissionClock,
  LedgerKind,
  LedgerWrite,
  PayOrder,
  PayRequest,
  Receipt,
  Settlement,
  SigningIdentity,
  StorageFailure,
  WalletArtifact,
} from "ardegazu-wallet-kit";
import { parsePayFragment as parseAlone, payRequestUrl as urlAlone } from "ardegazu-wallet-kit/paylink";
import { runWalletKitSelfTest } from "ardegazu-wallet-kit/selftest";

declare const payee: SigningIdentity;
declare const payer: SigningIdentity;
declare const bank: SigningIdentity;

// the constants are values with the types they claim
const consts: [string, string, string, string, string, string, number, number, number, number, number, number, number, number, number, number, number, string, string, string, string, string, string] = [
  DOM_PAY_REQ, DOM_PAY_ORD, DOM_PAY_RCP, DOM_PAY_ISS, DOM_PAY_LOCK, DOM_PAY_REL,
  AMT_MIN, AMT_MAX, CTX_MAX, MEMO_MAX, SKEW_MS, REQ_TTL_MS, ORDER_TTL_MS,
  MAX_TTL_MS, MAX_ARTIFACT_BYTES, MAX_SETTLEMENT_BYTES, DECLINE_REASONS.length,
  NEUTRAL_BANKER, NEUTRAL_CODE, NEUTRAL_UNIT, LEDGER_KEY_PREFIX, PAY_BASE_URL, PAY_FRAGMENT_KEY,
];
const shapes: RegExp[] = [PUB_RE, SIG_RE, ORDER_ID_RE, DIGEST_RE, CODE_RE, CUR_RE];

async function quote(cur: string): Promise<string> {
  const parsed = parseCurrency(cur);
  if (parsed === null || !isPayableCurrency(cur) || isNeutralUnit(cur)) throw new Error("bad currency");
  const banker: string | null = bankerOf(cur);

  const req: PayRequest = await buildPayRequest(payee, {
    cur,
    amt: 250,
    tox: parsed.banker,
    ctx: sanitizeCtx("stake:demo"),
    memo: sanitizeMemo("cafea"),
    expMs: Date.now() + REQ_TTL_MS,
  });
  const preimage: string = payRequestPreimage(req);
  const unsigned: object = unsignedPayRequest(req);
  const shaped: PayRequest | null = payRequestShape(req);
  const shapedFree: PayRequest | null = payRequestShape(req, null);
  void [banker, preimage, unsigned, shaped, shapedFree, consts, shapes];
  return payRequestUrl(req);
}

async function pay(url: string, store: LedgerStore): Promise<PayOrder> {
  const req: PayRequest | null = await parsePayFragment(url);
  if (req === null) throw new Error("bad link");
  if (expired(req)) throw new Error("stale quote");

  const po: PayOrder = await buildOrder(payer, {
    cur: req.cur,
    amt: req.amt,
    to: req.to,
    seq: await store.reserveSeq(req.cur), // allocate, never nextSeq, before signing
    ctx: req.ctx,
    ttlMs: ORDER_TTL_MS,
  });
  const checked: PayOrder | null = await verifyOrder(po);
  if (checked === null) throw new Error("unreachable");
  const recorded: LedgerWrite = await store.addOrder(checked);
  if (recorded === 0) throw new Error("the ledger refused the order");
  return checked;
}

async function settle(po: PayOrder, bankPub: string): Promise<Settlement> {
  const rc: Settlement = await buildSettlement(bank, po, { seq: "log-1" });
  const rj: Settlement = await buildSettlement(bank, po, { decline: "insufficient" });
  const why: DeclineReason = DECLINE_REASONS[0]!;
  void [rj, why, settlementPreimage(rc), unsignedSettlement(rc), settlementShape(rc), orderPreimage(po), unsignedOrder(po), orderShape(po)];

  const v: Settlement | null = await verifySettlement(rc, bankPub);
  if (v === null) throw new Error("bad settlement");
  if (v.t === "wrc") {
    const receipt: Receipt = v; // narrowing on `t` must work
    void receipt.seq.length;
  } else {
    const decline: Decline = v;
    void decline.why;
  }
  return v;
}

async function fold(idPub: string, rc: Settlement, rj: Settlement): Promise<void> {
  const store = new LedgerStore(idPub);
  store.onChange = () => {};
  store.onStorageError = (e: StorageFailure) => void e.name;
  const err: StorageFailure | null = store.storageError;
  const unread: string | null = store.unreadable;
  const acked: boolean = store.acknowledgeUnreadable();

  const applied: LedgerWrite = await store.applyReceipt(rc);
  const declined: LedgerWrite = await store.applyDecline(rj);
  // falsiness still means "was it recorded"; 0 is the only falsy outcome
  if (applied) void applied;
  if (declined === 2) void store.storageError?.name; // recorded, not durable
  const bal: Record<string, CurrencyBalance> = store.balances(Date.now());
  const one: CurrencyBalance | undefined = bal[rc.po.cur];
  void one?.available;
  if (one !== undefined && !one.exact) {
    const exact: bigint = one.settledExact - one.heldExact;
    void [exact, one.availableExact];
  }

  const pending: PayOrder[] = store.pendingOrders();
  const stale: PayOrder[] = store.expiredOrders(Date.now());
  const advisory: number = store.nextSeq(rc.po.cur);
  const receipts: Receipt[] = store.receipts();
  const declines: Decline[] = store.declines();
  const oid: string = await orderId(rc.po);
  const rk: string = await receiptKey(rc);

  store.load();
  const dropped: number = store.prune((_a: PayOrder | Settlement | IssuanceReceipt, kind: LedgerKind) => kind !== "wrj");
  const added: number = await store.importJson(store.exportJson());
  store.close();
  void [applied, declined, err, unread, acked, pending, stale, advisory, receipts, declines, oid, rk, dropped, added];
}

async function mint(cur: string, store: LedgerStore, bankPub: string): Promise<void> {
  const wri: IssuanceReceipt = await buildIssuanceReceipt(bank, {
    cur,
    seq: 1, // the BANK's issuance slot number
    to: store.idPub,
    amt: 100,
    h: "bafyreib-some-log-entry-hash",
    ts: Date.now(),
  });
  const pre: string = issuancePreimage(wri);
  const uns: object = unsignedIssuance(wri);
  const shaped: IssuanceReceipt | null = issuanceShape(wri);
  const shapedFree: IssuanceReceipt | null = issuanceShape(wri, null);
  const v: IssuanceReceipt | null = await verifyIssuanceReceipt(wri, bankPub);
  const vFree: IssuanceReceipt | null = await verifyIssuanceReceipt(wri, null, null);
  if (v === null) throw new Error("bad issuance");
  const k: string = await issuanceKey(v);
  const recorded: LedgerWrite = await store.applyIssuance(v); // credits only when v.to is me
  const held: IssuanceReceipt[] = store.issuances();
  const anyArtifact: WalletArtifact = v;
  void [pre, uns, shaped, shapedFree, vFree, k, recorded, held, anyArtifact];
}

/**
 * What a REPLICATED FOLD calls: no wall clock reaches any verdict, so two
 * replicas with skewed clocks cannot disagree about one log entry. This is the
 * shape banca's bank ledger uses in place of a transcribed copy of these rules.
 */
async function replicatedFold(entries: unknown[]): Promise<PayOrder[]> {
  const noClock: AdmissionClock = null;
  const kept: PayOrder[] = [];
  for (const e of entries) {
    const shaped: PayOrder | null = orderShape(e, noClock);
    const verified: PayOrder | null = await verifyOrder(e, noClock);
    const asSettlement: Settlement | null = await verifySettlement(e, null, noClock);
    void [shaped, asSettlement, settlementShape(e, noClock)];
    if (verified !== null) kept.push(verified);
  }
  return kept;
}

/**
 * The escrow story, end to end: one side of an atomic cross-bank trade.
 *
 * The maker holds the secret and locks FIRST — reversed, the secret-holder
 * could claim the other leg while never having locked anything of their own,
 * and the construction does not hold. `seq` is drawn from the SAME per-payer
 * space a payment order draws from, not a second one.
 */
async function escrowLeg(cur: string, counterparty: string, slot: number): Promise<void> {
  const hl: Hashlock = await newHashlock();
  const opened: boolean = await hashlockMatches(hl.pre, hl.hash);
  void opened;

  const lk: LockOrder = await buildLock(payer, {
    cur,
    amt: 100,
    to: counterparty,
    seq: slot,
    hash: hl.hash,
    ctx: sanitizeCtx("match:demo"),
    memo: sanitizeMemo("leg"),
    ttlMs: ORDER_TTL_MS,
  });
  const lkPre: string = lockPreimage(lk);
  const lkUnsigned: object = unsignedLock(lk);
  const lkShaped: LockOrder | null = lockShape(lk, null);
  const lkVerified: LockOrder | null = await verifyLock(lk, null);
  const lkid: string = await lockId(lk);
  void [lkPre, lkUnsigned, lkShaped, lkVerified, lkid];

  // the bank co-signs the CLAIM — `seq` is its log ref for the claim, a string,
  // not the lock's numeric slot
  const wlr: LockReceipt = await buildLockReceipt(bank, lk, { seq: "L-77" });
  const wlrPre: string = lockReceiptPreimage(wlr);
  const wlrUnsigned: object = unsignedLockReceipt(wlr);
  const wlrShaped: LockReceipt | null = lockReceiptShape(wlr, null);
  const wlrVerified: LockReceipt | null = await verifyLockReceipt(wlr, wlr.bank, null);
  const wlrKey: string = await lockReceiptKey(wlr);
  const embedded: LockOrder = wlr.lk;
  void [wlrPre, wlrUnsigned, wlrShaped, wlrVerified, wlrKey, embedded];

  // the other ending: the beneficiary hands it back, no bank required
  const rel: Release = await buildRelease(payee, { cur, lh: "zdpuLockEntryHash", ts: Date.now() });
  const relPre: string = releasePreimage(rel);
  const relUnsigned: object = unsignedRelease(rel);
  const relShaped: Release | null = releaseShape(rel, null);
  // expectedTo is REQUIRED in practice: this kit never sees the lock, so a
  // release that verifies proves only that somebody signed away some lock
  const relVerified: Release | null = await verifyRelease(rel, rel.to, null);
  void [relPre, relUnsigned, relShaped, relVerified];

  const anyEscrow: WalletArtifact = lk;
  void anyEscrow;
}

async function everything(): Promise<void> {
  const url = await quote(`${"A".repeat(42)}A.LEI`);
  void urlAlone;
  const req: PayRequest | null = await parseAlone(url);
  const junk: PayRequest | null = await verifyPayRequest(req);
  const store = new LedgerStore("me");
  const po = await pay(url, store);
  const rc = await settle(po, "bank");
  await fold("me", rc, rc);
  await mint(req!.cur, store, "bank");
  const anything: WalletArtifact = po;
  void [junk, anything];
  void (await replicatedFold([po, rc]));
  await escrowLeg(req!.cur, "peer", 9);
  await runWalletKitSelfTest();
}

void everything;

static mirror of HEAD · about · clone: git clone https://git.ardegazu.ro/wallet-kit.git