@kasufinance/kasu-sdk 2.6.0 → 2.7.1

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 (126) hide show
  1. package/README.md +167 -4
  2. package/dist/bundle.cjs.js +1389 -257
  3. package/dist/bundle.esm.js +1375 -258
  4. package/dist/domain/index.d.ts +5 -2
  5. package/dist/domain/index.js +3 -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/revert-errors.d.ts +59 -0
  11. package/dist/domain/revert-errors.js +190 -0
  12. package/dist/domain/revert-errors.js.map +1 -0
  13. package/dist/domain/wallet-errors.d.ts +63 -8
  14. package/dist/domain/wallet-errors.js +115 -16
  15. package/dist/domain/wallet-errors.js.map +1 -1
  16. package/dist/facade/deposits.js +2 -1
  17. package/dist/facade/deposits.js.map +1 -1
  18. package/dist/facade/flows.d.ts +95 -0
  19. package/dist/facade/flows.js +116 -0
  20. package/dist/facade/flows.js.map +1 -0
  21. package/dist/facade/index.d.ts +3 -0
  22. package/dist/facade/index.js +3 -0
  23. package/dist/facade/index.js.map +1 -1
  24. package/dist/facade/kasu.d.ts +6 -2
  25. package/dist/facade/kasu.js +28 -3
  26. package/dist/facade/kasu.js.map +1 -1
  27. package/dist/facade/read-only.d.ts +12 -0
  28. package/dist/facade/read-only.js +13 -0
  29. package/dist/facade/read-only.js.map +1 -0
  30. package/dist/flows/deposit-flow.d.ts +332 -0
  31. package/dist/flows/deposit-flow.js +436 -0
  32. package/dist/flows/deposit-flow.js.map +1 -0
  33. package/dist/flows/flow.d.ts +72 -0
  34. package/dist/flows/flow.js +110 -0
  35. package/dist/flows/flow.js.map +1 -0
  36. package/dist/flows/index.d.ts +19 -0
  37. package/dist/flows/index.js +17 -0
  38. package/dist/flows/index.js.map +1 -0
  39. package/dist/flows/observable.d.ts +59 -0
  40. package/dist/flows/observable.js +81 -0
  41. package/dist/flows/observable.js.map +1 -0
  42. package/dist/flows/withdraw-flow.d.ts +99 -0
  43. package/dist/flows/withdraw-flow.js +83 -0
  44. package/dist/flows/withdraw-flow.js.map +1 -0
  45. package/dist/index.d.ts +1 -0
  46. package/dist/index.js +6 -0
  47. package/dist/index.js.map +1 -1
  48. package/dist/services/DataService/data-service.js +0 -1
  49. package/dist/services/DataService/data-service.js.map +1 -1
  50. package/package.json +8 -2
  51. package/src/domain/index.ts +10 -1
  52. package/src/domain/requests.ts +57 -4
  53. package/src/domain/revert-errors.ts +248 -0
  54. package/src/domain/wallet-errors.ts +135 -18
  55. package/src/facade/deposits.ts +2 -3
  56. package/src/facade/flows.ts +172 -0
  57. package/src/facade/index.ts +8 -0
  58. package/src/facade/kasu.ts +43 -3
  59. package/src/facade/read-only.ts +13 -0
  60. package/src/flows/deposit-flow.ts +884 -0
  61. package/src/flows/flow.ts +108 -0
  62. package/src/flows/index.ts +47 -0
  63. package/src/flows/observable.ts +97 -0
  64. package/src/flows/withdraw-flow.ts +210 -0
  65. package/src/index.ts +7 -0
  66. package/src/services/DataService/data-service.ts +0 -1
  67. package/dist/domain/au-minimum.test.d.ts +0 -1
  68. package/dist/domain/au-minimum.test.js +0 -202
  69. package/dist/domain/au-minimum.test.js.map +0 -1
  70. package/dist/domain/deposit-bounds.test.d.ts +0 -1
  71. package/dist/domain/deposit-bounds.test.js +0 -135
  72. package/dist/domain/deposit-bounds.test.js.map +0 -1
  73. package/dist/domain/loan-contract.test.d.ts +0 -1
  74. package/dist/domain/loan-contract.test.js +0 -255
  75. package/dist/domain/loan-contract.test.js.map +0 -1
  76. package/dist/domain/partners.test.d.ts +0 -1
  77. package/dist/domain/partners.test.js +0 -53
  78. package/dist/domain/partners.test.js.map +0 -1
  79. package/dist/domain/pools.test.d.ts +0 -1
  80. package/dist/domain/pools.test.js +0 -184
  81. package/dist/domain/pools.test.js.map +0 -1
  82. package/dist/domain/rates.test.d.ts +0 -1
  83. package/dist/domain/rates.test.js +0 -181
  84. package/dist/domain/rates.test.js.map +0 -1
  85. package/dist/domain/requests.test.d.ts +0 -1
  86. package/dist/domain/requests.test.js +0 -470
  87. package/dist/domain/requests.test.js.map +0 -1
  88. package/dist/domain/settlement.test.d.ts +0 -1
  89. package/dist/domain/settlement.test.js +0 -152
  90. package/dist/domain/settlement.test.js.map +0 -1
  91. package/dist/domain/tranche-display-name.test.d.ts +0 -1
  92. package/dist/domain/tranche-display-name.test.js +0 -58
  93. package/dist/domain/tranche-display-name.test.js.map +0 -1
  94. package/dist/domain/tranches.test.d.ts +0 -1
  95. package/dist/domain/tranches.test.js +0 -206
  96. package/dist/domain/tranches.test.js.map +0 -1
  97. package/dist/domain/wallet-errors.test.d.ts +0 -1
  98. package/dist/domain/wallet-errors.test.js +0 -71
  99. package/dist/domain/wallet-errors.test.js.map +0 -1
  100. package/dist/facade/config.test.d.ts +0 -1
  101. package/dist/facade/config.test.js +0 -216
  102. package/dist/facade/config.test.js.map +0 -1
  103. package/dist/facade/facade.test.d.ts +0 -1
  104. package/dist/facade/facade.test.js +0 -278
  105. package/dist/facade/facade.test.js.map +0 -1
  106. package/dist/services/Locking/calculate-apy.test.d.ts +0 -1
  107. package/dist/services/Locking/calculate-apy.test.js +0 -41
  108. package/dist/services/Locking/calculate-apy.test.js.map +0 -1
  109. package/dist/tests/sample.test.d.ts +0 -1
  110. package/dist/tests/sample.test.js +0 -59
  111. package/dist/tests/sample.test.js.map +0 -1
  112. package/src/domain/au-minimum.test.ts +0 -371
  113. package/src/domain/deposit-bounds.test.ts +0 -200
  114. package/src/domain/loan-contract.test.ts +0 -343
  115. package/src/domain/partners.test.ts +0 -83
  116. package/src/domain/pools.test.ts +0 -260
  117. package/src/domain/rates.test.ts +0 -254
  118. package/src/domain/requests.test.ts +0 -653
  119. package/src/domain/settlement.test.ts +0 -198
  120. package/src/domain/tranche-display-name.test.ts +0 -96
  121. package/src/domain/tranches.test.ts +0 -300
  122. package/src/domain/wallet-errors.test.ts +0 -100
  123. package/src/facade/config.test.ts +0 -265
  124. package/src/facade/facade.test.ts +0 -374
  125. package/src/services/Locking/calculate-apy.test.ts +0 -52
  126. package/src/tests/sample.test.ts +0 -63
@@ -0,0 +1,332 @@
1
+ import { BigNumber } from 'ethers';
2
+ import { GenerateContractResponse } from '../domain/loan-contract';
3
+ import { DepositParams, KycParams } from '../facade/types';
4
+ import { Flow } from './flow';
5
+ import { WaitableTransaction } from './observable';
6
+ /**
7
+ * The KYC-gated deposit pipeline, headless.
8
+ *
9
+ * This is the state machine kasu-ui and kasu-mobile each hand-wrote and then
10
+ * had to keep in step by hand: sign an auth message, generate the loan
11
+ * agreement, park while the lender reads it, sign it, approve the EXACT amount,
12
+ * fetch the KYC signature, submit, wait. Two implementations of one money path
13
+ * is one too many, so it lives here once and each application drives it from
14
+ * its own UI.
15
+ *
16
+ * **No React, no copy, no I/O of its own.** Every side effect is an injected
17
+ * port and every observable state is a code — `{ step: 'approve', reason:
18
+ * 'cancelled' }`, never "USDC approval was cancelled in your wallet". The
19
+ * applications keep their own `DEPOSIT_STEP_ERRORS` tables and map the codes to
20
+ * their words, in their design system and their language. Nothing in this file
21
+ * may be shown to a lender.
22
+ *
23
+ * ## Order, and why each step is where it is
24
+ *
25
+ * 1. **Allowance pre-check** — before anything is signed, because it decides
26
+ * `approvalRequired`, which decides `stepTotal`. A badge that said "3 of 4"
27
+ * and then silently became "3 of 3" would be describing a pipeline the
28
+ * lender is not in. A failed read assumes an approve IS needed: the safe
29
+ * default is a redundant approval, never a reverted deposit.
30
+ * 2. **`generating-sign`** — the lender signs the auth message
31
+ * (`buildLoanAgreementSignMessage`, or the legacy builder). kasu-backend
32
+ * reconstructs that string byte-for-byte to verify the signature.
33
+ * 3. **`generating-fetch`** — the agreements service returns the contract.
34
+ * 4. **`awaiting-accept`** — the run PARKS on a promise the consumer settles
35
+ * with `acceptContract()` or `declineContract()`. This is the only point at
36
+ * which a lender is committing to anything.
37
+ * 5. **`accepting-sign`** — the acceptance signature, which becomes the
38
+ * on-chain `depositData` via `encodeDepositData`.
39
+ * 6. **The 5-minute TTL guard** — checked AFTER the accept, because that is
40
+ * where the idling happens. An expired agreement is refused here rather than
41
+ * broadcast as a transaction that cannot succeed.
42
+ * 7. **`approve`** — the EXACT amount, never `MaxUint256`. House rule, and it
43
+ * is why the allowance drops to zero after every deposit and why step 1
44
+ * reads it fresh rather than trusting a cache.
45
+ * 8. **`request-sign` / `request-confirm`** — KYC signature, then the deposit,
46
+ * then the receipt.
47
+ *
48
+ * ## Failure codes
49
+ *
50
+ * A wallet rejection (`isUserRejected`) is `'cancelled'` — the lender changed
51
+ * their mind, and telling them something broke would be a lie. Only a WALLET
52
+ * call is ever classified that way: the HTTP ports are always `'failed'`,
53
+ * because a backend that words a refusal "declined" did not involve the
54
+ * lender's wallet. A revert on the request step is read for WHAT reverted: a
55
+ * protocol error the ABI declares is `'reverted'` with the name, and only a
56
+ * token balance or allowance failure — or a revert nothing can decode — stays
57
+ * `'insufficient-balance'`. Everything else is `'failed'` and carries the
58
+ * original error for the consumer's crash reporter.
59
+ *
60
+ * ## Both signatures are checked before they are used
61
+ *
62
+ * A wallet is not obliged to hand back 65 bytes, and `encodeDepositData` will
63
+ * not catch one that does not: `defaultAbiCoder` encodes any even-length hex
64
+ * as `bytes`, `0x` included, so a malformed acceptance signature becomes a
65
+ * `depositData` blob that is broadcast, mined, and then can never be verified
66
+ * by the agreements service. Both personal signs are therefore length-checked
67
+ * where they are taken, and a bad one fails the step it was taken on rather
68
+ * than the one it would eventually have broken.
69
+ *
70
+ * ```ts
71
+ * const flow = new DepositFlow(ports);
72
+ * const stop = flow.subscribe((s) => render(s));
73
+ * await flow.start({ poolId, trancheId, amount, userAddress, ... });
74
+ * // …the consumer shows `flow.state.contract` and calls:
75
+ * await flow.acceptContract();
76
+ * ```
77
+ */
78
+ /**
79
+ * Where the run is. `success`, `declined` and `error` are terminal; everything
80
+ * else is in flight.
81
+ */
82
+ export type DepositPhase = 'idle' | 'generating-sign' | 'generating-fetch' | 'awaiting-accept' | 'accepting-sign' | 'approve' | 'request-sign' | 'request-confirm' | 'success' | 'declined' | 'error';
83
+ /**
84
+ * The four steps a lender sees as a badge. `approve` drops out of the sequence
85
+ * when the allowance already covers the deposit, which is why `stepIndex` and
86
+ * `stepTotal` are published rather than derived by each consumer.
87
+ */
88
+ export type DepositStep = 'generate' | 'confirm' | 'approve' | 'request';
89
+ /**
90
+ * Why a run did not reach `success`, as a code plus the step it happened on.
91
+ *
92
+ * The consumer maps this to its own words. `error` carries the underlying
93
+ * throw for a crash reporter — a `cancelled` and a `contract-expired` do not,
94
+ * because neither is a fault worth reporting.
95
+ */
96
+ export type DepositFailure = {
97
+ step: DepositStep;
98
+ reason: 'cancelled';
99
+ } | {
100
+ step: DepositStep;
101
+ reason: 'failed';
102
+ error: unknown;
103
+ } | {
104
+ step: 'request';
105
+ reason: 'insufficient-balance';
106
+ error: unknown;
107
+ } | {
108
+ step: 'request';
109
+ reason: 'reverted';
110
+ /**
111
+ * The custom error the contract reverted with, exactly as the ABI
112
+ * declares it — `'ClearingIsPending'`, `'LendingPoolIsStopped'`,
113
+ * `'UserNotKycd'`, and the rest of
114
+ * `ILendingPoolManagerAbi` / `IKasuAllowListAbi`.
115
+ *
116
+ * Render `reverted` with generic copy and special-case only the
117
+ * names you have words for: a contract upgrade can add an error, and
118
+ * a consumer that assumed the set was closed would have nothing to
119
+ * show for the new one.
120
+ */
121
+ revertError: string;
122
+ error: unknown;
123
+ } | {
124
+ step: 'request';
125
+ reason: 'contract-expired';
126
+ };
127
+ export type { WaitableTransaction };
128
+ /** What the KYC signing service hands back. */
129
+ export interface KycSignature {
130
+ signature: string;
131
+ blockExpiration: number | string;
132
+ }
133
+ /**
134
+ * The `/contract/generate` body, assembled by the flow and posted by the
135
+ * consumer's own port — through its server-side proxy (kasu-ui) or straight to
136
+ * the agreements service (kasu-mobile). The SDK never makes the call itself and
137
+ * never learns the URL or the key.
138
+ */
139
+ export interface GenerateContractRequest {
140
+ /**
141
+ * The lender's address, LOWERCASED. The legacy message embeds this casing
142
+ * and kasu-backend rebuilds the string from the body, so the two must
143
+ * agree.
144
+ */
145
+ address: string;
146
+ /** Signature over `signedMessage`. */
147
+ signature: string;
148
+ /** ms-epoch. The same value `signedMessage` states — do not re-clock it. */
149
+ timestamp: number;
150
+ /**
151
+ * The exact text that was signed. Sent so a consumer can log or assert on
152
+ * it; the backend rebuilds it from the other fields rather than trusting
153
+ * this one.
154
+ */
155
+ signedMessage: string;
156
+ poolId: string;
157
+ trancheId: string;
158
+ /** `'0'` for a variable-rate deposit. */
159
+ fixedTermConfigId: string;
160
+ /**
161
+ * The deposit in DISPLAY units, forwarded verbatim from
162
+ * `DepositFlowInput.depositAmount`. kasu-backend cross-checks it against
163
+ * the leading number of `amountLabel`.
164
+ */
165
+ depositAmount?: number;
166
+ /** The four human-readable fields, present only on the new format. */
167
+ strategyName?: string;
168
+ region?: string;
169
+ optionName?: string;
170
+ amountLabel?: string;
171
+ }
172
+ /**
173
+ * The human-readable `/contract/generate` format (BD deck slide 19): the lender
174
+ * signs a statement naming the strategy, region, option and amount.
175
+ *
176
+ * `amountLabel` must be derived from the same value as `depositAmount` — the
177
+ * backend refuses a message that states an amount other than the one being
178
+ * executed. The SDK does not format it, because formatting is the
179
+ * application's (and its locale's) business.
180
+ */
181
+ export interface LoanAgreementRequest {
182
+ format: 'loan-agreement';
183
+ strategyName: string;
184
+ region: string;
185
+ optionName: string;
186
+ amountLabel: string;
187
+ }
188
+ /**
189
+ * The legacy `I request contract content for {address} at {timestamp}.`
190
+ * format, which kasu-backend still accepts and `/contract/resolve` has no
191
+ * alternative to.
192
+ */
193
+ export interface LegacyContractRequest {
194
+ format: 'legacy';
195
+ }
196
+ export type ContractMessageRequest = LoanAgreementRequest | LegacyContractRequest;
197
+ /**
198
+ * Every side effect the pipeline needs, injected.
199
+ *
200
+ * `kasu.flows.deposit()` fills `readAllowance`, `approve`, `deposit` and
201
+ * `buildKycParams` from the SDK's own signer-bound implementations; the three
202
+ * that reach the consumer's own backend or wallet have no sensible default and
203
+ * are always supplied by the application.
204
+ */
205
+ export interface DepositPorts {
206
+ /** EIP-191 personal sign. Rejects when the lender refuses. */
207
+ signMessage(message: string): Promise<string>;
208
+ /** POST the generate request; resolve with the agreements service's reply. */
209
+ generateContract(req: GenerateContractRequest): Promise<GenerateContractResponse>;
210
+ /** Build the Nexera KYC params. Defaults to `kasu.deposits.buildKycParams`. */
211
+ buildKycParams(userAddress: `0x${string}`): KycParams | Promise<KycParams>;
212
+ /** Exchange those params for a signature at the consumer's own backend. */
213
+ getKycSignature(params: KycParams): Promise<KycSignature>;
214
+ /** ERC-20 `allowance(owner, spender)`, in base units. */
215
+ readAllowance(owner: string, spender: string): Promise<BigNumber>;
216
+ /** ERC-20 `approve(spender, amount)`. The flow only ever passes the EXACT amount. */
217
+ approve(spender: string, amount: BigNumber): Promise<WaitableTransaction>;
218
+ /** `requestDepositWithKyc`. Defaults to `kasu.deposits.deposit`. */
219
+ deposit(params: DepositParams): Promise<WaitableTransaction>;
220
+ /** ms-epoch clock. Defaults to `Date.now`; injected so the TTL is testable. */
221
+ now?(): number;
222
+ }
223
+ /** Construction options. `kasu.flows.deposit()` fills `spender` in. */
224
+ export interface DepositFlowOptions {
225
+ /** Agreement validity window; defaults to `CONTRACT_TTL_MS`. */
226
+ contractTtlMs?: number;
227
+ /**
228
+ * The ERC-20 spender every run approves and deposits through, when the
229
+ * input does not name one. `kasu.flows.deposit()` passes this chain's
230
+ * `contracts.LendingPoolManager`, which is the only contract the default
231
+ * deposit port calls.
232
+ */
233
+ spender?: string;
234
+ }
235
+ export interface DepositFlowInput {
236
+ poolId: string;
237
+ trancheId: string;
238
+ /** The deposit in BASE units (6dp for USDC and AUDD). */
239
+ amount: BigNumber;
240
+ /** `'0'` for a variable-rate deposit. */
241
+ fixedTermConfigId: string;
242
+ userAddress: `0x${string}`;
243
+ /**
244
+ * The ERC-20 spender, when it is NOT this chain's `LendingPoolManager`.
245
+ *
246
+ * Leave it out: `kasu.flows.deposit()` defaults it from the chain config,
247
+ * and the default deposit port calls no other contract. It exists for a
248
+ * consumer that replaced the `deposit` port with one that spends
249
+ * somewhere else — a wrong spender is an approval granted to the wrong
250
+ * contract and then a revert diagnosed as `insufficient-balance`.
251
+ */
252
+ spender?: string;
253
+ /** Which signed-message format to use, and its fields. */
254
+ contractMessage: ContractMessageRequest;
255
+ /**
256
+ * The deposit in DISPLAY units, for the generate request only.
257
+ *
258
+ * NOT derived from `amount`: turning base units back into a display number
259
+ * is formatting, and formatting is the application's job — it is also the
260
+ * application that produced `amountLabel`, and kasu-backend refuses the two
261
+ * if they disagree. Pass the same value both were built from.
262
+ */
263
+ depositAmount?: number;
264
+ }
265
+ export interface DepositState {
266
+ phase: DepositPhase;
267
+ /** The step `phase` belongs to; `null` only while idle. */
268
+ step: DepositStep | null;
269
+ /** 1-based badge position of `step`; `0` while idle. */
270
+ stepIndex: number;
271
+ /** `4`, or `3` when the allowance already covers the deposit. */
272
+ stepTotal: number;
273
+ /** Whether the approve step is in scope for this run. */
274
+ approvalRequired: boolean;
275
+ /** The generated agreement, from `generating-fetch` onwards. */
276
+ contract: GenerateContractResponse | null;
277
+ /** Set with `phase: 'error'`, cleared by `reset()`. */
278
+ failure: DepositFailure | null;
279
+ }
280
+ /** Generated agreements are valid for five minutes upstream. */
281
+ export declare const CONTRACT_TTL_MS: number;
282
+ /** What a run without a spender, from either source, fails with. */
283
+ export declare const NO_SPENDER_MESSAGE = "DepositFlow: no ERC-20 spender; build the flow with kasu.flows.deposit() or pass `spender` on the input";
284
+ /** What a malformed auth signature fails the generate step with. */
285
+ export declare const INVALID_AUTH_SIGNATURE_MESSAGE = "DepositFlow: the wallet returned a malformed authentication signature; expected 65 bytes of 0x-prefixed hex";
286
+ /** What a malformed acceptance signature fails the confirm step with. */
287
+ export declare const INVALID_ACCEPTANCE_SIGNATURE_MESSAGE = "DepositFlow: the wallet returned a malformed acceptance signature; expected 65 bytes of 0x-prefixed hex";
288
+ export declare class DepositFlow extends Flow<DepositState, DepositFlowInput> {
289
+ private readonly _ports;
290
+ private readonly _ttlMs;
291
+ private readonly _defaultSpender;
292
+ private readonly _now;
293
+ /**
294
+ * The accept handshake. The run parks on this promise; `acceptContract`,
295
+ * `declineContract` and `reset` each settle it with an `AcceptOutcome`.
296
+ * Cleared the moment it settles so a stale resolver from an abandoned run
297
+ * can never leak into the next one.
298
+ */
299
+ private _accept;
300
+ /**
301
+ * The run token that is between `acceptContract()` and the wallet
302
+ * settling, or `null`.
303
+ *
304
+ * A token rather than a boolean, because the flag has to belong to the RUN
305
+ * that set it: after `reset()` out of a wallet prompt that never answers,
306
+ * the abandoned run's `finally` may not arrive for minutes, and a boolean
307
+ * left standing refuses both Accept and Decline on every run after it.
308
+ * A stale token simply is not the current generation.
309
+ */
310
+ private _acceptingFor;
311
+ constructor(_ports: DepositPorts, opts?: DepositFlowOptions);
312
+ /**
313
+ * Sign the agreement and resume the parked run. A no-op when nothing is
314
+ * parked, so a double tap cannot sign twice.
315
+ */
316
+ acceptContract(): Promise<void>;
317
+ /**
318
+ * Back out of the agreement. The run ends on `declined` — a legitimate
319
+ * choice, not a failure, and `state.failure` stays null.
320
+ *
321
+ * Ignored once `acceptContract()` has opened the wallet: an agreement in
322
+ * the middle of being signed cannot also be refused. `reset()` is the way
323
+ * out of a prompt that never answers.
324
+ */
325
+ declineContract(): void;
326
+ /** True only while THIS generation is waiting on the acceptance signature. */
327
+ private _isAccepting;
328
+ /** `reset()`: unpark the abandoned run and drop its handshake. */
329
+ protected _onAbandon(): void;
330
+ protected _run(input: DepositFlowInput, token: number): Promise<void>;
331
+ private _fail;
332
+ }