@kasufinance/kasu-sdk 2.6.0 → 2.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.
Files changed (122) hide show
  1. package/README.md +128 -3
  2. package/dist/bundle.cjs.js +1119 -254
  3. package/dist/bundle.esm.js +1109 -255
  4. package/dist/domain/index.d.ts +3 -2
  5. package/dist/domain/index.js +2 -2
  6. package/dist/domain/index.js.map +1 -1
  7. package/dist/domain/requests.d.ts +42 -4
  8. package/dist/domain/requests.js +20 -4
  9. package/dist/domain/requests.js.map +1 -1
  10. package/dist/domain/wallet-errors.d.ts +63 -8
  11. package/dist/domain/wallet-errors.js +115 -16
  12. package/dist/domain/wallet-errors.js.map +1 -1
  13. package/dist/facade/deposits.js +2 -1
  14. package/dist/facade/deposits.js.map +1 -1
  15. package/dist/facade/flows.d.ts +95 -0
  16. package/dist/facade/flows.js +116 -0
  17. package/dist/facade/flows.js.map +1 -0
  18. package/dist/facade/index.d.ts +3 -0
  19. package/dist/facade/index.js +3 -0
  20. package/dist/facade/index.js.map +1 -1
  21. package/dist/facade/kasu.d.ts +6 -2
  22. package/dist/facade/kasu.js +28 -3
  23. package/dist/facade/kasu.js.map +1 -1
  24. package/dist/facade/read-only.d.ts +12 -0
  25. package/dist/facade/read-only.js +13 -0
  26. package/dist/facade/read-only.js.map +1 -0
  27. package/dist/flows/deposit-flow.d.ts +301 -0
  28. package/dist/flows/deposit-flow.js +358 -0
  29. package/dist/flows/deposit-flow.js.map +1 -0
  30. package/dist/flows/flow.d.ts +72 -0
  31. package/dist/flows/flow.js +110 -0
  32. package/dist/flows/flow.js.map +1 -0
  33. package/dist/flows/index.d.ts +19 -0
  34. package/dist/flows/index.js +17 -0
  35. package/dist/flows/index.js.map +1 -0
  36. package/dist/flows/observable.d.ts +59 -0
  37. package/dist/flows/observable.js +81 -0
  38. package/dist/flows/observable.js.map +1 -0
  39. package/dist/flows/withdraw-flow.d.ts +99 -0
  40. package/dist/flows/withdraw-flow.js +83 -0
  41. package/dist/flows/withdraw-flow.js.map +1 -0
  42. package/dist/index.d.ts +1 -0
  43. package/dist/index.js +6 -0
  44. package/dist/index.js.map +1 -1
  45. package/dist/services/DataService/data-service.js +0 -1
  46. package/dist/services/DataService/data-service.js.map +1 -1
  47. package/package.json +8 -2
  48. package/src/domain/index.ts +7 -1
  49. package/src/domain/requests.ts +57 -4
  50. package/src/domain/wallet-errors.ts +135 -18
  51. package/src/facade/deposits.ts +2 -3
  52. package/src/facade/flows.ts +172 -0
  53. package/src/facade/index.ts +8 -0
  54. package/src/facade/kasu.ts +43 -3
  55. package/src/facade/read-only.ts +13 -0
  56. package/src/flows/deposit-flow.ts +775 -0
  57. package/src/flows/flow.ts +108 -0
  58. package/src/flows/index.ts +45 -0
  59. package/src/flows/observable.ts +97 -0
  60. package/src/flows/withdraw-flow.ts +210 -0
  61. package/src/index.ts +7 -0
  62. package/src/services/DataService/data-service.ts +0 -1
  63. package/dist/domain/au-minimum.test.d.ts +0 -1
  64. package/dist/domain/au-minimum.test.js +0 -202
  65. package/dist/domain/au-minimum.test.js.map +0 -1
  66. package/dist/domain/deposit-bounds.test.d.ts +0 -1
  67. package/dist/domain/deposit-bounds.test.js +0 -135
  68. package/dist/domain/deposit-bounds.test.js.map +0 -1
  69. package/dist/domain/loan-contract.test.d.ts +0 -1
  70. package/dist/domain/loan-contract.test.js +0 -255
  71. package/dist/domain/loan-contract.test.js.map +0 -1
  72. package/dist/domain/partners.test.d.ts +0 -1
  73. package/dist/domain/partners.test.js +0 -53
  74. package/dist/domain/partners.test.js.map +0 -1
  75. package/dist/domain/pools.test.d.ts +0 -1
  76. package/dist/domain/pools.test.js +0 -184
  77. package/dist/domain/pools.test.js.map +0 -1
  78. package/dist/domain/rates.test.d.ts +0 -1
  79. package/dist/domain/rates.test.js +0 -181
  80. package/dist/domain/rates.test.js.map +0 -1
  81. package/dist/domain/requests.test.d.ts +0 -1
  82. package/dist/domain/requests.test.js +0 -470
  83. package/dist/domain/requests.test.js.map +0 -1
  84. package/dist/domain/settlement.test.d.ts +0 -1
  85. package/dist/domain/settlement.test.js +0 -152
  86. package/dist/domain/settlement.test.js.map +0 -1
  87. package/dist/domain/tranche-display-name.test.d.ts +0 -1
  88. package/dist/domain/tranche-display-name.test.js +0 -58
  89. package/dist/domain/tranche-display-name.test.js.map +0 -1
  90. package/dist/domain/tranches.test.d.ts +0 -1
  91. package/dist/domain/tranches.test.js +0 -206
  92. package/dist/domain/tranches.test.js.map +0 -1
  93. package/dist/domain/wallet-errors.test.d.ts +0 -1
  94. package/dist/domain/wallet-errors.test.js +0 -71
  95. package/dist/domain/wallet-errors.test.js.map +0 -1
  96. package/dist/facade/config.test.d.ts +0 -1
  97. package/dist/facade/config.test.js +0 -216
  98. package/dist/facade/config.test.js.map +0 -1
  99. package/dist/facade/facade.test.d.ts +0 -1
  100. package/dist/facade/facade.test.js +0 -278
  101. package/dist/facade/facade.test.js.map +0 -1
  102. package/dist/services/Locking/calculate-apy.test.d.ts +0 -1
  103. package/dist/services/Locking/calculate-apy.test.js +0 -41
  104. package/dist/services/Locking/calculate-apy.test.js.map +0 -1
  105. package/dist/tests/sample.test.d.ts +0 -1
  106. package/dist/tests/sample.test.js +0 -59
  107. package/dist/tests/sample.test.js.map +0 -1
  108. package/src/domain/au-minimum.test.ts +0 -371
  109. package/src/domain/deposit-bounds.test.ts +0 -200
  110. package/src/domain/loan-contract.test.ts +0 -343
  111. package/src/domain/partners.test.ts +0 -83
  112. package/src/domain/pools.test.ts +0 -260
  113. package/src/domain/rates.test.ts +0 -254
  114. package/src/domain/requests.test.ts +0 -653
  115. package/src/domain/settlement.test.ts +0 -198
  116. package/src/domain/tranche-display-name.test.ts +0 -96
  117. package/src/domain/tranches.test.ts +0 -300
  118. package/src/domain/wallet-errors.test.ts +0 -100
  119. package/src/facade/config.test.ts +0 -265
  120. package/src/facade/facade.test.ts +0 -374
  121. package/src/services/Locking/calculate-apy.test.ts +0 -52
  122. package/src/tests/sample.test.ts +0 -63
@@ -0,0 +1,775 @@
1
+ import { BigNumber } from 'ethers';
2
+
3
+ import {
4
+ asContractType,
5
+ buildLegacyContractRequestMessage,
6
+ buildLoanAgreementSignMessage,
7
+ encodeDepositData,
8
+ GenerateContractResponse,
9
+ } from '../domain/loan-contract';
10
+ import {
11
+ classifyWalletFailure,
12
+ isUnpredictableGas,
13
+ } from '../domain/wallet-errors';
14
+ import { DepositParams, KycParams } from '../facade/types';
15
+
16
+ import { Flow } from './flow';
17
+ import { WaitableTransaction } from './observable';
18
+
19
+ /**
20
+ * The KYC-gated deposit pipeline, headless.
21
+ *
22
+ * This is the state machine kasu-ui and kasu-mobile each hand-wrote and then
23
+ * had to keep in step by hand: sign an auth message, generate the loan
24
+ * agreement, park while the lender reads it, sign it, approve the EXACT amount,
25
+ * fetch the KYC signature, submit, wait. Two implementations of one money path
26
+ * is one too many, so it lives here once and each application drives it from
27
+ * its own UI.
28
+ *
29
+ * **No React, no copy, no I/O of its own.** Every side effect is an injected
30
+ * port and every observable state is a code — `{ step: 'approve', reason:
31
+ * 'cancelled' }`, never "USDC approval was cancelled in your wallet". The
32
+ * applications keep their own `DEPOSIT_STEP_ERRORS` tables and map the codes to
33
+ * their words, in their design system and their language. Nothing in this file
34
+ * may be shown to a lender.
35
+ *
36
+ * ## Order, and why each step is where it is
37
+ *
38
+ * 1. **Allowance pre-check** — before anything is signed, because it decides
39
+ * `approvalRequired`, which decides `stepTotal`. A badge that said "3 of 4"
40
+ * and then silently became "3 of 3" would be describing a pipeline the
41
+ * lender is not in. A failed read assumes an approve IS needed: the safe
42
+ * default is a redundant approval, never a reverted deposit.
43
+ * 2. **`generating-sign`** — the lender signs the auth message
44
+ * (`buildLoanAgreementSignMessage`, or the legacy builder). kasu-backend
45
+ * reconstructs that string byte-for-byte to verify the signature.
46
+ * 3. **`generating-fetch`** — the agreements service returns the contract.
47
+ * 4. **`awaiting-accept`** — the run PARKS on a promise the consumer settles
48
+ * with `acceptContract()` or `declineContract()`. This is the only point at
49
+ * which a lender is committing to anything.
50
+ * 5. **`accepting-sign`** — the acceptance signature, which becomes the
51
+ * on-chain `depositData` via `encodeDepositData`.
52
+ * 6. **The 5-minute TTL guard** — checked AFTER the accept, because that is
53
+ * where the idling happens. An expired agreement is refused here rather than
54
+ * broadcast as a transaction that cannot succeed.
55
+ * 7. **`approve`** — the EXACT amount, never `MaxUint256`. House rule, and it
56
+ * is why the allowance drops to zero after every deposit and why step 1
57
+ * reads it fresh rather than trusting a cache.
58
+ * 8. **`request-sign` / `request-confirm`** — KYC signature, then the deposit,
59
+ * then the receipt.
60
+ *
61
+ * ## Failure codes
62
+ *
63
+ * A wallet rejection (`isUserRejected`) is `'cancelled'` — the lender changed
64
+ * their mind, and telling them something broke would be a lie. Only a WALLET
65
+ * call is ever classified that way: the HTTP ports are always `'failed'`,
66
+ * because a backend that words a refusal "declined" did not involve the
67
+ * lender's wallet. A reverted gas estimate on the request step
68
+ * (`isUnpredictableGas`) is `'insufficient-balance'` — nothing was refused, the
69
+ * transaction simply cannot succeed as composed. Everything else is `'failed'`
70
+ * and carries the original error for the consumer's crash reporter.
71
+ *
72
+ * ```ts
73
+ * const flow = new DepositFlow(ports);
74
+ * const stop = flow.subscribe((s) => render(s));
75
+ * await flow.start({ poolId, trancheId, amount, userAddress, ... });
76
+ * // …the consumer shows `flow.state.contract` and calls:
77
+ * await flow.acceptContract();
78
+ * ```
79
+ */
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // Codes
83
+ // ---------------------------------------------------------------------------
84
+
85
+ /**
86
+ * Where the run is. `success`, `declined` and `error` are terminal; everything
87
+ * else is in flight.
88
+ */
89
+ export type DepositPhase =
90
+ | 'idle'
91
+ | 'generating-sign'
92
+ | 'generating-fetch'
93
+ | 'awaiting-accept'
94
+ | 'accepting-sign'
95
+ | 'approve'
96
+ | 'request-sign'
97
+ | 'request-confirm'
98
+ | 'success'
99
+ | 'declined'
100
+ | 'error';
101
+
102
+ /**
103
+ * The four steps a lender sees as a badge. `approve` drops out of the sequence
104
+ * when the allowance already covers the deposit, which is why `stepIndex` and
105
+ * `stepTotal` are published rather than derived by each consumer.
106
+ */
107
+ export type DepositStep = 'generate' | 'confirm' | 'approve' | 'request';
108
+
109
+ /**
110
+ * Why a run did not reach `success`, as a code plus the step it happened on.
111
+ *
112
+ * The consumer maps this to its own words. `error` carries the underlying
113
+ * throw for a crash reporter — a `cancelled` and a `contract-expired` do not,
114
+ * because neither is a fault worth reporting.
115
+ */
116
+ export type DepositFailure =
117
+ | { step: DepositStep; reason: 'cancelled' }
118
+ | { step: DepositStep; reason: 'failed'; error: unknown }
119
+ | { step: 'request'; reason: 'insufficient-balance'; error: unknown }
120
+ | { step: 'request'; reason: 'contract-expired' };
121
+
122
+ // ---------------------------------------------------------------------------
123
+ // Ports
124
+ // ---------------------------------------------------------------------------
125
+
126
+ export type { WaitableTransaction };
127
+
128
+ /** What the KYC signing service hands back. */
129
+ export interface KycSignature {
130
+ signature: string;
131
+ blockExpiration: number | string;
132
+ }
133
+
134
+ /**
135
+ * The `/contract/generate` body, assembled by the flow and posted by the
136
+ * consumer's own port — through its server-side proxy (kasu-ui) or straight to
137
+ * the agreements service (kasu-mobile). The SDK never makes the call itself and
138
+ * never learns the URL or the key.
139
+ */
140
+ export interface GenerateContractRequest {
141
+ /**
142
+ * The lender's address, LOWERCASED. The legacy message embeds this casing
143
+ * and kasu-backend rebuilds the string from the body, so the two must
144
+ * agree.
145
+ */
146
+ address: string;
147
+ /** Signature over `signedMessage`. */
148
+ signature: string;
149
+ /** ms-epoch. The same value `signedMessage` states — do not re-clock it. */
150
+ timestamp: number;
151
+ /**
152
+ * The exact text that was signed. Sent so a consumer can log or assert on
153
+ * it; the backend rebuilds it from the other fields rather than trusting
154
+ * this one.
155
+ */
156
+ signedMessage: string;
157
+ poolId: string;
158
+ trancheId: string;
159
+ /** `'0'` for a variable-rate deposit. */
160
+ fixedTermConfigId: string;
161
+ /**
162
+ * The deposit in DISPLAY units, forwarded verbatim from
163
+ * `DepositFlowInput.depositAmount`. kasu-backend cross-checks it against
164
+ * the leading number of `amountLabel`.
165
+ */
166
+ depositAmount?: number;
167
+ /** The four human-readable fields, present only on the new format. */
168
+ strategyName?: string;
169
+ region?: string;
170
+ optionName?: string;
171
+ amountLabel?: string;
172
+ }
173
+
174
+ /**
175
+ * The human-readable `/contract/generate` format (BD deck slide 19): the lender
176
+ * signs a statement naming the strategy, region, option and amount.
177
+ *
178
+ * `amountLabel` must be derived from the same value as `depositAmount` — the
179
+ * backend refuses a message that states an amount other than the one being
180
+ * executed. The SDK does not format it, because formatting is the
181
+ * application's (and its locale's) business.
182
+ */
183
+ export interface LoanAgreementRequest {
184
+ format: 'loan-agreement';
185
+ strategyName: string;
186
+ region: string;
187
+ optionName: string;
188
+ amountLabel: string;
189
+ }
190
+
191
+ /**
192
+ * The legacy `I request contract content for {address} at {timestamp}.`
193
+ * format, which kasu-backend still accepts and `/contract/resolve` has no
194
+ * alternative to.
195
+ */
196
+ export interface LegacyContractRequest {
197
+ format: 'legacy';
198
+ }
199
+
200
+ export type ContractMessageRequest =
201
+ | LoanAgreementRequest
202
+ | LegacyContractRequest;
203
+
204
+ /**
205
+ * Every side effect the pipeline needs, injected.
206
+ *
207
+ * `kasu.flows.deposit()` fills `readAllowance`, `approve`, `deposit` and
208
+ * `buildKycParams` from the SDK's own signer-bound implementations; the three
209
+ * that reach the consumer's own backend or wallet have no sensible default and
210
+ * are always supplied by the application.
211
+ */
212
+ export interface DepositPorts {
213
+ /** EIP-191 personal sign. Rejects when the lender refuses. */
214
+ signMessage(message: string): Promise<string>;
215
+ /** POST the generate request; resolve with the agreements service's reply. */
216
+ generateContract(
217
+ req: GenerateContractRequest,
218
+ ): Promise<GenerateContractResponse>;
219
+ /** Build the Nexera KYC params. Defaults to `kasu.deposits.buildKycParams`. */
220
+ buildKycParams(
221
+ userAddress: `0x${string}`,
222
+ ): KycParams | Promise<KycParams>;
223
+ /** Exchange those params for a signature at the consumer's own backend. */
224
+ getKycSignature(params: KycParams): Promise<KycSignature>;
225
+ /** ERC-20 `allowance(owner, spender)`, in base units. */
226
+ readAllowance(owner: string, spender: string): Promise<BigNumber>;
227
+ /** ERC-20 `approve(spender, amount)`. The flow only ever passes the EXACT amount. */
228
+ approve(spender: string, amount: BigNumber): Promise<WaitableTransaction>;
229
+ /** `requestDepositWithKyc`. Defaults to `kasu.deposits.deposit`. */
230
+ deposit(params: DepositParams): Promise<WaitableTransaction>;
231
+ /** ms-epoch clock. Defaults to `Date.now`; injected so the TTL is testable. */
232
+ now?(): number;
233
+ }
234
+
235
+ /** Construction options. `kasu.flows.deposit()` fills `spender` in. */
236
+ export interface DepositFlowOptions {
237
+ /** Agreement validity window; defaults to `CONTRACT_TTL_MS`. */
238
+ contractTtlMs?: number;
239
+ /**
240
+ * The ERC-20 spender every run approves and deposits through, when the
241
+ * input does not name one. `kasu.flows.deposit()` passes this chain's
242
+ * `contracts.LendingPoolManager`, which is the only contract the default
243
+ * deposit port calls.
244
+ */
245
+ spender?: string;
246
+ }
247
+
248
+ // ---------------------------------------------------------------------------
249
+ // Input and state
250
+ // ---------------------------------------------------------------------------
251
+
252
+ export interface DepositFlowInput {
253
+ poolId: string;
254
+ trancheId: string;
255
+ /** The deposit in BASE units (6dp for USDC and AUDD). */
256
+ amount: BigNumber;
257
+ /** `'0'` for a variable-rate deposit. */
258
+ fixedTermConfigId: string;
259
+ userAddress: `0x${string}`;
260
+ /**
261
+ * The ERC-20 spender, when it is NOT this chain's `LendingPoolManager`.
262
+ *
263
+ * Leave it out: `kasu.flows.deposit()` defaults it from the chain config,
264
+ * and the default deposit port calls no other contract. It exists for a
265
+ * consumer that replaced the `deposit` port with one that spends
266
+ * somewhere else — a wrong spender is an approval granted to the wrong
267
+ * contract and then a revert diagnosed as `insufficient-balance`.
268
+ */
269
+ spender?: string;
270
+ /** Which signed-message format to use, and its fields. */
271
+ contractMessage: ContractMessageRequest;
272
+ /**
273
+ * The deposit in DISPLAY units, for the generate request only.
274
+ *
275
+ * NOT derived from `amount`: turning base units back into a display number
276
+ * is formatting, and formatting is the application's job — it is also the
277
+ * application that produced `amountLabel`, and kasu-backend refuses the two
278
+ * if they disagree. Pass the same value both were built from.
279
+ */
280
+ depositAmount?: number;
281
+ }
282
+
283
+ export interface DepositState {
284
+ phase: DepositPhase;
285
+ /** The step `phase` belongs to; `null` only while idle. */
286
+ step: DepositStep | null;
287
+ /** 1-based badge position of `step`; `0` while idle. */
288
+ stepIndex: number;
289
+ /** `4`, or `3` when the allowance already covers the deposit. */
290
+ stepTotal: number;
291
+ /** Whether the approve step is in scope for this run. */
292
+ approvalRequired: boolean;
293
+ /** The generated agreement, from `generating-fetch` onwards. */
294
+ contract: GenerateContractResponse | null;
295
+ /** Set with `phase: 'error'`, cleared by `reset()`. */
296
+ failure: DepositFailure | null;
297
+ }
298
+
299
+ /** Generated agreements are valid for five minutes upstream. */
300
+ export const CONTRACT_TTL_MS = 5 * 60 * 1000;
301
+
302
+ /** What a run without a spender, from either source, fails with. */
303
+ export const NO_SPENDER_MESSAGE =
304
+ 'DepositFlow: no ERC-20 spender; build the flow with kasu.flows.deposit() or pass `spender` on the input';
305
+
306
+ const INITIAL: DepositState = {
307
+ phase: 'idle',
308
+ step: null,
309
+ stepIndex: 0,
310
+ stepTotal: 4,
311
+ approvalRequired: true,
312
+ contract: null,
313
+ failure: null,
314
+ };
315
+
316
+ // ---------------------------------------------------------------------------
317
+ // Internals
318
+ // ---------------------------------------------------------------------------
319
+
320
+ /**
321
+ * How the park ends, as data.
322
+ *
323
+ * It used to be signalled by throwing tagged `Error`s and sniffing them again
324
+ * on the way out, which meant a port error whose message happened to read
325
+ * `contract-declined` ENDED THE RUN AS A DECLINE — a lender's deposit
326
+ * abandoned on a string coincidence. A discriminated result cannot be
327
+ * counterfeited by an error message: `failed` carries the throw, and only
328
+ * `declineContract()` can produce `declined`.
329
+ */
330
+ type AcceptOutcome =
331
+ | { kind: 'accepted'; signature: string }
332
+ | { kind: 'declined' }
333
+ | { kind: 'failed'; error: unknown }
334
+ /** `reset()` unparked it. The run's token check drops everything after. */
335
+ | { kind: 'abandoned' };
336
+
337
+ /** 1-based badge position, with `approve` dropped when it is out of scope. */
338
+ function stepIndexOf(step: DepositStep, approvalRequired: boolean): number {
339
+ const order: DepositStep[] = approvalRequired
340
+ ? ['generate', 'confirm', 'approve', 'request']
341
+ : ['generate', 'confirm', 'request'];
342
+ return order.indexOf(step) + 1;
343
+ }
344
+
345
+ function badgeFor(
346
+ step: DepositStep,
347
+ approvalRequired: boolean,
348
+ ): Pick<DepositState, 'step' | 'stepIndex' | 'stepTotal'> {
349
+ return {
350
+ step,
351
+ stepIndex: stepIndexOf(step, approvalRequired),
352
+ stepTotal: approvalRequired ? 4 : 3,
353
+ };
354
+ }
355
+
356
+ /**
357
+ * The request step has a third outcome. `UNPREDICTABLE_GAS_LIMIT` here is
358
+ * almost always `transferFrom` reverting on a balance that cannot cover the
359
+ * deposit, and it takes precedence: nothing was refused by the lender, so
360
+ * inviting a retry would just reproduce it.
361
+ */
362
+ function classifyRequest(err: unknown): DepositFailure {
363
+ if (isUnpredictableGas(err)) {
364
+ return { step: 'request', reason: 'insufficient-balance', error: err };
365
+ }
366
+ return classifyWalletFailure('request', err);
367
+ }
368
+
369
+ // ---------------------------------------------------------------------------
370
+ // The flow
371
+ // ---------------------------------------------------------------------------
372
+
373
+ export class DepositFlow extends Flow<DepositState, DepositFlowInput> {
374
+ private readonly _ttlMs: number;
375
+ private readonly _defaultSpender: string | undefined;
376
+ private readonly _now: () => number;
377
+
378
+ /**
379
+ * The accept handshake. The run parks on this promise; `acceptContract`,
380
+ * `declineContract` and `reset` each settle it with an `AcceptOutcome`.
381
+ * Cleared the moment it settles so a stale resolver from an abandoned run
382
+ * can never leak into the next one.
383
+ */
384
+ private _accept: { settle: (outcome: AcceptOutcome) => void } | null = null;
385
+
386
+ /**
387
+ * The run token that is between `acceptContract()` and the wallet
388
+ * settling, or `null`.
389
+ *
390
+ * A token rather than a boolean, because the flag has to belong to the RUN
391
+ * that set it: after `reset()` out of a wallet prompt that never answers,
392
+ * the abandoned run's `finally` may not arrive for minutes, and a boolean
393
+ * left standing refuses both Accept and Decline on every run after it.
394
+ * A stale token simply is not the current generation.
395
+ */
396
+ private _acceptingFor: number | null = null;
397
+
398
+ constructor(
399
+ private readonly _ports: DepositPorts,
400
+ opts?: DepositFlowOptions,
401
+ ) {
402
+ super(INITIAL);
403
+ this._ttlMs = opts?.contractTtlMs ?? CONTRACT_TTL_MS;
404
+ this._defaultSpender = opts?.spender;
405
+ // Called through the ports object, never captured off it: a consumer
406
+ // whose clock is a method on its own object keeps its `this`.
407
+ this._now = (): number => _ports.now?.() ?? Date.now();
408
+ }
409
+
410
+ /**
411
+ * Sign the agreement and resume the parked run. A no-op when nothing is
412
+ * parked, so a double tap cannot sign twice.
413
+ */
414
+ async acceptContract(): Promise<void> {
415
+ const bridge = this._accept;
416
+ const contract = this._store.state.contract;
417
+ if (!bridge || !contract || this._isAccepting()) return;
418
+ const token = this._store.generation;
419
+ this._acceptingFor = token;
420
+ this._store.patch(
421
+ {
422
+ phase: 'accepting-sign',
423
+ ...badgeFor('confirm', this._store.state.approvalRequired),
424
+ },
425
+ token,
426
+ );
427
+ try {
428
+ const signature = await this._ports.signMessage(
429
+ contract.contractMessage,
430
+ );
431
+ bridge.settle({ kind: 'accepted', signature });
432
+ } catch (err) {
433
+ // A WALLET error, and the only one this flow classifies as a
434
+ // possible cancellation on the confirm step.
435
+ bridge.settle({ kind: 'failed', error: err });
436
+ } finally {
437
+ // Only if this run still holds it: a `reset()` during the prompt
438
+ // may have started another one, and that one's flag is its own.
439
+ if (this._acceptingFor === token) this._acceptingFor = null;
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Back out of the agreement. The run ends on `declined` — a legitimate
445
+ * choice, not a failure, and `state.failure` stays null.
446
+ *
447
+ * Ignored once `acceptContract()` has opened the wallet: an agreement in
448
+ * the middle of being signed cannot also be refused. `reset()` is the way
449
+ * out of a prompt that never answers.
450
+ */
451
+ declineContract(): void {
452
+ const bridge = this._accept;
453
+ if (!bridge || this._isAccepting()) return;
454
+ this._accept = null;
455
+ bridge.settle({ kind: 'declined' });
456
+ }
457
+
458
+ /** True only while THIS generation is waiting on the acceptance signature. */
459
+ private _isAccepting(): boolean {
460
+ return (
461
+ this._acceptingFor !== null &&
462
+ this._store.isCurrent(this._acceptingFor)
463
+ );
464
+ }
465
+
466
+ /** `reset()`: unpark the abandoned run and drop its handshake. */
467
+ protected override _onAbandon(): void {
468
+ const bridge = this._accept;
469
+ this._accept = null;
470
+ this._acceptingFor = null;
471
+ bridge?.settle({ kind: 'abandoned' });
472
+ }
473
+
474
+ // -----------------------------------------------------------------------
475
+
476
+ protected async _run(
477
+ input: DepositFlowInput,
478
+ token: number,
479
+ ): Promise<void> {
480
+ this._accept = null;
481
+ this._acceptingFor = null;
482
+ const ports = this._ports;
483
+ const owner = input.userAddress.toLowerCase();
484
+
485
+ // 0. The spender, from the input or from the chain config the facade
486
+ // built this flow with. Without one there is nothing to read an
487
+ // allowance against and nothing to approve — and guessing would
488
+ // grant an approval to the wrong contract.
489
+ const spender = input.spender ?? this._defaultSpender;
490
+ if (!spender) {
491
+ this._fail(token, true, {
492
+ step: 'generate',
493
+ reason: 'failed',
494
+ error: new Error(NO_SPENDER_MESSAGE),
495
+ });
496
+ return;
497
+ }
498
+
499
+ // 1. Allowance pre-check. Decides `approvalRequired` — and therefore
500
+ // the badge total — before the lender is shown a single step. Read
501
+ // live, never cached: an exact-amount approval is fully consumed by
502
+ // the deposit it paid for, so a stale allowance is exactly the value
503
+ // that would wrongly skip the approve and revert the deposit.
504
+ let approvalRequired = true;
505
+ try {
506
+ const allowance = await ports.readAllowance(owner, spender);
507
+ approvalRequired = allowance.lt(input.amount);
508
+ } catch {
509
+ // A read failure is not a reason to skip an approval. Assume one is
510
+ // needed: the cost is a redundant approve, the alternative is a
511
+ // reverted deposit.
512
+ approvalRequired = true;
513
+ }
514
+ if (!this._store.isCurrent(token)) return;
515
+
516
+ // 2. Generate — sign the auth message.
517
+ this._store.patch(
518
+ {
519
+ approvalRequired,
520
+ phase: 'generating-sign',
521
+ ...badgeFor('generate', approvalRequired),
522
+ },
523
+ token,
524
+ );
525
+
526
+ const timestamp = this._now();
527
+ const signedMessage = buildAuthMessage(input, owner, timestamp);
528
+ let signature: string;
529
+ try {
530
+ signature = await ports.signMessage(signedMessage);
531
+ } catch (err) {
532
+ this._fail(
533
+ token,
534
+ approvalRequired,
535
+ classifyWalletFailure('generate', err),
536
+ );
537
+ return;
538
+ }
539
+ if (!this._store.isCurrent(token)) return;
540
+
541
+ // 3. Generate — POST the request.
542
+ this._store.patch(
543
+ {
544
+ phase: 'generating-fetch',
545
+ ...badgeFor('generate', approvalRequired),
546
+ },
547
+ token,
548
+ );
549
+ let contract: GenerateContractResponse;
550
+ try {
551
+ contract = await ports.generateContract({
552
+ address: owner,
553
+ signature,
554
+ timestamp,
555
+ signedMessage,
556
+ poolId: input.poolId,
557
+ trancheId: input.trancheId,
558
+ fixedTermConfigId: input.fixedTermConfigId,
559
+ depositAmount: input.depositAmount,
560
+ ...displayFieldsOf(input.contractMessage),
561
+ });
562
+ } catch (err) {
563
+ // Never a wallet rejection: this step is an HTTP call, and the
564
+ // lender's wallet was not involved in it. A backend that happened
565
+ // to echo the words "user rejected" must not be reported to them as
566
+ // something they did.
567
+ this._fail(token, approvalRequired, {
568
+ step: 'generate',
569
+ reason: 'failed',
570
+ error: err,
571
+ });
572
+ return;
573
+ }
574
+ if (!this._store.isCurrent(token)) return;
575
+
576
+ // 4. Park on the agreement until the consumer accepts or declines.
577
+ const outcome = await new Promise<AcceptOutcome>((resolve) => {
578
+ this._accept = { settle: resolve };
579
+ this._store.patch(
580
+ {
581
+ phase: 'awaiting-accept',
582
+ contract,
583
+ ...badgeFor('confirm', approvalRequired),
584
+ },
585
+ token,
586
+ );
587
+ });
588
+ this._accept = null;
589
+ // An abandoned run lands here too — `reset()` unparks it. The token
590
+ // check is what tells the two apart.
591
+ if (!this._store.isCurrent(token)) return;
592
+ if (outcome.kind === 'declined') {
593
+ this._store.patch(
594
+ { phase: 'declined', ...badgeFor('confirm', approvalRequired) },
595
+ token,
596
+ );
597
+ return;
598
+ }
599
+ if (outcome.kind !== 'accepted') {
600
+ if (outcome.kind === 'failed') {
601
+ this._fail(
602
+ token,
603
+ approvalRequired,
604
+ classifyWalletFailure('confirm', outcome.error),
605
+ );
606
+ }
607
+ return;
608
+ }
609
+
610
+ // 5. TTL guard. Checked here because this is where the idling happens:
611
+ // the lender has just spent as long as they wanted reading. An
612
+ // expired agreement is refused rather than broadcast — the on-chain
613
+ // call would revert, after a wallet prompt and a gas estimate, with
614
+ // nothing on screen explaining why.
615
+ if (this._now() > contract.timestamp + this._ttlMs) {
616
+ this._fail(token, approvalRequired, {
617
+ step: 'request',
618
+ reason: 'contract-expired',
619
+ });
620
+ return;
621
+ }
622
+
623
+ const depositData = encodeDepositData({
624
+ signature: outcome.signature,
625
+ timestamp: contract.timestamp,
626
+ contractVersion: contract.contractVersion,
627
+ contractType: asContractType(contract.contractType),
628
+ });
629
+
630
+ // 6. Approve — the EXACT amount, never `MaxUint256`. House rule: an
631
+ // unlimited allowance outlives the deposit it was granted for, and a
632
+ // later exploit of the spender would drain a wallet that has long
633
+ // since stopped lending.
634
+ if (approvalRequired) {
635
+ this._store.patch(
636
+ { phase: 'approve', ...badgeFor('approve', approvalRequired) },
637
+ token,
638
+ );
639
+ try {
640
+ const tx = await ports.approve(spender, input.amount);
641
+ await tx.wait();
642
+ } catch (err) {
643
+ this._fail(
644
+ token,
645
+ approvalRequired,
646
+ classifyWalletFailure('approve', err),
647
+ );
648
+ return;
649
+ }
650
+ if (!this._store.isCurrent(token)) return;
651
+ }
652
+
653
+ // 7. Request — KYC signature, then the deposit and its receipt.
654
+ this._store.patch(
655
+ { phase: 'request-sign', ...badgeFor('request', approvalRequired) },
656
+ token,
657
+ );
658
+
659
+ // The two KYC ports reach the consumer's own backend, so they fail the
660
+ // way the generate step does: `failed`, with the error kept. Running
661
+ // them through the rejection classifier would let a backend wording —
662
+ // "Declined", "request rejected" — end a run as "you cancelled in your
663
+ // wallet", with the real error discarded and nothing to report.
664
+ let kyc: KycSignature;
665
+ try {
666
+ const kycParams = await ports.buildKycParams(
667
+ owner as `0x${string}`,
668
+ );
669
+ kyc = await ports.getKycSignature(kycParams);
670
+ } catch (err) {
671
+ this._fail(token, approvalRequired, {
672
+ step: 'request',
673
+ reason: 'failed',
674
+ error: err,
675
+ });
676
+ return;
677
+ }
678
+ if (!this._store.isCurrent(token)) return;
679
+
680
+ try {
681
+ const tx = await ports.deposit({
682
+ poolId: input.poolId,
683
+ trancheId: input.trancheId,
684
+ amount: input.amount,
685
+ kycSignature: {
686
+ blockExpiration: kyc.blockExpiration,
687
+ signature: kyc.signature,
688
+ },
689
+ depositData,
690
+ fixedTermConfigId: input.fixedTermConfigId,
691
+ });
692
+ this._store.patch(
693
+ {
694
+ phase: 'request-confirm',
695
+ ...badgeFor('request', approvalRequired),
696
+ },
697
+ token,
698
+ );
699
+ await tx.wait();
700
+ } catch (err) {
701
+ this._fail(token, approvalRequired, classifyRequest(err));
702
+ return;
703
+ }
704
+ if (!this._store.isCurrent(token)) return;
705
+
706
+ this._store.patch(
707
+ { phase: 'success', ...badgeFor('request', approvalRequired) },
708
+ token,
709
+ );
710
+ }
711
+
712
+ private _fail(
713
+ token: number,
714
+ approvalRequired: boolean,
715
+ failure: DepositFailure,
716
+ ): void {
717
+ this._store.patch(
718
+ {
719
+ phase: 'error',
720
+ failure,
721
+ ...badgeFor(failure.step, approvalRequired),
722
+ },
723
+ token,
724
+ );
725
+ }
726
+ }
727
+
728
+ // ---------------------------------------------------------------------------
729
+ // Message building
730
+ // ---------------------------------------------------------------------------
731
+
732
+ /**
733
+ * The auth message, in whichever format the consumer asked for. Both builders
734
+ * are the byte-exact protocol strings from `domain/loan-contract` — the string
735
+ * signed here and the body posted from `_run` state the SAME timestamp and the
736
+ * SAME lowercased address, because kasu-backend rebuilds one from the other.
737
+ */
738
+ function buildAuthMessage(
739
+ input: DepositFlowInput,
740
+ owner: string,
741
+ timestamp: number,
742
+ ): string {
743
+ if (input.contractMessage.format === 'legacy') {
744
+ return buildLegacyContractRequestMessage(owner, timestamp);
745
+ }
746
+ const { strategyName, region, optionName, amountLabel } =
747
+ input.contractMessage;
748
+ return buildLoanAgreementSignMessage({
749
+ strategyName,
750
+ region,
751
+ optionName,
752
+ amountLabel,
753
+ timestamp,
754
+ });
755
+ }
756
+
757
+ /**
758
+ * The four display fields, present only on the new format. The backend picks
759
+ * its verification path on their presence: all four → the human-readable
760
+ * format, any missing → the legacy string.
761
+ */
762
+ function displayFieldsOf(
763
+ message: ContractMessageRequest,
764
+ ): Pick<
765
+ GenerateContractRequest,
766
+ 'strategyName' | 'region' | 'optionName' | 'amountLabel'
767
+ > {
768
+ if (message.format === 'legacy') return {};
769
+ return {
770
+ strategyName: message.strategyName,
771
+ region: message.region,
772
+ optionName: message.optionName,
773
+ amountLabel: message.amountLabel,
774
+ };
775
+ }