@econ-v1/domain 7.6.172 → 7.6.174

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,4 +1,8 @@
1
1
  // @ts-check
2
+ /** @typedef {import('@econ-v1/ports').GiftWalletPort} GiftWalletPort */
3
+ /** @typedef {import('@econ-v1/ports').GiftWalletRedeemOutcome} GiftWalletRedeemOutcome */
4
+ /** @typedef {import('@econ-v1/ports').GiftWalletStatusOutcome} GiftWalletStatusOutcome */
5
+ /** @typedef {import('@econ-v1/ports').GiftWalletStep} GiftWalletStep */
2
6
  /** @typedef {import('@econ-v1/ports').OnboardingAccessCodeStore} OnboardingAccessCodeStore */
3
7
  /** @typedef {import('@econ-v1/ports').OnboardingPresencePhase} OnboardingPresencePhase */
4
8
  /** @typedef {import('@econ-v1/ports').OnboardingPresencePort} OnboardingPresencePort */
@@ -11,7 +15,7 @@
11
15
  /** @typedef {import("./wifi-provisioning-service.js").WifiStatusOutcome} WifiStatusOutcome */
12
16
  import { createNullOnboardingPresence } from "@econ-v1/ports";
13
17
  import { DomainError } from "../errors/index.js";
14
- /** @type {readonly ["join-qr", "open-browser", "choose-network", "network-password", "handoff", "way-back", "install", "match-code", "invitation", "identity", "trusted"]} */
18
+ /** @type {readonly ["join-qr", "open-browser", "choose-network", "network-password", "handoff", "way-back", "install", "match-code", "invitation", "identity", "gift", "trusted"]} */
15
19
  export const ONBOARDING_FLOW_STEP_IDS = [
16
20
  "join-qr",
17
21
  "open-browser",
@@ -23,6 +27,7 @@ export const ONBOARDING_FLOW_STEP_IDS = [
23
27
  "match-code",
24
28
  "invitation",
25
29
  "identity",
30
+ "gift",
26
31
  "trusted",
27
32
  ];
28
33
  /** @type {readonly OnboardingFlowStep[]} */
@@ -47,6 +52,11 @@ const STEP_TABLE = [
47
52
  phase: "identify",
48
53
  },
49
54
  { id: "identity", lcdScreenId: "onboard_working", phase: "identify" },
55
+ // Gated like `invitation`, but on a fact the flow only learns late: the row joins the active
56
+ // list once the node has answered that a gift wallet IS available for it (`#giftOffered`).
57
+ // Until then, and for every node with no gift, the pager counts exactly the steps it always
58
+ // counted; the total grows by one at the moment this step appears, and never shrinks back.
59
+ { gate: "gift", id: "gift", lcdScreenId: "onboard_working", phase: "ready" },
50
60
  { id: "trusted", lcdScreenId: "onboard_trusted", phase: "ready" },
51
61
  ];
52
62
  /** @type {OnboardingFlowStepId} */
@@ -63,6 +73,49 @@ const WIFI_SKIPPABLE_STEPS = new Set([
63
73
  const PROBE_RETRY_DEADLINE_MS = 500;
64
74
  const CONFIRMATION_WINDOW_MS = 5 * 60 * 1000;
65
75
  const HANDOFF_WINDOW_MS = 3 * 60 * 1000;
76
+ /** How long the flow waits for `wallet.gift.check` before it carries on with no gift. Short on
77
+ * purpose: this wait is spent on the identity step's "Setting up your node…" button, and a
78
+ * node with no gift source answers at once. */
79
+ const GIFT_CHECK_DEADLINE_MS = 8_000;
80
+ /** How long the flow waits for one `wallet.gift.redeem` call. The node's own budget for a call
81
+ * is 55 s; a call still unanswered past this counts as timed out (and is retried, see
82
+ * `#startGiftRedeem`). */
83
+ const GIFT_REDEEM_DEADLINE_MS = 60_000;
84
+ /** The most `wallet.gift.redeem` calls one visit to the gift step makes. A redeem resumes on the
85
+ * node, so a transient failure is followed at once by the next call. */
86
+ const GIFT_REDEEM_MAX_ATTEMPTS = 3;
87
+ /** The longest the gift step keeps the screen `arriving`, across every redeem call. */
88
+ const GIFT_STEP_BUDGET_MS = 150_000;
89
+ /** Codes a next redeem can get past: the node saved its progress, or never reached the LSP. Also
90
+ * this side's own `call_failed` (the call threw) and `timeout` (no answer in time). Any other
91
+ * failure — the gift is gone, not held, refused by this node — is final for this visit. */
92
+ const RESUMABLE_GIFT_ERRORS = new Set([
93
+ "budget_exhausted",
94
+ "timeout",
95
+ "unreachable",
96
+ "interrupted",
97
+ "upstream",
98
+ // The node's contract: after a hash mismatch the next redeem starts again from the claim.
99
+ "bundle_mismatch",
100
+ "call_failed",
101
+ ]);
102
+ /** The deadline of the one status read a reloaded gift step starts with. */
103
+ const GIFT_STATUS_DEADLINE_MS = 8_000;
104
+ /** Cadence of the `wallet.gift.status` poll that moves the three rows. Not a round second: the
105
+ * transport's loop detector reports twenty identical requests inside thirty seconds, which a
106
+ * one-second poll reaches on every ordinary redeem. */
107
+ const GIFT_POLL_INTERVAL_MS = 1_600;
108
+ /** The longest single wait a gift deadline is built from — see `#beforeDeadline`. */
109
+ const GIFT_DEADLINE_SLICE_MS = 1_000;
110
+ /** How long a reload may still resume the gift step: the time the LSP keeps a gift held for a
111
+ * node that asked for it. Past it the resume point is discarded like any stale checkpoint. */
112
+ const GIFT_RESUME_WINDOW_MS = 15 * 60 * 1000;
113
+ /** @type {readonly GiftWalletStep[]} */
114
+ const GIFT_STEP_ORDER = ["reserved", "moving", "spendable"];
115
+ /** Where the rows stand when the step appears: the node only reports a gift as available once
116
+ * the LSP holds it, so "Reserved for your node" is already true and the transfer is next. */
117
+ const GIFT_ENTRY_PROGRESS = 1;
118
+ const GIFT_RETRY_DETAIL = "Still trying · you can continue";
66
119
  /** @type {Readonly<Record<string, "confirm" | "reject">>} */
67
120
  /** @type {Readonly<Record<string, "confirm" | "reject">>} */
68
121
  const LCD_DECISION_COMPONENTS = {
@@ -72,6 +125,7 @@ const LCD_DECISION_COMPONENTS = {
72
125
  /** @type {Readonly<Record<string, string>>} */
73
126
  /** @type {Readonly<Record<string, string>>} */
74
127
  const LCD_WORKING_CAPTIONS = {
128
+ gift: "Adding your gift wallet",
75
129
  identity: "Naming your node",
76
130
  install: "Installing the app",
77
131
  invitation: "Setting up",
@@ -89,6 +143,10 @@ export class OnboardingFlowService {
89
143
  #checkpoints;
90
144
  /** @readonly @type {OnboardingFlowClaimPort} */
91
145
  #claim;
146
+ /** Absent = this composition has no gift wallet: the check is never made and the flow is the
147
+ * one that shipped before the step existed.
148
+ * @readonly @type {GiftWalletPort | undefined} */
149
+ #gift;
92
150
  /** @readonly @type {() => boolean} */
93
151
  #invitationRequired;
94
152
  /** @type {() => string | undefined} */
@@ -179,6 +237,41 @@ export class OnboardingFlowService {
179
237
  /** @default "" */
180
238
  #targetSsid = "";
181
239
  #reconnectGeneration = 0;
240
+ /** Bumped by everything that ends a gift conversation with the node: a new check, a new
241
+ * redeem, a resume, leaving the step (`#moveTo`), `start()` and `cancel()`. Every gift answer
242
+ * — the check, the redeem, each status poll, the resume read — compares the value it started
243
+ * under before it touches the flow, so one that lands late changes nothing.
244
+ * @default 0 */
245
+ #giftGeneration = 0;
246
+ /** True once the node answered that a gift wallet is available for it (or a checkpoint says
247
+ * this flow was already on the gift step). It is what puts `gift` in `#activeSteps()`.
248
+ * @default false */
249
+ #giftOffered = false;
250
+ /** The amount on the card. @default 0 */
251
+ #giftAmountSats = 0;
252
+ /** @type {OnboardingFlowGiftStatus} */
253
+ #giftStatus = "arriving";
254
+ /** Index into `GIFT_STEP_ORDER` of the row in progress; its length means every row is done.
255
+ * Only ever grows: a status poll that names an earlier step never moves a row backwards. */
256
+ #giftProgress = GIFT_ENTRY_PROGRESS;
257
+ /** Set only when the wallet was IMPORTED (redeem answered `ready` or `installed`). It is the
258
+ * last screen's `GIFT WALLET` row, so it must never be a promise.
259
+ * @type {number | undefined} */
260
+ #giftSats;
261
+ /** Whether the imported gift wallet already has a usable channel (redeem said `ready`), so the
262
+ * last screen never calls a wallet "ready to spend" that is still waiting for one.
263
+ * @default false */
264
+ #giftSpendable = false;
265
+ /** @type {string | undefined} */
266
+ #giftId;
267
+ /** @type {string | undefined} */
268
+ #giftWalletId;
269
+ /** Why the gift is not ready, as the node's machine code — only for the details disclosure.
270
+ * @type {string | undefined} */
271
+ #giftErrorCode;
272
+ /** ISO instant after which a reload no longer resumes the gift step.
273
+ * @type {string | undefined} */
274
+ #giftResumeDeadline;
182
275
  /** @default 0 */
183
276
  #wifiGeneration = 0;
184
277
  /** @type {string | undefined} */
@@ -190,6 +283,7 @@ export class OnboardingFlowService {
190
283
  this.#accessCodes = options.accessCodes;
191
284
  this.#checkpoints = options.checkpoints;
192
285
  this.#claim = options.claim;
286
+ this.#gift = options.gift;
193
287
  this.#invitationRequired = options.invitationRequired ?? (() => true);
194
288
  this.#defaultNodeName = options.defaultNodeName ?? (() => undefined);
195
289
  this.#invitationsEnabled = options.invitationsEnabled;
@@ -262,9 +356,25 @@ export class OnboardingFlowService {
262
356
  stepId,
263
357
  submitting: this.#submittingIdentity,
264
358
  };
359
+ case "gift": {
360
+ const nodeName = this.#nodeName ?? this.#defaultNodeName();
361
+ return {
362
+ ...base,
363
+ amountSats: this.#giftAmountSats,
364
+ // The node's reason is only worth showing once the screen says "not ready yet".
365
+ ...(this.#giftStatus !== "later" || this.#giftErrorCode === undefined ? {} : { giftErrorCode: this.#giftErrorCode }),
366
+ ...(this.#giftId === undefined ? {} : { giftId: this.#giftId }),
367
+ giftStatus: this.#giftStatus,
368
+ giftSteps: this.#giftRows(),
369
+ ...(nodeName === undefined ? {} : { nodeName }),
370
+ stepId,
371
+ ...(this.#giftWalletId === undefined ? {} : { walletId: this.#giftWalletId }),
372
+ };
373
+ }
265
374
  case "trusted":
266
375
  return {
267
376
  ...base,
377
+ ...(this.#giftSats === undefined ? {} : { giftSats: this.#giftSats, giftSpendable: this.#giftSpendable }),
268
378
  sessionEstablished: this.#sessionEstablished,
269
379
  ...(this.#nodeName === undefined ? {} : { nodeName: this.#nodeName }),
270
380
  stepId,
@@ -284,12 +394,24 @@ export class OnboardingFlowService {
284
394
  // See `#accessCodeMode`'s own doc comment for why this is the only place it is ever set.
285
395
  this.#accessCodeMode = this.#accessCodes.read() !== null;
286
396
  const checkpoint = this.#checkpoints.read();
397
+ // Before the restore below, for the same reason `#accessCodeMode` is: `gift` is an active
398
+ // step only while `#giftOffered` is set, and a checkpoint naming it is the one way a fresh
399
+ // instance can know a gift was on offer. A composition with no gift port never restores it.
400
+ this.#giftGeneration += 1;
401
+ this.#resetGift();
402
+ if (checkpoint?.stepId === "gift" && this.#gift !== undefined) {
403
+ this.#giftOffered = true;
404
+ this.#giftAmountSats = checkpoint.giftAmountSats ?? 0;
405
+ this.#giftResumeDeadline = checkpoint.deadline;
406
+ }
287
407
  const restored =
288
408
  checkpoint === undefined
289
409
  ? undefined
290
410
  : this.#asActiveStepId(checkpoint.stepId);
291
411
  this.#approvalState = "waiting";
292
- this.#deadline = checkpoint?.deadline;
412
+ // The gift step borrows the checkpoint's `deadline` slot for its own resume window; that
413
+ // instant says nothing about a claim confirmation and must not be read as one.
414
+ this.#deadline = this.#giftOffered ? undefined : checkpoint?.deadline;
293
415
  this.#digits = [];
294
416
  // Neither the invitation's name nor the session flag is checkpointed: both are facts about
295
417
  // an in-memory attempt, and a resumed flow must re-earn them rather than assert them.
@@ -363,6 +485,7 @@ export class OnboardingFlowService {
363
485
  if (this.#stepId === "way-back") {
364
486
  this.#watchWayBack();
365
487
  }
488
+ if (this.#stepId === "gift") void this.#resumeGift();
366
489
  }
367
490
  /**
368
491
  * @returns {Promise<void>}
@@ -379,6 +502,12 @@ export class OnboardingFlowService {
379
502
  case "install":
380
503
  if (this.#reasonCode === "claim-failed") void this.installDecision("continue-in-browser");
381
504
  return;
505
+ case "gift":
506
+ // While the wallet is still arriving there is nothing to continue to: the button is not
507
+ // even enabled, and a stray command must not cut the transfer's screen short.
508
+ if (this.#giftStatus === "arriving") return;
509
+ this.#moveTo("trusted");
510
+ return;
382
511
  default:
383
512
  // Every other step needs its own command. Silently ignoring a stray `advance` is
384
513
  // deliberate: reinterpreting it as a generic "next" would discard the step's real data.
@@ -680,6 +809,22 @@ export class OnboardingFlowService {
680
809
  this.#accessCodes.clear();
681
810
  this.#approvalState = "approved";
682
811
  this.#sessionEstablished = outcome === "claimed";
812
+ // A gift needs an owner AND this browser's device session: the three `wallet.gift.*` calls
813
+ // go through the authenticated client. `claimed-unpaired` has no session, so it never asks.
814
+ if (outcome === "claimed" && this.#gift !== undefined) {
815
+ const generation = ++this.#giftGeneration;
816
+ // Still "Setting up your node…": the check is part of the same wait, and a second submit
817
+ // while it runs must be refused exactly like one during the claim itself.
818
+ this.#submittingIdentity = true;
819
+ const offer = await this.#checkGift();
820
+ if (generation !== this.#giftGeneration) return;
821
+ this.#submittingIdentity = false;
822
+ if (this.#stepId !== "identity") return;
823
+ if (offer !== undefined) {
824
+ this.#enterGift(offer.amountSats, offer.giftId);
825
+ return;
826
+ }
827
+ }
683
828
  this.#moveTo("trusted");
684
829
  }
685
830
  /**
@@ -736,6 +881,8 @@ export class OnboardingFlowService {
736
881
  this.#submittingIdentity = false;
737
882
  this.#claimGeneration += 1;
738
883
  this.#claim.cancel();
884
+ this.#giftGeneration += 1;
885
+ this.#resetGift();
739
886
  this.#accessCodes.clear();
740
887
  this.#checkpoints.clear();
741
888
  this.#approvalState = "waiting";
@@ -789,6 +936,7 @@ export class OnboardingFlowService {
789
936
  const invitations = this.#invitationsEnabled();
790
937
  return STEP_TABLE.filter((row) => {
791
938
  if (row.gate === "invitations" && !invitations) return false;
939
+ if (row.gate === "gift" && !this.#giftOffered) return false;
792
940
  // Access-code mode never shows the match-code screen (design §4): the code itself was
793
941
  // this claim's physical-presence proof, so there is no code to display and nothing to
794
942
  // wait for. See `#accessCodeMode`'s doc comment for why this can never flip back.
@@ -1003,6 +1151,7 @@ export class OnboardingFlowService {
1003
1151
  case "install":
1004
1152
  case "invitation":
1005
1153
  case "identity":
1154
+ case "gift":
1006
1155
  return { caption: LCD_WORKING_CAPTIONS[this.#stepId] ?? "" };
1007
1156
  default:
1008
1157
  // Every other screen is either stateless or holds state only the NODE knows (its LAN
@@ -1017,6 +1166,9 @@ export class OnboardingFlowService {
1017
1166
  */
1018
1167
  #moveTo(stepId, reasonCode) {
1019
1168
  if (stepId !== this.#stepId) this.#stopInvitationPolling();
1169
+ // Leaving the gift step ends its conversation with the node, whoever asked to leave: the
1170
+ // redeem still in flight and the poll's next wake-up both find a newer generation.
1171
+ if (this.#stepId === "gift" && stepId !== "gift") this.#giftGeneration += 1;
1020
1172
  this.#stepId = stepId;
1021
1173
  this.#reasonCode = reasonCode;
1022
1174
  this.#writeCheckpoint();
@@ -1131,6 +1283,326 @@ export class OnboardingFlowService {
1131
1283
  this.#publish(this.#stepId);
1132
1284
  });
1133
1285
  }
1286
+ /**
1287
+ * Runs `call` and resolves with its answer, or with `undefined` once `deadlineMs` has passed
1288
+ * or the call threw.
1289
+ *
1290
+ * The deadline is built from short waits on the injected delay rather than one long one, so
1291
+ * nothing stays armed for longer than a slice after the answer is in — a single eight- or
1292
+ * sixty-second wait would still be pending long after the flow had left the step that
1293
+ * started it. Without an injected delay there is no clock to enforce a deadline with, and
1294
+ * the call is simply awaited.
1295
+ * @template T
1296
+ * @param {() => Promise<T>} call
1297
+ * @param {number} deadlineMs
1298
+ * @returns {Promise<T | undefined>}
1299
+ */
1300
+ async #beforeDeadline(call, deadlineMs) {
1301
+ /** @type {{ settled: boolean; value: T | undefined }} */
1302
+ const answer = { settled: false, value: undefined };
1303
+ const work = (async () => {
1304
+ try {
1305
+ answer.value = await call();
1306
+ } catch {
1307
+ answer.value = undefined;
1308
+ }
1309
+ answer.settled = true;
1310
+ })();
1311
+ const delay = this.#delay;
1312
+ if (delay === undefined) {
1313
+ await work;
1314
+ return answer.value;
1315
+ }
1316
+ const deadline = Date.parse(this.#now()) + deadlineMs;
1317
+ for (;;) {
1318
+ const remaining = deadline - Date.parse(this.#now());
1319
+ if (remaining <= 0) return undefined;
1320
+ await Promise.race([work, delay(Math.min(remaining, GIFT_DEADLINE_SLICE_MS))]);
1321
+ if (answer.settled) return answer.value;
1322
+ }
1323
+ }
1324
+ /**
1325
+ * Asks the node whether a gift wallet is available. Anything but a clear "available" — no
1326
+ * gift, a gift already imported, a failure, no answer in time — is `undefined`, and the flow
1327
+ * then goes on exactly as it did before the gift step existed.
1328
+ * @returns {Promise<{ readonly amountSats: number; readonly giftId: string } | undefined>}
1329
+ */
1330
+ async #checkGift() {
1331
+ const gift = this.#gift;
1332
+ if (gift === undefined) return undefined;
1333
+ const outcome = await this.#beforeDeadline(() => gift.check(), GIFT_CHECK_DEADLINE_MS);
1334
+ if (outcome === undefined || outcome.status !== "available") return undefined;
1335
+ return { amountSats: outcome.amountSats, giftId: outcome.giftId };
1336
+ }
1337
+ /**
1338
+ * @returns {void}
1339
+ */
1340
+ #resetGift() {
1341
+ this.#giftOffered = false;
1342
+ this.#giftAmountSats = 0;
1343
+ this.#giftStatus = "arriving";
1344
+ this.#giftProgress = GIFT_ENTRY_PROGRESS;
1345
+ this.#giftSats = undefined;
1346
+ this.#giftSpendable = false;
1347
+ this.#giftId = undefined;
1348
+ this.#giftWalletId = undefined;
1349
+ this.#giftErrorCode = undefined;
1350
+ this.#giftResumeDeadline = undefined;
1351
+ }
1352
+ /**
1353
+ * @param {number} amountSats
1354
+ * @param {string} giftId
1355
+ * @returns {void}
1356
+ */
1357
+ #enterGift(amountSats, giftId) {
1358
+ this.#resetGift();
1359
+ this.#giftOffered = true;
1360
+ this.#giftAmountSats = amountSats;
1361
+ this.#giftId = giftId;
1362
+ this.#giftResumeDeadline = new Date(
1363
+ Date.parse(this.#now()) + GIFT_RESUME_WINDOW_MS,
1364
+ ).toISOString();
1365
+ this.#moveTo("gift");
1366
+ this.#startGiftRedeem();
1367
+ }
1368
+ /**
1369
+ * The three rows, derived from where the transfer stands. `ready` is every row done; while
1370
+ * arriving the row in progress spins; once the screen has stopped promising (`later`) that
1371
+ * same row says it is still being tried, and the rows before it stay done.
1372
+ * @returns {readonly OnboardingFlowGiftStep[]}
1373
+ */
1374
+ #giftRows() {
1375
+ const progress = this.#giftStatus === "ready" ? GIFT_STEP_ORDER.length : this.#giftProgress;
1376
+ return GIFT_STEP_ORDER.map((id, index) => {
1377
+ if (index < progress) return { id, state: "done" };
1378
+ if (index > progress) return { id, state: "pending" };
1379
+ return this.#giftStatus === "later"
1380
+ ? { detail: GIFT_RETRY_DETAIL, id, state: "retrying" }
1381
+ : { id, state: "active" };
1382
+ });
1383
+ }
1384
+ /**
1385
+ * Starts `wallet.gift.redeem` and, beside it, the status poll that moves the rows.
1386
+ *
1387
+ * A redeem is resumable on the node: a slow LSP makes the first call answer `failed` with
1388
+ * `budget_exhausted` (or another transient code) with its progress saved, and the next call
1389
+ * carries on from there. So while the person is on the step, a transient failure — or a call
1390
+ * that threw or ran past its sixty seconds — starts the next redeem at once and the screen
1391
+ * stays `arriving`, its rows moved by the status poll. That stops after
1392
+ * `GIFT_REDEEM_MAX_ATTEMPTS` calls or `GIFT_STEP_BUDGET_MS` on the step, whichever comes
1393
+ * first; a failure that no retry can fix ends the wait at once. Either way the screen then
1394
+ * says `later` and the person continues.
1395
+ *
1396
+ * The poll is also the clock: each wake-up first checks the step's budget and the running
1397
+ * call's deadline, so a redeem that never answers still ends the wait. A status read is never
1398
+ * awaited inside the loop — one that hangs must not be able to hold a deadline back — and at
1399
+ * most one is in flight at a time.
1400
+ *
1401
+ * Nothing here outlives the step by more than one poll interval, and no retry is ever started
1402
+ * once the step is left: the loop and every redeem answer check that their generation is
1403
+ * current, the flow is on `gift` and the wallet is still arriving.
1404
+ * @returns {void}
1405
+ */
1406
+ #startGiftRedeem() {
1407
+ const gift = this.#gift;
1408
+ if (gift === undefined) return;
1409
+ const generation = ++this.#giftGeneration;
1410
+ const onStep = () => generation === this.#giftGeneration && this.#stepId === "gift";
1411
+ const arriving = () => onStep() && this.#giftStatus === "arriving";
1412
+ const delay = this.#delay;
1413
+ const stepDeadline = Date.parse(this.#now()) + GIFT_STEP_BUDGET_MS;
1414
+ let attempts = 0;
1415
+ /** The attempt whose failure may still decide what happens next; an older one's may not. */
1416
+ let current = 0;
1417
+ let callDeadline = Number.POSITIVE_INFINITY;
1418
+ /** @param {GiftWalletRedeemOutcome} outcome @returns {void} */
1419
+ const settleFailure = (outcome) => {
1420
+ if (outcome.status === "failed" && outcome.step !== undefined) {
1421
+ this.#giftProgress = Math.max(this.#giftProgress, GIFT_STEP_ORDER.indexOf(outcome.step));
1422
+ }
1423
+ const withinBudget = delay === undefined || Date.parse(this.#now()) < stepDeadline;
1424
+ if (isResumableGiftFailure(outcome) && attempts < GIFT_REDEEM_MAX_ATTEMPTS && withinBudget) {
1425
+ attempt();
1426
+ return;
1427
+ }
1428
+ this.#applyGiftRedeem(outcome);
1429
+ };
1430
+ const attempt = () => {
1431
+ attempts += 1;
1432
+ const mine = ++current;
1433
+ callDeadline = Math.min(Date.parse(this.#now()) + GIFT_REDEEM_DEADLINE_MS, stepDeadline);
1434
+ void (async () => {
1435
+ /** @type {GiftWalletRedeemOutcome} */
1436
+ let outcome;
1437
+ try {
1438
+ outcome = await gift.redeem();
1439
+ } catch {
1440
+ outcome = { errorCode: "call_failed", status: "failed" };
1441
+ }
1442
+ // Once the person has left the step, no answer is anybody's business — and no retry.
1443
+ if (!onStep()) return;
1444
+ // A wallet that is on the node is the truth about this gift whichever call says so, even
1445
+ // one that lands after the screen stopped waiting: the person is still looking at it.
1446
+ if (outcome.status === "ready" || outcome.status === "installed") {
1447
+ this.#applyGiftRedeem(outcome);
1448
+ return;
1449
+ }
1450
+ // A failure only counts from the call the flow is still waiting on.
1451
+ if (mine !== current || this.#giftStatus !== "arriving") return;
1452
+ settleFailure(outcome);
1453
+ })();
1454
+ };
1455
+ attempt();
1456
+ if (delay === undefined) return;
1457
+ void (async () => {
1458
+ let reading = false;
1459
+ for (;;) {
1460
+ const remaining = stepDeadline - Date.parse(this.#now());
1461
+ await delay(Math.max(0, Math.min(remaining, GIFT_POLL_INTERVAL_MS)));
1462
+ if (!arriving()) return;
1463
+ const now = Date.parse(this.#now());
1464
+ if (now >= stepDeadline) {
1465
+ current += 1;
1466
+ this.#giftErrorCode = "deadline";
1467
+ this.#giftStatus = "later";
1468
+ this.#publish(this.#stepId);
1469
+ return;
1470
+ }
1471
+ if (now >= callDeadline) {
1472
+ // The running call is past its own deadline: treat it as timed out. `settleFailure`
1473
+ // starts the next one (which moves `current` on) or ends the wait.
1474
+ current += 1;
1475
+ settleFailure({ errorCode: "timeout", status: "failed" });
1476
+ if (!arriving()) return;
1477
+ }
1478
+ if (reading) continue;
1479
+ reading = true;
1480
+ void gift.status().then((status) => {
1481
+ reading = false;
1482
+ if (arriving()) this.#applyGiftProgress(status);
1483
+ }, () => {
1484
+ reading = false;
1485
+ });
1486
+ }
1487
+ })();
1488
+ }
1489
+ /**
1490
+ * One status poll's worth of progress. Only a running redeem's step and the unambiguous good
1491
+ * news count: a poll that still reports the PREVIOUS attempt's `failed`, or the `available`
1492
+ * from before the redeem started, says nothing about the attempt in flight.
1493
+ * @param {GiftWalletStatusOutcome} status
1494
+ * @returns {void}
1495
+ */
1496
+ #applyGiftProgress(status) {
1497
+ if (status.status === "ready") {
1498
+ this.#applyGiftRedeem({
1499
+ amountSats: status.amountSats ?? this.#giftAmountSats,
1500
+ status: "ready",
1501
+ walletId: status.walletId ?? this.#giftWalletId ?? "",
1502
+ });
1503
+ return;
1504
+ }
1505
+ if (status.status !== "redeeming" && status.status !== "installed") return;
1506
+ const step = status.status === "installed" ? "spendable" : status.step;
1507
+ const progress = step === undefined ? -1 : GIFT_STEP_ORDER.indexOf(step);
1508
+ let changed = false;
1509
+ if (progress > this.#giftProgress) {
1510
+ this.#giftProgress = progress;
1511
+ changed = true;
1512
+ }
1513
+ if (status.giftId !== undefined && status.giftId !== this.#giftId) {
1514
+ this.#giftId = status.giftId;
1515
+ changed = true;
1516
+ }
1517
+ if (status.walletId !== undefined && status.walletId !== this.#giftWalletId) {
1518
+ this.#giftWalletId = status.walletId;
1519
+ changed = true;
1520
+ }
1521
+ if (changed) this.#publish(this.#stepId);
1522
+ }
1523
+ /**
1524
+ * The redeem's own answer — the only thing that may say the wallet is on this node.
1525
+ * @param {GiftWalletRedeemOutcome} outcome
1526
+ * @returns {void}
1527
+ */
1528
+ #applyGiftRedeem(outcome) {
1529
+ switch (outcome.status) {
1530
+ case "ready":
1531
+ this.#giftStatus = "ready";
1532
+ this.#giftProgress = GIFT_STEP_ORDER.length;
1533
+ this.#giftAmountSats = outcome.amountSats;
1534
+ this.#giftSats = outcome.amountSats;
1535
+ this.#giftSpendable = true;
1536
+ this.#giftErrorCode = undefined;
1537
+ if (outcome.walletId !== "") this.#giftWalletId = outcome.walletId;
1538
+ break;
1539
+ case "installed":
1540
+ // Imported, so the last screen may say so — but no channel is usable yet.
1541
+ this.#giftStatus = "later";
1542
+ this.#giftProgress = Math.max(this.#giftProgress, GIFT_STEP_ORDER.indexOf("spendable"));
1543
+ this.#giftAmountSats = outcome.amountSats;
1544
+ this.#giftSats = outcome.amountSats;
1545
+ this.#giftSpendable = false;
1546
+ this.#giftErrorCode = "not_spendable_yet";
1547
+ if (outcome.walletId !== "") this.#giftWalletId = outcome.walletId;
1548
+ break;
1549
+ case "failed":
1550
+ this.#giftStatus = "later";
1551
+ if (outcome.step !== undefined) {
1552
+ this.#giftProgress = Math.max(this.#giftProgress, GIFT_STEP_ORDER.indexOf(outcome.step));
1553
+ }
1554
+ this.#giftErrorCode = outcome.errorCode;
1555
+ break;
1556
+ default:
1557
+ // `none`: the node holds nothing for this redeem after all. The step never leaves on its
1558
+ // own — the person continues from the same "not ready yet" state as any other miss.
1559
+ this.#giftStatus = "later";
1560
+ this.#giftErrorCode = `not_held_${outcome.reason}`;
1561
+ }
1562
+ this.#publish(this.#stepId);
1563
+ }
1564
+ /**
1565
+ * A reload landed on the gift step. The node's persisted state decides what is shown: a
1566
+ * wallet that is already there renders as it is, anything else means the transfer is not
1567
+ * finished and `redeem` — which resumes — is called again.
1568
+ *
1569
+ * No answer at all is treated as "this checkpoint is not mine to resume": the calls are
1570
+ * authenticated, so a browser with no session (a node that was reset since, a stale slot)
1571
+ * gets none, and the flow then starts where a flow with no checkpoint starts instead of
1572
+ * showing a gift nobody can deliver.
1573
+ * @returns {Promise<void>}
1574
+ */
1575
+ async #resumeGift() {
1576
+ const gift = this.#gift;
1577
+ if (gift === undefined) return;
1578
+ const generation = ++this.#giftGeneration;
1579
+ const status = await this.#beforeDeadline(() => gift.status(), GIFT_STATUS_DEADLINE_MS);
1580
+ if (generation !== this.#giftGeneration || this.#stepId !== "gift") return;
1581
+ if (status === undefined || status.status === "unavailable") {
1582
+ this.#checkpoints.clear();
1583
+ this.start();
1584
+ return;
1585
+ }
1586
+ // An authenticated capability answered, so this browser does hold a device session — the
1587
+ // one fact about the claim a resumed flow can re-earn here rather than assert.
1588
+ this.#sessionEstablished = true;
1589
+ if (status.amountSats !== undefined) this.#giftAmountSats = status.amountSats;
1590
+ if (status.giftId !== undefined) this.#giftId = status.giftId;
1591
+ if (status.walletId !== undefined) this.#giftWalletId = status.walletId;
1592
+ if (status.status === "ready" || status.status === "installed") {
1593
+ this.#applyGiftRedeem({
1594
+ amountSats: this.#giftAmountSats,
1595
+ status: status.status,
1596
+ walletId: this.#giftWalletId ?? "",
1597
+ });
1598
+ return;
1599
+ }
1600
+ if (status.status === "redeeming" && status.step !== undefined) {
1601
+ this.#giftProgress = Math.max(this.#giftProgress, GIFT_STEP_ORDER.indexOf(status.step));
1602
+ }
1603
+ this.#publish(this.#stepId);
1604
+ this.#startGiftRedeem();
1605
+ }
1134
1606
  /**
1135
1607
  * @returns {void}
1136
1608
  */
@@ -1139,6 +1611,16 @@ export class OnboardingFlowService {
1139
1611
  this.#checkpoints.clear();
1140
1612
  return;
1141
1613
  }
1614
+ if (this.#stepId === "gift") {
1615
+ // Nothing of the claim is resumable from here — the owner exists — so the slot carries
1616
+ // only what the gift step needs: its own window and the amount on the card.
1617
+ this.#checkpoints.write({
1618
+ ...(this.#giftResumeDeadline === undefined ? {} : { deadline: this.#giftResumeDeadline }),
1619
+ giftAmountSats: this.#giftAmountSats,
1620
+ stepId: "gift",
1621
+ });
1622
+ return;
1623
+ }
1142
1624
  this.#checkpoints.write({
1143
1625
  stepId: this.#stepId,
1144
1626
  ...(this.#deadline === undefined ? {} : { deadline: this.#deadline }),
@@ -1165,6 +1647,14 @@ function invitationReasonCode(outcome) {
1165
1647
  return "invitation-unknown";
1166
1648
  }
1167
1649
 
1650
+ /**
1651
+ * Whether the next `wallet.gift.redeem` can get past this answer (see `RESUMABLE_GIFT_ERRORS`).
1652
+ * @param {GiftWalletRedeemOutcome} outcome
1653
+ * @returns {boolean}
1654
+ */
1655
+ function isResumableGiftFailure(outcome) {
1656
+ return outcome.status === "failed" && RESUMABLE_GIFT_ERRORS.has(outcome.errorCode);
1657
+ }
1168
1658
  /**
1169
1659
  * Maps a `prepareClaim()` rejection onto the access-code rail's two specific reason codes
1170
1660
  * (design §5.4), so `#prepareCode()` can surface "the code is bound to another device" or "that
@@ -1199,6 +1689,19 @@ function accessCodeReasonCode(error) {
1199
1689
  * | "onboard_rejected"} OnboardingFlowLcdScreenId
1200
1690
  */
1201
1691
  /** @typedef {"open" | "wep" | "wpa2" | "wpa3"} OnboardingFlowWifiSecurity */
1692
+ /**
1693
+ * What the gift step's screen says. `arriving` = the transfer is running. `ready` = the wallet
1694
+ * is on this node and spendable. `later` = this screen has stopped waiting (imported but not
1695
+ * spendable yet, a failed or unanswered redeem, the deadline): the person can continue.
1696
+ * @typedef {"arriving" | "ready" | "later"} OnboardingFlowGiftStatus
1697
+ */
1698
+ /**
1699
+ * One of the gift step's three rows.
1700
+ * @typedef {object} OnboardingFlowGiftStep
1701
+ * @property {GiftWalletStep} id
1702
+ * @property {"done" | "active" | "retrying" | "pending"} state
1703
+ * @property {string} [detail]
1704
+ */
1202
1705
  /**
1203
1706
  * @typedef {| "waiting"
1204
1707
  * | "approved"
@@ -1272,6 +1775,18 @@ function accessCodeReasonCode(error) {
1272
1775
  * readonly submitting: boolean;
1273
1776
  * }
1274
1777
  * | {
1778
+ * readonly amountSats: number;
1779
+ * readonly giftErrorCode?: string;
1780
+ * readonly giftId?: string;
1781
+ * readonly giftStatus: OnboardingFlowGiftStatus;
1782
+ * readonly giftSteps: readonly OnboardingFlowGiftStep[];
1783
+ * readonly nodeName?: string;
1784
+ * readonly stepId: "gift";
1785
+ * readonly walletId?: string;
1786
+ * }
1787
+ * | {
1788
+ * readonly giftSats?: number;
1789
+ * readonly giftSpendable?: boolean;
1275
1790
  * readonly nodeName?: string;
1276
1791
  * readonly sessionEstablished: boolean;
1277
1792
  * readonly stepId: "trusted";
@@ -1284,6 +1799,7 @@ function accessCodeReasonCode(error) {
1284
1799
  * readonly stepId: Exclude<
1285
1800
  * OnboardingFlowStepId,
1286
1801
  * | "choose-network"
1802
+ * | "gift"
1287
1803
  * | "handoff"
1288
1804
  * | "identity"
1289
1805
  * | "invitation"
@@ -1340,11 +1856,16 @@ function accessCodeReasonCode(error) {
1340
1856
  * @property {Pick<OnboardingCheckpointStore, "clear" | "read" | "write">} checkpoints
1341
1857
  * @property {OnboardingFlowClaimPort} claim
1342
1858
  * @property {() => string | undefined} [defaultNodeName]
1859
+ * @property {GiftWalletPort} [gift] The node's gift wallet (`wallet.gift.*`), reached through the AUTHENTICATED home-node client.
1860
+ * Asked only after a claim that left this browser with a device session. Absent = no gift is
1861
+ * ever offered and the flow is unchanged — the right wiring for a composition with no such
1862
+ * client (tests, headless).
1343
1863
  * @property {() => boolean} [invitationRequired]
1344
1864
  * @property {() => boolean} invitationsEnabled
1345
1865
  * @property {OnboardingFlowInvitePort} invites
1346
1866
  * @property {OnboardingFlowLcdPort} [lcd]
1347
- * @property {(ms: number) => Promise<void>} [delay] Waits between invitation progress polls; absent = no live progress.
1867
+ * @property {(ms: number) => Promise<void>} [delay] Waits between invitation progress polls, and paces the gift step's status poll and its
1868
+ * deadlines; absent = no live progress and no gift deadline.
1348
1869
  * @property {() => string} now
1349
1870
  * @property {OnboardingPresencePort} [presence]
1350
1871
  * @property {(stepId: OnboardingFlowStepId) => void} publish
@@ -1352,7 +1873,7 @@ function accessCodeReasonCode(error) {
1352
1873
  */
1353
1874
  /**
1354
1875
  * @typedef {object} OnboardingFlowStep
1355
- * @property {"invitations"} [gate]
1876
+ * @property {"invitations" | "gift"} [gate]
1356
1877
  * @property {OnboardingFlowStepId} id
1357
1878
  * @property {OnboardingFlowLcdScreenId} lcdScreenId
1358
1879
  * @property {OnboardingFlowPhase} phase