@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
@@ -16205,7 +16205,6 @@ class DataService {
16205
16205
  return __awaiter(this, void 0, void 0, function* () {
16206
16206
  var _a;
16207
16207
  const poolDelegateProfileAndHistoryDirectus = (yield this._directus.request(bs('PoolDelegateProfileAndHistory', {
16208
- // @ts-ignore Directus' deep-fields typing is fragile across versions
16209
16208
  fields: ['*', { otherPools: ['*'] }],
16210
16209
  })));
16211
16210
  const [poolNames, directusPoolNames] = yield Promise.all([
@@ -20836,12 +20835,12 @@ function toURLEncodedForm(data, options) {
20836
20835
  });
20837
20836
  }
20838
20837
 
20839
- const MAX_DEPTH = DEFAULT_FORM_DATA_MAX_DEPTH;
20838
+ const MAX_DEPTH$1 = DEFAULT_FORM_DATA_MAX_DEPTH;
20840
20839
 
20841
20840
  function throwIfDepthExceeded(index) {
20842
- if (index > MAX_DEPTH) {
20841
+ if (index > MAX_DEPTH$1) {
20843
20842
  throw new AxiosError$1(
20844
- 'FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH,
20843
+ 'FormData field is too deeply nested (' + index + ' levels). Max depth: ' + MAX_DEPTH$1,
20845
20844
  AxiosError$1.ERR_FORM_DATA_DEPTH_EXCEEDED
20846
20845
  );
20847
20846
  }
@@ -24351,6 +24350,19 @@ const CHAIN_CONFIGS = {
24351
24350
  },
24352
24351
  };
24353
24352
 
24353
+ /**
24354
+ * The refusal every write path shares when the instance holds a Provider
24355
+ * rather than a Signer.
24356
+ *
24357
+ * One constant, because the message's job is to name the fix — `kasu.connect`
24358
+ * — and three near-identical wordings across the facades would be three
24359
+ * different pieces of advice for one problem. ethers' own
24360
+ * "sending a transaction requires a signer" arrives several frames deeper,
24361
+ * after the params have been encoded, and says nothing about how to get a
24362
+ * signer onto THIS object.
24363
+ */
24364
+ const READ_ONLY_MESSAGE = 'Kasu: this instance is read-only; call kasu.connect(signer) first';
24365
+
24354
24366
  /**
24355
24367
  * High-level facade for deposit and withdrawal operations.
24356
24368
  *
@@ -24379,7 +24391,7 @@ class DepositsFacade {
24379
24391
  */
24380
24392
  assertWritable() {
24381
24393
  if (this._isReadOnly) {
24382
- throw new Error('Kasu: this instance is read-only; call kasu.connect(signer) first');
24394
+ throw new Error(READ_ONLY_MESSAGE);
24383
24395
  }
24384
24396
  }
24385
24397
  /**
@@ -24407,49 +24419,1330 @@ class DepositsFacade {
24407
24419
  });
24408
24420
  }
24409
24421
  /**
24410
- * Submit a withdrawal request for a specific stable asset amount.
24422
+ * Submit a withdrawal request for a specific stable asset amount.
24423
+ */
24424
+ withdraw(params) {
24425
+ return __awaiter(this, void 0, void 0, function* () {
24426
+ this.assertWritable();
24427
+ return yield this._userLending.requestWithdrawalInAsset(params.poolId, params.trancheId, params.amount);
24428
+ });
24429
+ }
24430
+ /**
24431
+ * Withdraw the entire balance from a tranche.
24432
+ */
24433
+ withdrawMax(poolId, trancheId, userAddress) {
24434
+ return __awaiter(this, void 0, void 0, function* () {
24435
+ this.assertWritable();
24436
+ return yield this._userLending.requestWithdrawalMax(poolId, trancheId, userAddress);
24437
+ });
24438
+ }
24439
+ /**
24440
+ * Build KYC signature parameters for the Nexera verification flow.
24441
+ *
24442
+ * The integrator is responsible for sending these to their backend,
24443
+ * which obtains the signature from Nexera's signing service.
24444
+ */
24445
+ buildKycParams(userAddress) {
24446
+ return this._userLending.buildKycSignatureParams(userAddress, this._chainId);
24447
+ }
24448
+ /**
24449
+ * Check whether the pool is currently in a clearing period
24450
+ * (deposits/withdrawals are temporarily paused).
24451
+ */
24452
+ isClearingPending(poolId) {
24453
+ return __awaiter(this, void 0, void 0, function* () {
24454
+ return yield this._userLending.isClearingPending(poolId);
24455
+ });
24456
+ }
24457
+ /**
24458
+ * Get the current epoch number.
24459
+ */
24460
+ getCurrentEpoch() {
24461
+ return __awaiter(this, void 0, void 0, function* () {
24462
+ return yield this._userLending.getCurrentEpoch();
24463
+ });
24464
+ }
24465
+ }
24466
+
24467
+ /**
24468
+ * The tiny observable-state kernel both flows are built on.
24469
+ *
24470
+ * Deliberately not a framework store: no React, no signals, no dependency.
24471
+ * A flow is a long asynchronous run that has to publish every transition to
24472
+ * whatever is rendering it, and has to be able to abandon a run that the
24473
+ * consumer walked away from. That is the whole requirement, and it is 60 lines.
24474
+ *
24475
+ * The `generation` counter is the abandonment mechanism. `reset()` bumps it;
24476
+ * an in-flight run captured the previous value, so every later `patch` it
24477
+ * attempts is dropped and every `isCurrent` checkpoint tells it to stop. It is
24478
+ * what makes `reset()` safe to call mid-flight — the run cannot resurrect a
24479
+ * dead state or, worse, drive the UI back into a phase the consumer has left.
24480
+ */
24481
+ class FlowStore {
24482
+ constructor(_initial) {
24483
+ this._initial = _initial;
24484
+ this._generation = 0;
24485
+ this._listeners = new Set();
24486
+ this._state = _initial;
24487
+ }
24488
+ get state() {
24489
+ return this._state;
24490
+ }
24491
+ /** The run token an in-flight pipeline captures at `start()`. */
24492
+ get generation() {
24493
+ return this._generation;
24494
+ }
24495
+ /** False once `reset()` (or a later `start()`) has superseded `token`. */
24496
+ isCurrent(token) {
24497
+ return this._generation === token;
24498
+ }
24499
+ /**
24500
+ * Subscribe to every transition. Returns the unsubscribe function; calling
24501
+ * it twice is harmless.
24502
+ *
24503
+ * Listeners are NOT called on subscribe — read `state` for the current
24504
+ * value. A listener that throws is not allowed to break the pipeline or
24505
+ * starve the listeners registered after it, so throws are swallowed.
24506
+ */
24507
+ subscribe(listener) {
24508
+ this._listeners.add(listener);
24509
+ return () => {
24510
+ this._listeners.delete(listener);
24511
+ };
24512
+ }
24513
+ /**
24514
+ * Merge `next` into the state and notify, unless `token` names a
24515
+ * superseded run.
24516
+ */
24517
+ patch(next, token) {
24518
+ if (token !== undefined && !this.isCurrent(token))
24519
+ return;
24520
+ this._state = Object.assign(Object.assign({}, this._state), next);
24521
+ for (const listener of [...this._listeners]) {
24522
+ try {
24523
+ listener(this._state);
24524
+ }
24525
+ catch (_a) {
24526
+ // A consumer's rendering fault is its own problem; the pipeline
24527
+ // owns real money and keeps going.
24528
+ }
24529
+ }
24530
+ }
24531
+ /**
24532
+ * Back to the initial state, abandoning any in-flight run.
24533
+ *
24534
+ * Subscribers are kept: the consumer that was watching the last run is the
24535
+ * one that will watch the next.
24536
+ */
24537
+ reset() {
24538
+ this._generation += 1;
24539
+ this.patch(this._initial);
24540
+ }
24541
+ /** Claim the next run token. Any earlier run is abandoned. */
24542
+ beginRun() {
24543
+ this._generation += 1;
24544
+ return this._generation;
24545
+ }
24546
+ }
24547
+
24548
+ /**
24549
+ * The run lifecycle both flows share: one run at a time, every transition
24550
+ * published, and a `reset()` that is safe to call in the middle of one.
24551
+ *
24552
+ * `DepositFlow` and `WithdrawFlow` each carried their own copy of this — the
24553
+ * re-entrancy guard, the `try/finally` around the run, `state`, `isRunning`,
24554
+ * `subscribe`, `reset`. Two copies of a guard is two places for a guard to be
24555
+ * wrong, on the money path, which is the same reason the pipelines themselves
24556
+ * moved out of the applications.
24557
+ *
24558
+ * ## The guard and the run token are separate, and both matter
24559
+ *
24560
+ * `_runToken` is the re-entrancy guard: claimed synchronously, before the
24561
+ * first `await`, so a double tap cannot launch two pipelines. The store's
24562
+ * `generation` is the abandonment mechanism: an in-flight run holds the value
24563
+ * it claimed, and every `patch` and `isCurrent` checkpoint it makes after
24564
+ * `reset()` is dropped.
24565
+ *
24566
+ * `reset()` releases the guard IMMEDIATELY rather than waiting for the
24567
+ * abandoned run to notice. It has to: a run parked on a wallet prompt that
24568
+ * never answers is a promise that may never settle, and a consumer that has
24569
+ * left that screen must be able to start a new run in the same tick. The
24570
+ * abandoned run's `finally` therefore releases the guard only if it still
24571
+ * holds it — by then a NEW run may own it, and clearing it there would let a
24572
+ * third run start alongside the second.
24573
+ */
24574
+ class Flow {
24575
+ constructor(initial) {
24576
+ /**
24577
+ * The token of the run currently holding the guard, or `null` when none
24578
+ * does. Not a boolean: releasing the guard has to be attributable to the
24579
+ * run that claimed it.
24580
+ */
24581
+ this._runToken = null;
24582
+ this._store = new FlowStore(initial);
24583
+ }
24584
+ /** The current state. Every transition is also published to `subscribe`. */
24585
+ get state() {
24586
+ return this._store.state;
24587
+ }
24588
+ /** True while a run is in flight, including while parked. */
24589
+ get isRunning() {
24590
+ return this._runToken !== null;
24591
+ }
24592
+ /**
24593
+ * Observe every transition. Returns the unsubscribe function.
24594
+ *
24595
+ * The listener is not called on subscribe; read `state` for the value it
24596
+ * starts from.
24597
+ */
24598
+ subscribe(listener) {
24599
+ return this._store.subscribe(listener);
24600
+ }
24601
+ /**
24602
+ * Run the pipeline. Resolves when it reaches a terminal phase — it does
24603
+ * not reject, because every outcome a consumer can act on is in `state`.
24604
+ *
24605
+ * A second call while one is in flight is a no-op: one submission per
24606
+ * intent, however many times the button is pressed.
24607
+ */
24608
+ start(input) {
24609
+ return __awaiter(this, void 0, void 0, function* () {
24610
+ if (this._runToken !== null)
24611
+ return;
24612
+ this._store.reset();
24613
+ const token = this._store.beginRun();
24614
+ this._runToken = token;
24615
+ try {
24616
+ yield this._run(input, token);
24617
+ }
24618
+ finally {
24619
+ if (this._runToken === token)
24620
+ this._runToken = null;
24621
+ }
24622
+ });
24623
+ }
24624
+ /**
24625
+ * Back to `idle`, abandoning any run in flight: its remaining transitions
24626
+ * are dropped, whatever it is parked on is unparked, and the guard is
24627
+ * released at once so `start()` is accepted in the SAME tick. Subscribers
24628
+ * are kept — the consumer watching the last run is the one watching the
24629
+ * next.
24630
+ */
24631
+ reset() {
24632
+ this._runToken = null;
24633
+ // Bump the generation BEFORE unparking, so the abandoned run's next
24634
+ // checkpoint already reads as superseded.
24635
+ this._store.reset();
24636
+ this._onAbandon();
24637
+ }
24638
+ /**
24639
+ * Hook for a flow that parks: unpark it. Called by `reset()` after the
24640
+ * generation has been bumped, so anything the abandoned run does with the
24641
+ * result is dropped.
24642
+ */
24643
+ _onAbandon() {
24644
+ // A flow with nothing parked has nothing to unpark.
24645
+ }
24646
+ }
24647
+
24648
+ /** Narrow the backend's loose `contractType` string to the encoded union. */
24649
+ function asContractType(raw) {
24650
+ return raw === 'exempt' ? 'exempt' : 'retail';
24651
+ }
24652
+ /**
24653
+ * Parse the server's JSON-string `formattedMessage` into a tree. Returns
24654
+ * `null` on parse failure so a renderer can fall back to the plaintext.
24655
+ */
24656
+ function parseFormattedMessage(raw) {
24657
+ try {
24658
+ const parsed = JSON.parse(raw);
24659
+ if (parsed && typeof parsed === 'object')
24660
+ return parsed;
24661
+ return null;
24662
+ }
24663
+ catch (_a) {
24664
+ return null;
24665
+ }
24666
+ }
24667
+ // ---------------------------------------------------------------------------
24668
+ // The on-chain `depositData` blob
24669
+ // ---------------------------------------------------------------------------
24670
+ /**
24671
+ * Pack the contract version and type into the `versionType` word.
24672
+ *
24673
+ * ```
24674
+ * high byte = contract version (>= 1)
24675
+ * low byte = 0 for retail, 1 for exempt
24676
+ * ```
24677
+ */
24678
+ function buildContractVersionType(contractVersion, contractType) {
24679
+ return (contractVersion << 8) + (contractType === 'retail' ? 0 : 1);
24680
+ }
24681
+ /**
24682
+ * Build the on-chain `depositData` blob that `requestDepositWithKyc` expects.
24683
+ *
24684
+ * The KasuController decodes the bytes as
24685
+ * `(bytes signature, uint256 timestamp, uint256 versionType)` and uses the
24686
+ * embedded acceptance signature to verify — retrospectively, via the
24687
+ * agreements service `/contract/resolve` — that the lender signed the
24688
+ * loan-contract text. The ABI tuple and the packing are consensus-critical:
24689
+ * these bytes go on chain.
24690
+ *
24691
+ * kasu-ui encodes this with viem, kasu-mobile with ethers v5 (viem is not
24692
+ * available on Expo). This is the ethers v5 implementation, and
24693
+ * `loan-contract.test.ts` pins its output byte-for-byte against fixtures
24694
+ * produced by the viem version, so the two apps can never diverge here.
24695
+ *
24696
+ * @param args.signature EIP-191 signature from the lender accepting
24697
+ * `contractMessage`, as a 0x-prefixed hex string.
24698
+ * @param args.timestamp ms-epoch from the contract response.
24699
+ */
24700
+ function encodeDepositData(args) {
24701
+ const versionType = buildContractVersionType(args.contractVersion, args.contractType);
24702
+ return ethers.utils.defaultAbiCoder.encode(['bytes', 'uint256', 'uint256'], [
24703
+ args.signature,
24704
+ ethers.BigNumber.from(args.timestamp),
24705
+ ethers.BigNumber.from(versionType),
24706
+ ]);
24707
+ }
24708
+ // ---------------------------------------------------------------------------
24709
+ // The signed messages
24710
+ // ---------------------------------------------------------------------------
24711
+ const MONTH_NAMES = [
24712
+ 'January',
24713
+ 'February',
24714
+ 'March',
24715
+ 'April',
24716
+ 'May',
24717
+ 'June',
24718
+ 'July',
24719
+ 'August',
24720
+ 'September',
24721
+ 'October',
24722
+ 'November',
24723
+ 'December',
24724
+ ];
24725
+ /**
24726
+ * Format a unix timestamp as `{day} {MonthName} {yyyy}, {HH}:{mm}` in UTC.
24727
+ * Day is non-padded; hour and minute are zero-padded to two digits (24h). A
24728
+ * timestamp with >= 13 digits is treated as milliseconds, otherwise as seconds
24729
+ * — the same auto-detection kasu-backend applies.
24730
+ *
24731
+ * Deliberately a manual formatter with English month names: no locale, no
24732
+ * `Intl`, so the output is byte-identical across runtimes and time zones. This
24733
+ * is not a display date. It goes inside a signed message.
24734
+ *
24735
+ * e.g. 1785313320000 → `"29 July 2026, 08:22"`
24736
+ */
24737
+ function formatSignTimestampUtc(timestamp) {
24738
+ const ms = timestamp.toString().length >= 13 ? timestamp : timestamp * 1000;
24739
+ const date = new Date(ms);
24740
+ const day = date.getUTCDate();
24741
+ const month = MONTH_NAMES[date.getUTCMonth()];
24742
+ const year = date.getUTCFullYear();
24743
+ const hours = String(date.getUTCHours()).padStart(2, '0');
24744
+ const minutes = String(date.getUTCMinutes()).padStart(2, '0');
24745
+ return `${day} ${month} ${year}, ${hours}:${minutes}`;
24746
+ }
24747
+ /**
24748
+ * The 4-line human-readable message a lender signs to generate their loan
24749
+ * agreement for review — `POST /contract/generate`.
24750
+ *
24751
+ * ⚠️ BYTE-EXACT PROTOCOL STRING. kasu-backend rebuilds this string from the
24752
+ * request body and verifies the signature against it, so the wording,
24753
+ * ordering, separators, line breaks and date format are all part of the wire
24754
+ * contract. The separator between the line-2 fields is a MIDDLE DOT U+00B7
24755
+ * (·) with a single space on each side; the four lines are joined with `\n`.
24756
+ *
24757
+ * The backend takes this format only when all four display fields are present
24758
+ * and non-empty, and it cross-checks `amountLabel`'s leading number against
24759
+ * the `depositAmount` it was sent (thousands separators stripped) — a message
24760
+ * that states an amount other than the one being executed is refused.
24761
+ */
24762
+ function buildLoanAgreementSignMessage(p) {
24763
+ return [
24764
+ 'Generate my Loan Agreement for review:',
24765
+ `${p.strategyName} · ${p.region} · ${p.optionName} · ${p.amountLabel}.`,
24766
+ `Request made ${formatSignTimestampUtc(p.timestamp)} UTC.`,
24767
+ 'This request does not commit me to lend.',
24768
+ ].join('\n');
24769
+ }
24770
+ /**
24771
+ * The legacy `/contract/generate` and `/contract/resolve` message.
24772
+ *
24773
+ * ⚠️ BYTE-EXACT PROTOCOL STRING. kasu-backend rebuilds it as
24774
+ * `` `I request contract content for ${address} at ${timestamp}.` `` from the
24775
+ * `address` and `timestamp` fields of the request body — so the string signed
24776
+ * and the body sent must agree exactly, INCLUDING the address casing. This
24777
+ * builder lowercases, and the request body must carry the same lowercased
24778
+ * address; that is what both apps signing this format do today.
24779
+ *
24780
+ * The backend takes this path whenever the four human-readable display fields
24781
+ * are absent, and documents it as permanent until the legacy app is
24782
+ * decommissioned. `/contract/resolve` has no other format — every consumer
24783
+ * signs this one to retrieve an existing agreement.
24784
+ *
24785
+ * @param timestampMs ms-epoch, and the same value sent as the body's
24786
+ * `timestamp`.
24787
+ */
24788
+ function buildLegacyContractRequestMessage(address, timestampMs) {
24789
+ return `I request contract content for ${address.toLowerCase()} at ${timestampMs}.`;
24790
+ }
24791
+ /**
24792
+ * The `POST /contract/fullname` message.
24793
+ *
24794
+ * ⚠️ BYTE-EXACT PROTOCOL STRING, on the same terms as
24795
+ * `buildLegacyContractRequestMessage`: kasu-backend rebuilds
24796
+ * `` `I request my full name for ${address} at ${timestamp}.` `` from the
24797
+ * request body and verifies the signature against it, so the body must carry
24798
+ * the same lowercased address this builder signs.
24799
+ *
24800
+ * @param timestampMs ms-epoch, and the same value sent as the body's
24801
+ * `timestamp`.
24802
+ */
24803
+ function buildFullNameRequestMessage(address, timestampMs) {
24804
+ return `I request my full name for ${address.toLowerCase()} at ${timestampMs}.`;
24805
+ }
24806
+
24807
+ // ---------------------------------------------------------------------------
24808
+ // The selector tables
24809
+ // ---------------------------------------------------------------------------
24810
+ /**
24811
+ * OpenZeppelin v5's ERC-20 errors. They are not in either Kasu ABI because no
24812
+ * Kasu contract declares them — they arrive from the TOKEN, through the
24813
+ * manager's `transferFrom`, and they are the modern spelling of the string
24814
+ * reverts below.
24815
+ */
24816
+ const ERC20_ERROR_ABI = [
24817
+ 'error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed)',
24818
+ 'error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed)',
24819
+ ];
24820
+ /**
24821
+ * The protocol errors that mean the ERC-20 transfer failed rather than the
24822
+ * protocol refusing.
24823
+ *
24824
+ * `SafeERC20FailedOperation` is OpenZeppelin's wrapper around a token call
24825
+ * that returned false or reverted, which on this path IS the `transferFrom`;
24826
+ * `AddressInsufficientBalance` is its native-value sibling. Both belong with
24827
+ * the balance case, not with the pool conditions — a lender who sees one of
24828
+ * them really does need to fund or re-approve.
24829
+ */
24830
+ const ERC20_FAMILY_NAMES = new Set([
24831
+ 'AddressInsufficientBalance',
24832
+ 'ERC20InsufficientAllowance',
24833
+ 'ERC20InsufficientBalance',
24834
+ 'SafeERC20FailedOperation',
24835
+ ]);
24836
+ /** Solidity's `Error(string)`, the selector every `require` reason arrives under. */
24837
+ const STRING_REVERT_SELECTOR = '0x08c379a0';
24838
+ /**
24839
+ * The `require` reasons that are a balance or an allowance, across the token
24840
+ * implementations in circulation: OpenZeppelin v4's sentences, and the
24841
+ * shorthand the minimal implementations use.
24842
+ */
24843
+ const ERC20_REASON_PATTERNS = [
24844
+ /exceeds\s+balance/,
24845
+ /exceeds\s+allowance/,
24846
+ /insufficient\s+balance/,
24847
+ /insufficient\s+allowance/,
24848
+ /transfer_from_failed/,
24849
+ /transferfrom\s+failed/,
24850
+ /low-level\s+call\s+failed/,
24851
+ ];
24852
+ /**
24853
+ * selector → error name, built once on first use.
24854
+ *
24855
+ * Lazily, because a consumer that never sees a revert should not pay for three
24856
+ * `Interface` constructions at import. The two Kasu tables are the GENERATED
24857
+ * typechain ABIs, so this cannot drift from the contracts: regenerate the ABIs
24858
+ * and the new errors are recognised with no edit here.
24859
+ */
24860
+ let selectorTable = null;
24861
+ function selectors() {
24862
+ if (selectorTable)
24863
+ return selectorTable;
24864
+ const table = new Map();
24865
+ const interfaces = [
24866
+ // The manager the deposit is called against, and the allow list it
24867
+ // delegates the KYC and block-window checks to.
24868
+ ILendingPoolManagerAbi__factory.createInterface(),
24869
+ IKasuAllowListAbi__factory.createInterface(),
24870
+ new ethers.utils.Interface(ERC20_ERROR_ABI),
24871
+ ];
24872
+ for (const iface of interfaces) {
24873
+ for (const fragment of Object.values(iface.errors)) {
24874
+ // First writer wins: the same name declared by both ABIs is the
24875
+ // same selector, so the duplicate would be a no-op anyway.
24876
+ const sighash = iface.getSighash(fragment);
24877
+ if (!table.has(sighash))
24878
+ table.set(sighash, fragment.name);
24879
+ }
24880
+ }
24881
+ selectorTable = table;
24882
+ return table;
24883
+ }
24884
+ // ---------------------------------------------------------------------------
24885
+ // Getting the bytes out of the envelope
24886
+ // ---------------------------------------------------------------------------
24887
+ /**
24888
+ * How deep to look for the revert data. Providers nest it differently —
24889
+ * ethers' own error wraps the provider's, which wraps the RPC body — and a
24890
+ * bound is what keeps a self-referencing error object from being walked
24891
+ * forever.
24892
+ */
24893
+ const MAX_DEPTH = 6;
24894
+ /** The keys ethers and the providers under it put a wrapped error on. */
24895
+ const NESTED_KEYS = [
24896
+ 'data',
24897
+ 'error',
24898
+ 'originalError',
24899
+ 'info',
24900
+ 'cause',
24901
+ 'body',
24902
+ ];
24903
+ /** At least a 4-byte selector, and a whole number of bytes. */
24904
+ function isRevertData(value) {
24905
+ return (value.length >= 10 &&
24906
+ value.length % 2 === 0 &&
24907
+ /^0x[0-9a-fA-F]+$/.test(value));
24908
+ }
24909
+ /**
24910
+ * Find the revert data on an error, wherever the provider left it.
24911
+ *
24912
+ * ethers v5 raises `UNPREDICTABLE_GAS_LIMIT` with the provider's own error
24913
+ * attached, and each provider nests the bytes one layer differently:
24914
+ * `error.data`, `error.error.data`, `error.data.originalError.data`, or only
24915
+ * inside the JSON `body` of a `SERVER_ERROR`. Rather than enumerate the
24916
+ * products, walk a fixed set of keys to a fixed depth and take the first value
24917
+ * that is shaped like revert data.
24918
+ */
24919
+ function extractRevertData(err) {
24920
+ return walk(err, 0);
24921
+ }
24922
+ function walk(node, depth) {
24923
+ if (node == null || depth > MAX_DEPTH)
24924
+ return null;
24925
+ if (typeof node === 'string') {
24926
+ if (isRevertData(node))
24927
+ return node;
24928
+ // A `SERVER_ERROR`'s body: the RPC's JSON reply, verbatim.
24929
+ if (!node.startsWith('{'))
24930
+ return null;
24931
+ try {
24932
+ return walk(JSON.parse(node), depth + 1);
24933
+ }
24934
+ catch (_a) {
24935
+ return null;
24936
+ }
24937
+ }
24938
+ if (typeof node !== 'object')
24939
+ return null;
24940
+ const record = node;
24941
+ for (const key of NESTED_KEYS) {
24942
+ const found = walk(record[key], depth + 1);
24943
+ if (found)
24944
+ return found;
24945
+ }
24946
+ return null;
24947
+ }
24948
+ // ---------------------------------------------------------------------------
24949
+ // Decoding
24950
+ // ---------------------------------------------------------------------------
24951
+ /**
24952
+ * Decode a failed call's revert into the error the contract named, or `null`
24953
+ * when there is nothing recognisable to name.
24954
+ *
24955
+ * `null` is the honest answer for an unknown selector, an unrelated `require`
24956
+ * string, or an error with no revert data at all — the caller keeps whatever
24957
+ * it did before rather than inventing a diagnosis from bytes it cannot read.
24958
+ */
24959
+ function decodeRevert(err) {
24960
+ const data = extractRevertData(err);
24961
+ if (!data)
24962
+ return null;
24963
+ const selector = data.slice(0, 10).toLowerCase();
24964
+ if (selector === STRING_REVERT_SELECTOR) {
24965
+ const reason = decodeStringRevert(data);
24966
+ if (reason === null)
24967
+ return null;
24968
+ return isErc20Reason(reason)
24969
+ ? { name: 'Error', family: 'erc20', reason }
24970
+ : null;
24971
+ }
24972
+ const name = selectors().get(selector);
24973
+ if (!name)
24974
+ return null;
24975
+ return {
24976
+ name,
24977
+ family: ERC20_FAMILY_NAMES.has(name) ? 'erc20' : 'protocol',
24978
+ };
24979
+ }
24980
+ function decodeStringRevert(data) {
24981
+ try {
24982
+ const [reason] = ethers.utils.defaultAbiCoder.decode(['string'], `0x${data.slice(10)}`);
24983
+ return reason;
24984
+ }
24985
+ catch (_a) {
24986
+ return null;
24987
+ }
24988
+ }
24989
+ function isErc20Reason(reason) {
24990
+ const lower = reason.toLowerCase();
24991
+ return ERC20_REASON_PATTERNS.some((pattern) => pattern.test(lower));
24992
+ }
24993
+
24994
+ /**
24995
+ * Wallet and RPC error predicates — pure functions over `unknown`.
24996
+ *
24997
+ * Every consumer has to tell three things apart when a write fails: the lender
24998
+ * changed their mind, the call would revert, and everything else. The first
24999
+ * two must never be reported as a failure the lender should retry or contact
25000
+ * support about, and each wallet spells them differently, so the shapes are
25001
+ * enumerated once here.
25002
+ *
25003
+ * Lifted from kasu-ui's `src/lib/web3/is-user-rejected.ts` and kasu-mobile's
25004
+ * `src/features/lending/lib/errors.ts` — and now the UNION of the two, so
25005
+ * neither app has to keep a wrapper on top of this one.
25006
+ */
25007
+ /**
25008
+ * Did the lender reject the request in their wallet?
25009
+ *
25010
+ * Providers surface a rejection in different shapes, and the union of them is
25011
+ * the point of this function existing once:
25012
+ * - MetaMask and most EIP-1193 wallets: `code: 4001`
25013
+ * - Coinbase Wallet and ethers v5: `code: 'ACTION_REJECTED'`
25014
+ * - viem: a `UserRejectedRequestError` name
25015
+ * - WalletConnect and some Privy paths: `Error('User rejected the request')`
25016
+ * - a provider error WRAPPED by another layer, carrying the real code and
25017
+ * message on a nested `error` — the shape Privy's embedded wallet
25018
+ * surfaces on Expo, where the outer object says nothing useful
25019
+ * - ethers' own `reason` field, which is often the only place the text lands
25020
+ * - a PLAIN OBJECT carrying `message`, which `String(err)` would read as
25021
+ * `"[object Object]"`
25022
+ *
25023
+ * Previously kasu-ui's implementation verbatim, with kasu-mobile keeping its
25024
+ * own superset on top. That is precisely the drift this layer exists to stop —
25025
+ * a rejection kasu-mobile recognised and kasu-ui did not was reported to the
25026
+ * same lender as a failure on one app and a cancellation on the other. The
25027
+ * union lives here; the mobile wrapper goes.
25028
+ *
25029
+ * ## The text is read for a SUBJECT, not for a keyword
25030
+ *
25031
+ * The words alone are not the signal. "Declined" and "request rejected" are
25032
+ * also what a rate limiter, a risk engine and a KYC decision say, and those
25033
+ * arrive wrapped in exactly the same envelope a wallet error does — ethers'
25034
+ * `SERVER_ERROR` around `-32603` carries the upstream body on a nested
25035
+ * `error.message`, so `{ error: { message: 'request rejected: rate limit
25036
+ * exceeded' } }` is an RPC refusing to serve us, not a lender refusing to
25037
+ * sign. Reporting one as the other tells a lender they cancelled something
25038
+ * they never saw, and DROPS the real error on the floor.
25039
+ *
25040
+ * So a rejection is a machine-readable wallet code, or a sentence that names
25041
+ * the party who did it: "user rejected", "declined by the user", "cancelled by
25042
+ * the wallet". A bare "declined" is not a rejection, whatever else is on the
25043
+ * envelope.
25044
+ *
25045
+ * Within that rule, being generous is the safe direction: calling a genuine
25046
+ * fault a cancellation costs a lender one retry, while calling a deliberate
25047
+ * rejection a failure sends them to support to report a bug that does not
25048
+ * exist.
25049
+ */
25050
+ function isUserRejected(err) {
25051
+ var _a;
25052
+ if (!err)
25053
+ return false;
25054
+ if (typeof err === 'object') {
25055
+ const e = err;
25056
+ if (isRejectionCode(e.code))
25057
+ return true;
25058
+ // A wrapped provider error: the outer layer's code is its own, the
25059
+ // inner one is the wallet's.
25060
+ if (isRejectionCode((_a = e.error) === null || _a === void 0 ? void 0 : _a.code))
25061
+ return true;
25062
+ }
25063
+ const lower = rejectionText(err).toLowerCase();
25064
+ return USER_REJECTION_PATTERNS.some((pattern) => pattern.test(lower));
25065
+ }
25066
+ function isRejectionCode(code) {
25067
+ return code === 4001 || code === 'ACTION_REJECTED';
25068
+ }
25069
+ /**
25070
+ * The wordings that name the wallet or the person at it.
25071
+ *
25072
+ * Each one carries a SUBJECT — the identifier a wallet library uses, or the
25073
+ * verb with the party who performed it. That is what separates a lender
25074
+ * pressing Reject from a server declining to answer, and it is why none of
25075
+ * these is a bare "declined" or "rejected".
25076
+ */
25077
+ const USER_REJECTION_PATTERNS = [
25078
+ // Machine-readable markers that only a wallet layer emits, arriving as
25079
+ // text because something in between stringified the error.
25080
+ /action_rejected/,
25081
+ /user_rejected/,
25082
+ /userrejectedrequest/,
25083
+ // "the user did it", in the orders the wallets write it.
25084
+ /user\s+(?:has\s+)?(?:rejected|denied|declined|refused|cancell?ed)/,
25085
+ /(?:rejected|denied|declined|refused|cancell?ed)\s+by\s+(?:the\s+)?(?:user|wallet|signer|owner)/,
25086
+ // The wallet as the subject, which is how some embedded wallets word it.
25087
+ /(?:wallet|signer)\s+(?:rejected|denied|declined|refused)/,
25088
+ ];
25089
+ /**
25090
+ * Every place a wallet might have put the words: the message, ethers' `reason`,
25091
+ * the error's `name` (viem puts the whole signal there), and a wrapped error's
25092
+ * own three. Joined rather than picked, because which one carries the text
25093
+ * depends on how many layers wrapped it.
25094
+ *
25095
+ * A separator is used rather than a bare space: two fields must not be able to
25096
+ * form a phrase across the join that neither of them said.
25097
+ */
25098
+ function rejectionText(err) {
25099
+ var _a, _b, _c;
25100
+ if (typeof err !== 'object' || err === null)
25101
+ return String(err);
25102
+ const e = err;
25103
+ return [
25104
+ e.message,
25105
+ e.reason,
25106
+ e.name,
25107
+ (_a = e.error) === null || _a === void 0 ? void 0 : _a.message,
25108
+ (_b = e.error) === null || _b === void 0 ? void 0 : _b.reason,
25109
+ (_c = e.error) === null || _c === void 0 ? void 0 : _c.name,
25110
+ ]
25111
+ .filter((part) => typeof part === 'string')
25112
+ .join(' | ');
25113
+ }
25114
+ /**
25115
+ * Did the wallet or RPC signal that the on-chain call would revert?
25116
+ *
25117
+ * ethers v5 raises `UNPREDICTABLE_GAS_LIMIT` when gas estimation reverts —
25118
+ * most often an underlying `transferFrom` failing on an insufficient balance
25119
+ * or allowance. Distinct from a rejection: nothing was refused by the lender,
25120
+ * the transaction simply cannot succeed as composed, so the caller should
25121
+ * re-check its preconditions rather than invite a retry.
25122
+ */
25123
+ function isUnpredictableGas(err) {
25124
+ if (!err || typeof err !== 'object')
25125
+ return false;
25126
+ return err.code === 'UNPREDICTABLE_GAS_LIMIT';
25127
+ }
25128
+ /**
25129
+ * The `cancelled` / `failed` split, for a WALLET call on any step of any flow.
25130
+ *
25131
+ * A lender who pressed Reject is not a fault. Reporting one as the other is
25132
+ * how a support queue fills with people who did exactly what they meant to.
25133
+ *
25134
+ * Generic in the step so both flows share one implementation — it was
25135
+ * duplicated byte-for-byte in each of them, which is the same drift this
25136
+ * layer exists to stop, one level up.
25137
+ *
25138
+ * Only pass it an error a WALLET produced. An HTTP port's throw is always a
25139
+ * `failed`: the lender's wallet was not involved in it, so a backend that
25140
+ * happens to word a refusal "declined" must never be shown to them as
25141
+ * something they did.
25142
+ */
25143
+ function classifyWalletFailure(step, err) {
25144
+ return isUserRejected(err)
25145
+ ? { step, reason: 'cancelled' }
25146
+ : { step, reason: 'failed', error: err };
25147
+ }
25148
+
25149
+ /** Generated agreements are valid for five minutes upstream. */
25150
+ const CONTRACT_TTL_MS = 5 * 60 * 1000;
25151
+ /** What a run without a spender, from either source, fails with. */
25152
+ const NO_SPENDER_MESSAGE = 'DepositFlow: no ERC-20 spender; build the flow with kasu.flows.deposit() or pass `spender` on the input';
25153
+ /** What a malformed auth signature fails the generate step with. */
25154
+ const INVALID_AUTH_SIGNATURE_MESSAGE = 'DepositFlow: the wallet returned a malformed authentication signature; expected 65 bytes of 0x-prefixed hex';
25155
+ /** What a malformed acceptance signature fails the confirm step with. */
25156
+ const INVALID_ACCEPTANCE_SIGNATURE_MESSAGE = 'DepositFlow: the wallet returned a malformed acceptance signature; expected 65 bytes of 0x-prefixed hex';
25157
+ /**
25158
+ * Is this an EIP-191 personal sign, in the only shape the protocol accepts?
25159
+ *
25160
+ * 65 bytes — `r`, `s`, `v` — 0x-prefixed. Nothing downstream checks it: the
25161
+ * ABI coder takes any even-length hex as `bytes`, so `'0x'` and a 64-byte
25162
+ * string both encode happily into a `depositData` the agreements service then
25163
+ * cannot verify against anything. The check has to happen where the signature
25164
+ * is taken, which is here.
25165
+ */
25166
+ function isPersonalSignature(signature) {
25167
+ return utils$2.isHexString(signature, 65);
25168
+ }
25169
+ const INITIAL$1 = {
25170
+ phase: 'idle',
25171
+ step: null,
25172
+ stepIndex: 0,
25173
+ stepTotal: 4,
25174
+ approvalRequired: true,
25175
+ contract: null,
25176
+ failure: null,
25177
+ };
25178
+ /** 1-based badge position, with `approve` dropped when it is out of scope. */
25179
+ function stepIndexOf(step, approvalRequired) {
25180
+ const order = approvalRequired
25181
+ ? ['generate', 'confirm', 'approve', 'request']
25182
+ : ['generate', 'confirm', 'request'];
25183
+ return order.indexOf(step) + 1;
25184
+ }
25185
+ function badgeFor(step, approvalRequired) {
25186
+ return {
25187
+ step,
25188
+ stepIndex: stepIndexOf(step, approvalRequired),
25189
+ stepTotal: approvalRequired ? 4 : 3,
25190
+ };
25191
+ }
25192
+ /**
25193
+ * The request step's extra outcomes, in the order the evidence supports.
25194
+ *
25195
+ * A revert is read for WHAT reverted before it is read as a shortfall.
25196
+ * `requestDepositWithKyc` reverts for a whole family of declared reasons —
25197
+ * `LendingPoolIsStopped`, `ClearingIsPending`, `UserNotKycd`, `UserBlocked`,
25198
+ * `UserNotInAllowList`, `InvalidTranche`, `BlockExpired` — and every one of
25199
+ * them used to arrive as `insufficient-balance`, which told a fully funded
25200
+ * lender to top up a wallet that was never short while their pool was simply
25201
+ * mid-clearing. So: a decoded protocol error is `reverted` and names itself.
25202
+ *
25203
+ * Only a token balance or allowance failure — or revert data nothing can
25204
+ * decode, on the `UNPREDICTABLE_GAS_LIMIT` ethers raises for a failed gas
25205
+ * estimate — is still `insufficient-balance`, which is the case that reason
25206
+ * was named for and the one where topping up is genuinely the answer.
25207
+ */
25208
+ function classifyRequest(err) {
25209
+ const revert = decodeRevert(err);
25210
+ if ((revert === null || revert === void 0 ? void 0 : revert.family) === 'protocol') {
25211
+ return {
25212
+ step: 'request',
25213
+ reason: 'reverted',
25214
+ revertError: revert.name,
25215
+ error: err,
25216
+ };
25217
+ }
25218
+ if (revert !== null || isUnpredictableGas(err)) {
25219
+ return { step: 'request', reason: 'insufficient-balance', error: err };
25220
+ }
25221
+ return classifyWalletFailure('request', err);
25222
+ }
25223
+ // ---------------------------------------------------------------------------
25224
+ // The flow
25225
+ // ---------------------------------------------------------------------------
25226
+ class DepositFlow extends Flow {
25227
+ constructor(_ports, opts) {
25228
+ var _a;
25229
+ super(INITIAL$1);
25230
+ this._ports = _ports;
25231
+ /**
25232
+ * The accept handshake. The run parks on this promise; `acceptContract`,
25233
+ * `declineContract` and `reset` each settle it with an `AcceptOutcome`.
25234
+ * Cleared the moment it settles so a stale resolver from an abandoned run
25235
+ * can never leak into the next one.
25236
+ */
25237
+ this._accept = null;
25238
+ /**
25239
+ * The run token that is between `acceptContract()` and the wallet
25240
+ * settling, or `null`.
25241
+ *
25242
+ * A token rather than a boolean, because the flag has to belong to the RUN
25243
+ * that set it: after `reset()` out of a wallet prompt that never answers,
25244
+ * the abandoned run's `finally` may not arrive for minutes, and a boolean
25245
+ * left standing refuses both Accept and Decline on every run after it.
25246
+ * A stale token simply is not the current generation.
25247
+ */
25248
+ this._acceptingFor = null;
25249
+ this._ttlMs = (_a = opts === null || opts === void 0 ? void 0 : opts.contractTtlMs) !== null && _a !== void 0 ? _a : CONTRACT_TTL_MS;
25250
+ this._defaultSpender = opts === null || opts === void 0 ? void 0 : opts.spender;
25251
+ // Called through the ports object, never captured off it: a consumer
25252
+ // whose clock is a method on its own object keeps its `this`.
25253
+ this._now = () => { var _a, _b; return (_b = (_a = _ports.now) === null || _a === void 0 ? void 0 : _a.call(_ports)) !== null && _b !== void 0 ? _b : Date.now(); };
25254
+ }
25255
+ /**
25256
+ * Sign the agreement and resume the parked run. A no-op when nothing is
25257
+ * parked, so a double tap cannot sign twice.
25258
+ */
25259
+ acceptContract() {
25260
+ return __awaiter(this, void 0, void 0, function* () {
25261
+ const bridge = this._accept;
25262
+ const contract = this._store.state.contract;
25263
+ if (!bridge || !contract || this._isAccepting())
25264
+ return;
25265
+ const token = this._store.generation;
25266
+ this._acceptingFor = token;
25267
+ this._store.patch(Object.assign({ phase: 'accepting-sign' }, badgeFor('confirm', this._store.state.approvalRequired)), token);
25268
+ try {
25269
+ const signature = yield this._ports.signMessage(contract.contractMessage);
25270
+ // Checked HERE, not at the encoder: this is the signature the
25271
+ // agreements service verifies the deposit against, and a wallet
25272
+ // that returned something other than 65 bytes has not signed
25273
+ // anything. Failing the confirm step names the step that produced
25274
+ // it; letting it through would put an unverifiable blob on chain.
25275
+ if (!isPersonalSignature(signature)) {
25276
+ bridge.settle({
25277
+ kind: 'failed',
25278
+ error: new Error(INVALID_ACCEPTANCE_SIGNATURE_MESSAGE),
25279
+ });
25280
+ return;
25281
+ }
25282
+ bridge.settle({ kind: 'accepted', signature });
25283
+ }
25284
+ catch (err) {
25285
+ // A WALLET error, and the only one this flow classifies as a
25286
+ // possible cancellation on the confirm step.
25287
+ bridge.settle({ kind: 'failed', error: err });
25288
+ }
25289
+ finally {
25290
+ // Only if this run still holds it: a `reset()` during the prompt
25291
+ // may have started another one, and that one's flag is its own.
25292
+ if (this._acceptingFor === token)
25293
+ this._acceptingFor = null;
25294
+ }
25295
+ });
25296
+ }
25297
+ /**
25298
+ * Back out of the agreement. The run ends on `declined` — a legitimate
25299
+ * choice, not a failure, and `state.failure` stays null.
25300
+ *
25301
+ * Ignored once `acceptContract()` has opened the wallet: an agreement in
25302
+ * the middle of being signed cannot also be refused. `reset()` is the way
25303
+ * out of a prompt that never answers.
25304
+ */
25305
+ declineContract() {
25306
+ const bridge = this._accept;
25307
+ if (!bridge || this._isAccepting())
25308
+ return;
25309
+ this._accept = null;
25310
+ bridge.settle({ kind: 'declined' });
25311
+ }
25312
+ /** True only while THIS generation is waiting on the acceptance signature. */
25313
+ _isAccepting() {
25314
+ return (this._acceptingFor !== null &&
25315
+ this._store.isCurrent(this._acceptingFor));
25316
+ }
25317
+ /** `reset()`: unpark the abandoned run and drop its handshake. */
25318
+ _onAbandon() {
25319
+ const bridge = this._accept;
25320
+ this._accept = null;
25321
+ this._acceptingFor = null;
25322
+ bridge === null || bridge === void 0 ? void 0 : bridge.settle({ kind: 'abandoned' });
25323
+ }
25324
+ // -----------------------------------------------------------------------
25325
+ _run(input, token) {
25326
+ return __awaiter(this, void 0, void 0, function* () {
25327
+ var _a;
25328
+ this._accept = null;
25329
+ this._acceptingFor = null;
25330
+ const ports = this._ports;
25331
+ const owner = input.userAddress.toLowerCase();
25332
+ // 0. The spender, from the input or from the chain config the facade
25333
+ // built this flow with. Without one there is nothing to read an
25334
+ // allowance against and nothing to approve — and guessing would
25335
+ // grant an approval to the wrong contract.
25336
+ const spender = (_a = input.spender) !== null && _a !== void 0 ? _a : this._defaultSpender;
25337
+ if (!spender) {
25338
+ this._fail(token, true, {
25339
+ step: 'generate',
25340
+ reason: 'failed',
25341
+ error: new Error(NO_SPENDER_MESSAGE),
25342
+ });
25343
+ return;
25344
+ }
25345
+ // 1. Allowance pre-check. Decides `approvalRequired` — and therefore
25346
+ // the badge total — before the lender is shown a single step. Read
25347
+ // live, never cached: an exact-amount approval is fully consumed by
25348
+ // the deposit it paid for, so a stale allowance is exactly the value
25349
+ // that would wrongly skip the approve and revert the deposit.
25350
+ let approvalRequired = true;
25351
+ try {
25352
+ const allowance = yield ports.readAllowance(owner, spender);
25353
+ approvalRequired = allowance.lt(input.amount);
25354
+ }
25355
+ catch (_b) {
25356
+ // A read failure is not a reason to skip an approval. Assume one is
25357
+ // needed: the cost is a redundant approve, the alternative is a
25358
+ // reverted deposit.
25359
+ approvalRequired = true;
25360
+ }
25361
+ if (!this._store.isCurrent(token))
25362
+ return;
25363
+ // 2. Generate — sign the auth message.
25364
+ this._store.patch(Object.assign({ approvalRequired, phase: 'generating-sign' }, badgeFor('generate', approvalRequired)), token);
25365
+ const timestamp = this._now();
25366
+ const signedMessage = buildAuthMessage(input, owner, timestamp);
25367
+ let signature;
25368
+ try {
25369
+ signature = yield ports.signMessage(signedMessage);
25370
+ }
25371
+ catch (err) {
25372
+ this._fail(token, approvalRequired, classifyWalletFailure('generate', err));
25373
+ return;
25374
+ }
25375
+ // The same EIP-191 shape as the acceptance, and the same reason to
25376
+ // check it: kasu-backend verifies this one to decide whether to issue
25377
+ // an agreement at all, so a malformed signature is a 4xx that says
25378
+ // nothing about which step produced it. Named here instead.
25379
+ if (!isPersonalSignature(signature)) {
25380
+ this._fail(token, approvalRequired, {
25381
+ step: 'generate',
25382
+ reason: 'failed',
25383
+ error: new Error(INVALID_AUTH_SIGNATURE_MESSAGE),
25384
+ });
25385
+ return;
25386
+ }
25387
+ if (!this._store.isCurrent(token))
25388
+ return;
25389
+ // 3. Generate — POST the request.
25390
+ this._store.patch(Object.assign({ phase: 'generating-fetch' }, badgeFor('generate', approvalRequired)), token);
25391
+ let contract;
25392
+ try {
25393
+ contract = yield ports.generateContract(Object.assign({ address: owner, signature,
25394
+ timestamp,
25395
+ signedMessage, poolId: input.poolId, trancheId: input.trancheId, fixedTermConfigId: input.fixedTermConfigId, depositAmount: input.depositAmount }, displayFieldsOf(input.contractMessage)));
25396
+ }
25397
+ catch (err) {
25398
+ // Never a wallet rejection: this step is an HTTP call, and the
25399
+ // lender's wallet was not involved in it. A backend that happened
25400
+ // to echo the words "user rejected" must not be reported to them as
25401
+ // something they did.
25402
+ this._fail(token, approvalRequired, {
25403
+ step: 'generate',
25404
+ reason: 'failed',
25405
+ error: err,
25406
+ });
25407
+ return;
25408
+ }
25409
+ if (!this._store.isCurrent(token))
25410
+ return;
25411
+ // 4. Park on the agreement until the consumer accepts or declines.
25412
+ const outcome = yield new Promise((resolve) => {
25413
+ this._accept = { settle: resolve };
25414
+ this._store.patch(Object.assign({ phase: 'awaiting-accept', contract }, badgeFor('confirm', approvalRequired)), token);
25415
+ });
25416
+ this._accept = null;
25417
+ // An abandoned run lands here too — `reset()` unparks it. The token
25418
+ // check is what tells the two apart.
25419
+ if (!this._store.isCurrent(token))
25420
+ return;
25421
+ if (outcome.kind === 'declined') {
25422
+ this._store.patch(Object.assign({ phase: 'declined' }, badgeFor('confirm', approvalRequired)), token);
25423
+ return;
25424
+ }
25425
+ if (outcome.kind !== 'accepted') {
25426
+ if (outcome.kind === 'failed') {
25427
+ this._fail(token, approvalRequired, classifyWalletFailure('confirm', outcome.error));
25428
+ }
25429
+ return;
25430
+ }
25431
+ // 5. TTL guard. Checked here because this is where the idling happens:
25432
+ // the lender has just spent as long as they wanted reading. An
25433
+ // expired agreement is refused rather than broadcast — the on-chain
25434
+ // call would revert, after a wallet prompt and a gas estimate, with
25435
+ // nothing on screen explaining why.
25436
+ if (this._now() > contract.timestamp + this._ttlMs) {
25437
+ this._fail(token, approvalRequired, {
25438
+ step: 'request',
25439
+ reason: 'contract-expired',
25440
+ });
25441
+ return;
25442
+ }
25443
+ // The acceptance signature is already known to be 65 bytes, but the
25444
+ // encoder also reads `timestamp`, `contractVersion` and
25445
+ // `contractType` off a response the SDK did not produce. `start()`
25446
+ // promises it does not reject, so anything that throws in here becomes
25447
+ // a failure the consumer can render rather than an unhandled rejection
25448
+ // in an application that was told it never had to catch one.
25449
+ let depositData;
25450
+ try {
25451
+ depositData = encodeDepositData({
25452
+ signature: outcome.signature,
25453
+ timestamp: contract.timestamp,
25454
+ contractVersion: contract.contractVersion,
25455
+ contractType: asContractType(contract.contractType),
25456
+ });
25457
+ }
25458
+ catch (err) {
25459
+ this._fail(token, approvalRequired, {
25460
+ step: 'request',
25461
+ reason: 'failed',
25462
+ error: err,
25463
+ });
25464
+ return;
25465
+ }
25466
+ // 6. Approve — the EXACT amount, never `MaxUint256`. House rule: an
25467
+ // unlimited allowance outlives the deposit it was granted for, and a
25468
+ // later exploit of the spender would drain a wallet that has long
25469
+ // since stopped lending.
25470
+ if (approvalRequired) {
25471
+ this._store.patch(Object.assign({ phase: 'approve' }, badgeFor('approve', approvalRequired)), token);
25472
+ try {
25473
+ const tx = yield ports.approve(spender, input.amount);
25474
+ yield tx.wait();
25475
+ }
25476
+ catch (err) {
25477
+ this._fail(token, approvalRequired, classifyWalletFailure('approve', err));
25478
+ return;
25479
+ }
25480
+ if (!this._store.isCurrent(token))
25481
+ return;
25482
+ }
25483
+ // 7. Request — KYC signature, then the deposit and its receipt.
25484
+ this._store.patch(Object.assign({ phase: 'request-sign' }, badgeFor('request', approvalRequired)), token);
25485
+ // The two KYC ports reach the consumer's own backend, so they fail the
25486
+ // way the generate step does: `failed`, with the error kept. Running
25487
+ // them through the rejection classifier would let a backend wording —
25488
+ // "Declined", "request rejected" — end a run as "you cancelled in your
25489
+ // wallet", with the real error discarded and nothing to report.
25490
+ let kyc;
25491
+ try {
25492
+ const kycParams = yield ports.buildKycParams(owner);
25493
+ kyc = yield ports.getKycSignature(kycParams);
25494
+ }
25495
+ catch (err) {
25496
+ this._fail(token, approvalRequired, {
25497
+ step: 'request',
25498
+ reason: 'failed',
25499
+ error: err,
25500
+ });
25501
+ return;
25502
+ }
25503
+ if (!this._store.isCurrent(token))
25504
+ return;
25505
+ try {
25506
+ const tx = yield ports.deposit({
25507
+ poolId: input.poolId,
25508
+ trancheId: input.trancheId,
25509
+ amount: input.amount,
25510
+ kycSignature: {
25511
+ blockExpiration: kyc.blockExpiration,
25512
+ signature: kyc.signature,
25513
+ },
25514
+ depositData,
25515
+ fixedTermConfigId: input.fixedTermConfigId,
25516
+ });
25517
+ this._store.patch(Object.assign({ phase: 'request-confirm' }, badgeFor('request', approvalRequired)), token);
25518
+ yield tx.wait();
25519
+ }
25520
+ catch (err) {
25521
+ this._fail(token, approvalRequired, classifyRequest(err));
25522
+ return;
25523
+ }
25524
+ if (!this._store.isCurrent(token))
25525
+ return;
25526
+ this._store.patch(Object.assign({ phase: 'success' }, badgeFor('request', approvalRequired)), token);
25527
+ });
25528
+ }
25529
+ _fail(token, approvalRequired, failure) {
25530
+ this._store.patch(Object.assign({ phase: 'error', failure }, badgeFor(failure.step, approvalRequired)), token);
25531
+ }
25532
+ }
25533
+ // ---------------------------------------------------------------------------
25534
+ // Message building
25535
+ // ---------------------------------------------------------------------------
25536
+ /**
25537
+ * The auth message, in whichever format the consumer asked for. Both builders
25538
+ * are the byte-exact protocol strings from `domain/loan-contract` — the string
25539
+ * signed here and the body posted from `_run` state the SAME timestamp and the
25540
+ * SAME lowercased address, because kasu-backend rebuilds one from the other.
25541
+ */
25542
+ function buildAuthMessage(input, owner, timestamp) {
25543
+ if (input.contractMessage.format === 'legacy') {
25544
+ return buildLegacyContractRequestMessage(owner, timestamp);
25545
+ }
25546
+ const { strategyName, region, optionName, amountLabel } = input.contractMessage;
25547
+ return buildLoanAgreementSignMessage({
25548
+ strategyName,
25549
+ region,
25550
+ optionName,
25551
+ amountLabel,
25552
+ timestamp,
25553
+ });
25554
+ }
25555
+ /**
25556
+ * The four display fields, present only on the new format. The backend picks
25557
+ * its verification path on their presence: all four → the human-readable
25558
+ * format, any missing → the legacy string.
25559
+ */
25560
+ function displayFieldsOf(message) {
25561
+ if (message.format === 'legacy')
25562
+ return {};
25563
+ return {
25564
+ strategyName: message.strategyName,
25565
+ region: message.region,
25566
+ optionName: message.optionName,
25567
+ amountLabel: message.amountLabel,
25568
+ };
25569
+ }
25570
+
25571
+ const INITIAL = {
25572
+ phase: 'idle',
25573
+ step: null,
25574
+ isMax: false,
25575
+ failure: null,
25576
+ };
25577
+ /** What a KYC pre-check with no `buildKycParams` to call fails with. */
25578
+ const NO_KYC_PARAMS_MESSAGE = 'WithdrawFlow: getKycSignature was supplied without buildKycParams; build the flow with kasu.flows.withdraw() or pass both';
25579
+ // ---------------------------------------------------------------------------
25580
+ // The flow
25581
+ // ---------------------------------------------------------------------------
25582
+ class WithdrawFlow extends Flow {
25583
+ constructor(_ports) {
25584
+ super(INITIAL);
25585
+ this._ports = _ports;
25586
+ }
25587
+ _run(input, token) {
25588
+ return __awaiter(this, void 0, void 0, function* () {
25589
+ const ports = this._ports;
25590
+ const isMax = input.amount === 'max';
25591
+ // 1. The optional KYC pre-check: build the params, exchange them for a
25592
+ // signature. Both ports reach the application's own backend, so a
25593
+ // throw here is ALWAYS `failed` — running it through the wallet
25594
+ // rejection classifier would let a backend's "Declined" be reported
25595
+ // to a lender as something they did, with the real error dropped.
25596
+ if (ports.getKycSignature) {
25597
+ this._store.patch({ phase: 'checking-kyc', step: 'kyc', isMax }, token);
25598
+ try {
25599
+ if (!ports.buildKycParams) {
25600
+ throw new Error(NO_KYC_PARAMS_MESSAGE);
25601
+ }
25602
+ const params = yield ports.buildKycParams(input.userAddress);
25603
+ yield ports.getKycSignature(params);
25604
+ }
25605
+ catch (err) {
25606
+ this._store.patch({
25607
+ phase: 'error',
25608
+ failure: { step: 'kyc', reason: 'failed', error: err },
25609
+ }, token);
25610
+ return;
25611
+ }
25612
+ if (!this._store.isCurrent(token))
25613
+ return;
25614
+ }
25615
+ // 2. The submission. This one IS a wallet call, so it keeps the
25616
+ // `cancelled` / `failed` split.
25617
+ this._store.patch({ phase: 'request-sign', step: 'request', isMax }, token);
25618
+ try {
25619
+ const tx = input.amount === 'max'
25620
+ ? yield ports.withdrawMax(input.poolId, input.trancheId, input.userAddress.toLowerCase())
25621
+ : yield ports.withdraw({
25622
+ poolId: input.poolId,
25623
+ trancheId: input.trancheId,
25624
+ amount: input.amount,
25625
+ });
25626
+ this._store.patch({ phase: 'request-confirm' }, token);
25627
+ yield tx.wait();
25628
+ }
25629
+ catch (err) {
25630
+ this._store.patch({
25631
+ phase: 'error',
25632
+ failure: classifyWalletFailure('request', err),
25633
+ }, token);
25634
+ return;
25635
+ }
25636
+ if (!this._store.isCurrent(token))
25637
+ return;
25638
+ this._store.patch({ phase: 'success' }, token);
25639
+ });
25640
+ }
25641
+ }
25642
+
25643
+ /**
25644
+ * Builds `DepositFlow` / `WithdrawFlow` instances wired to THIS Kasu instance:
25645
+ * its chain's stable token, its `LendingPoolManager`, its signer.
25646
+ *
25647
+ * ```ts
25648
+ * const flow = kasu.connect(signer).flows.deposit({
25649
+ * signMessage: (m) => signer.signMessage(m),
25650
+ * generateContract: (req) => postToMyProxy(req),
25651
+ * getKycSignature: (p) => postToMyBackend(p),
25652
+ * });
25653
+ * ```
25654
+ *
25655
+ * A flow built from a read-only instance constructs fine and reads fine — the
25656
+ * write ports throw `READ_ONLY_MESSAGE` when the run reaches them, exactly as
25657
+ * `kasu.deposits.deposit` does. Constructing is not the mistake; submitting is.
25658
+ *
25659
+ * It holds the `DepositsFacade` and NOTHING the facade already owns: no
25660
+ * `UserLending`, no chain id, no signer. Two paths to one behaviour is how the
25661
+ * KYC params a flow built came to differ from the ones `kasu.deposits`
25662
+ * built — the same class of drift the flows themselves exist to end.
25663
+ */
25664
+ class FlowsFacade {
25665
+ constructor(_deposits,
25666
+ /**
25667
+ * The chain's stable token, bound to whatever the Kasu instance holds.
25668
+ * A factory rather than a contract: it is one `new Contract`, and a
25669
+ * cached binding would outlive the config it was built from.
24411
25670
  */
24412
- withdraw(params) {
24413
- return __awaiter(this, void 0, void 0, function* () {
24414
- this.assertWritable();
24415
- return yield this._userLending.requestWithdrawalInAsset(params.poolId, params.trancheId, params.amount);
24416
- });
24417
- }
25671
+ _erc20,
25672
+ /** The read-only flag `Kasu` already computed — never re-derived here. */
25673
+ _isReadOnly,
24418
25674
  /**
24419
- * Withdraw the entire balance from a tranche.
25675
+ * The ERC-20 spender every deposit run approves: this chain's
25676
+ * `LendingPoolManager`, which is the only contract the default deposit
25677
+ * port calls. Passed to the flow so a consumer never has to hand-wire
25678
+ * an address whose only wrong value grants an approval to the wrong
25679
+ * contract.
24420
25680
  */
24421
- withdrawMax(poolId, trancheId, userAddress) {
24422
- return __awaiter(this, void 0, void 0, function* () {
24423
- this.assertWritable();
24424
- return yield this._userLending.requestWithdrawalMax(poolId, trancheId, userAddress);
24425
- });
25681
+ _spender) {
25682
+ this._deposits = _deposits;
25683
+ this._erc20 = _erc20;
25684
+ this._isReadOnly = _isReadOnly;
25685
+ this._spender = _spender;
24426
25686
  }
24427
25687
  /**
24428
- * Build KYC signature parameters for the Nexera verification flow.
25688
+ * A deposit pipeline. `readAllowance`, `approve`, `deposit` and
25689
+ * `buildKycParams` default to the SDK's own implementations; pass any of
25690
+ * them to override (kasu-ui approves through its sponsored-gas path, for
25691
+ * one).
24429
25692
  *
24430
- * The integrator is responsible for sending these to their backend,
24431
- * which obtains the signature from Nexera's signing service.
24432
- */
24433
- buildKycParams(userAddress) {
24434
- return this._userLending.buildKycSignatureParams(userAddress, this._chainId);
24435
- }
24436
- /**
24437
- * Check whether the pool is currently in a clearing period
24438
- * (deposits/withdrawals are temporarily paused).
25693
+ * Each default is applied per key with `??`, not by spreading `ports` over
25694
+ * them: `{ ...defaults, ...ports }` lets an EXPLICITLY undefined value
25695
+ * delete the default it was meant to keep, and
25696
+ * `approve: sponsoredGas ? sponsoredApprove : undefined` is exactly how a
25697
+ * consumer writes a conditional override.
24439
25698
  */
24440
- isClearingPending(poolId) {
24441
- return __awaiter(this, void 0, void 0, function* () {
24442
- return yield this._userLending.isClearingPending(poolId);
25699
+ deposit(ports, opts) {
25700
+ var _a, _b, _c, _d, _e;
25701
+ return new DepositFlow({
25702
+ signMessage: ports.signMessage,
25703
+ generateContract: ports.generateContract,
25704
+ getKycSignature: ports.getKycSignature,
25705
+ buildKycParams: (_a = ports.buildKycParams) !== null && _a !== void 0 ? _a : ((userAddress) => this._deposits.buildKycParams(userAddress)),
25706
+ readAllowance: (_b = ports.readAllowance) !== null && _b !== void 0 ? _b : ((owner, spender) => this._erc20().allowance(owner, spender)),
25707
+ approve: (_c = ports.approve) !== null && _c !== void 0 ? _c : ((spender, amount) => __awaiter(this, void 0, void 0, function* () {
25708
+ this._assertWritable();
25709
+ // The EXACT amount the flow asked for. Nothing here
25710
+ // rounds it up, and nothing here substitutes
25711
+ // MaxUint256.
25712
+ return yield this._erc20().approve(spender, amount);
25713
+ })),
25714
+ deposit: (_d = ports.deposit) !== null && _d !== void 0 ? _d : ((params) => this._deposits.deposit(params)),
25715
+ now: ports.now,
25716
+ }, {
25717
+ contractTtlMs: opts === null || opts === void 0 ? void 0 : opts.contractTtlMs,
25718
+ // Per key here too, for the same reason the ports are: an
25719
+ // explicit `spender: undefined` must not delete the default.
25720
+ spender: (_e = opts === null || opts === void 0 ? void 0 : opts.spender) !== null && _e !== void 0 ? _e : this._spender,
24443
25721
  });
24444
25722
  }
24445
25723
  /**
24446
- * Get the current epoch number.
25724
+ * A withdrawal pipeline. Both write ports and `buildKycParams` default to
25725
+ * this instance; supplying `getKycSignature` turns the KYC pre-check on.
25726
+ * Defaults are applied per key, for the reason `deposit()` gives.
24447
25727
  */
24448
- getCurrentEpoch() {
24449
- return __awaiter(this, void 0, void 0, function* () {
24450
- return yield this._userLending.getCurrentEpoch();
25728
+ withdraw(ports = {}) {
25729
+ var _a, _b, _c;
25730
+ return new WithdrawFlow({
25731
+ buildKycParams: (_a = ports.buildKycParams) !== null && _a !== void 0 ? _a : ((userAddress) => this._deposits.buildKycParams(userAddress)),
25732
+ getKycSignature: ports.getKycSignature,
25733
+ withdraw: (_b = ports.withdraw) !== null && _b !== void 0 ? _b : ((params) => this._deposits.withdraw({
25734
+ poolId: params.poolId,
25735
+ trancheId: params.trancheId,
25736
+ amount: params.amount,
25737
+ })),
25738
+ withdrawMax: (_c = ports.withdrawMax) !== null && _c !== void 0 ? _c : ((poolId, trancheId, userAddress) => this._deposits.withdrawMax(poolId, trancheId, userAddress)),
24451
25739
  });
24452
25740
  }
25741
+ _assertWritable() {
25742
+ if (this._isReadOnly) {
25743
+ throw new Error(READ_ONLY_MESSAGE);
25744
+ }
25745
+ }
24453
25746
  }
24454
25747
 
24455
25748
  /**
@@ -24908,6 +26201,16 @@ function firstSubmissionTimestamp(events, fallback) {
24908
26201
  return fallback;
24909
26202
  return submissions.reduce((min, e) => (e.timestamp < min ? e.timestamp : min), Infinity);
24910
26203
  }
26204
+ /**
26205
+ * The LATEST event timestamp, or `fallback` when the timeline is empty — or
26206
+ * when every event predates it, because `fallback` seeds the reduction. That
26207
+ * seeding is deliberate and is kasu-ui's behaviour: `request.timestamp` is a
26208
+ * fact about the request, and an event indexed with an earlier clock must not
26209
+ * make the row look older than the request itself.
26210
+ */
26211
+ function lastEventTimestamp(events, fallback) {
26212
+ return events.reduce((max, e) => (e.timestamp > max ? e.timestamp : max), fallback);
26213
+ }
24911
26214
  /**
24912
26215
  * Has THIS request's cycle closed? — the single open/closed signal behind the
24913
26216
  * status vocabulary and behind Cancel.
@@ -24991,10 +26294,10 @@ const numOrNull = (str) => {
24991
26294
  * status would strand it.
24992
26295
  *
24993
26296
  * WHAT THE APPLICATION STILL OWNS: the status word and the detail line beneath
24994
- * it; the tranche display rename (`getTrancheDisplayName` on `trancheName`,
24995
- * and on the reallocation destination read off `request.events`); the pool-name
24996
- * split; the amount format. The "view loan agreement" affordance is a fact, and
24997
- * it follows from two fields already here —
26297
+ * it; the tranche display rename (`getTrancheDisplayName` on `trancheName`
26298
+ * and on `reallocationTargetTrancheName`, both of which are RAW here); the
26299
+ * pool-name split; the amount format. The "view loan agreement" affordance is
26300
+ * a fact, and it follows from two fields already here —
24998
26301
  * `requestType === 'Deposit' && statusCode !== 'cancelled' && statusCode !== 'rejected'`
24999
26302
  * — because neither a cancelled nor a fully-rejected deposit ever issued one,
25000
26303
  * and withdrawals sign no agreement at all.
@@ -25029,6 +26332,12 @@ function deriveRequestState(request) {
25029
26332
  initiatedAmount: initiated
25030
26333
  ? initiatedAmountOf(request.events)
25031
26334
  : null,
26335
+ rejectedAmount: rejected,
26336
+ reallocatedOutAmount: reallocation ? num(reallocation.assetAmount) : 0,
26337
+ reallocationTargetTrancheName: reallocation
26338
+ ? reallocation.trancheName
26339
+ : null,
26340
+ lastTimestamp: lastEventTimestamp(request.events, request.timestamp),
25032
26341
  submissionCount: countSubmissions(request.events),
25033
26342
  // `firstSubmissionTimestamp` needs a fallback it will never use here:
25034
26343
  // the bundle is non-empty on every path that reaches the call.
@@ -25148,8 +26457,9 @@ class PortfolioFacade {
25148
26457
  /**
25149
26458
  * High-level entry point for external integrators.
25150
26459
  *
25151
- * Provides three domain facades — `strategies`, `deposits`, `portfolio` — and
25152
- * exposes the underlying `KasuSdk` services via `.services` for power-users.
26460
+ * Provides four domain facades — `strategies`, `deposits`, `portfolio`,
26461
+ * `flows` — and exposes the underlying `KasuSdk` services via `.services` for
26462
+ * power-users.
25153
26463
  *
25154
26464
  * ```ts
25155
26465
  * import { Kasu } from '@kasufinance/kasu-sdk';
@@ -25173,8 +26483,13 @@ class Kasu {
25173
26483
  this._signerOrProvider = signerOrProvider;
25174
26484
  this._configOverrides = configOverrides;
25175
26485
  this.strategies = new StrategiesFacade(sdk.DataService, sdk.UserLending);
25176
- this.deposits = new DepositsFacade(sdk.UserLending, chainConfig.chainId.toString(), !Signer.isSigner(signerOrProvider));
26486
+ // Derived ONCE and handed to every facade that needs it. Each of them
26487
+ // re-deriving `Signer.isSigner` is how two facades come to disagree
26488
+ // about whether the same instance can write.
26489
+ const isReadOnly = !Signer.isSigner(signerOrProvider);
26490
+ this.deposits = new DepositsFacade(sdk.UserLending, chainConfig.chainId.toString(), isReadOnly);
25177
26491
  this.portfolio = new PortfolioFacade(sdk.DataService, sdk.UserLending, sdk.Portfolio);
26492
+ this.flows = new FlowsFacade(this.deposits, () => erc20Of(chainConfig, signerOrProvider), isReadOnly, chainConfig.contracts.LendingPoolManager);
25178
26493
  }
25179
26494
  /**
25180
26495
  * Create a Kasu instance with built-in chain config.
@@ -25306,6 +26621,23 @@ function rpcUrlsOf(chainConfig) {
25306
26621
  var _a;
25307
26622
  return (_a = chainConfig.rpcUrls) !== null && _a !== void 0 ? _a : [];
25308
26623
  }
26624
+ /**
26625
+ * The chain's stable token, bound to whatever this instance holds.
26626
+ *
26627
+ * Built per call rather than cached: it is one `new Contract`, and a cached
26628
+ * binding would outlive the signer a `connect()` replaced. A config with no
26629
+ * `stableAsset` (a hand-written entry from before 2.5.0) throws here rather
26630
+ * than inside ethers, naming the two ports that make the flow work without
26631
+ * one.
26632
+ */
26633
+ function erc20Of(chainConfig, signerOrProvider) {
26634
+ var _a;
26635
+ const address = (_a = stableAssetOf(chainConfig)) === null || _a === void 0 ? void 0 : _a.address;
26636
+ if (!address) {
26637
+ throw new Error('Kasu: this chain config has no stableAsset; pass readAllowance and approve ports explicitly');
26638
+ }
26639
+ return IERC20MetadataAbi__factory.connect(address, signerOrProvider);
26640
+ }
25309
26641
  /**
25310
26642
  * The read-only provider used when the caller passes no `signerOrProvider`.
25311
26643
  *
@@ -25672,165 +27004,6 @@ function getInstitutionalLender(originator) {
25672
27004
  return originator.name === APXIUM.name ? RIXON_CAPITAL : null;
25673
27005
  }
25674
27006
 
25675
- /** Narrow the backend's loose `contractType` string to the encoded union. */
25676
- function asContractType(raw) {
25677
- return raw === 'exempt' ? 'exempt' : 'retail';
25678
- }
25679
- /**
25680
- * Parse the server's JSON-string `formattedMessage` into a tree. Returns
25681
- * `null` on parse failure so a renderer can fall back to the plaintext.
25682
- */
25683
- function parseFormattedMessage(raw) {
25684
- try {
25685
- const parsed = JSON.parse(raw);
25686
- if (parsed && typeof parsed === 'object')
25687
- return parsed;
25688
- return null;
25689
- }
25690
- catch (_a) {
25691
- return null;
25692
- }
25693
- }
25694
- // ---------------------------------------------------------------------------
25695
- // The on-chain `depositData` blob
25696
- // ---------------------------------------------------------------------------
25697
- /**
25698
- * Pack the contract version and type into the `versionType` word.
25699
- *
25700
- * ```
25701
- * high byte = contract version (>= 1)
25702
- * low byte = 0 for retail, 1 for exempt
25703
- * ```
25704
- */
25705
- function buildContractVersionType(contractVersion, contractType) {
25706
- return (contractVersion << 8) + (contractType === 'retail' ? 0 : 1);
25707
- }
25708
- /**
25709
- * Build the on-chain `depositData` blob that `requestDepositWithKyc` expects.
25710
- *
25711
- * The KasuController decodes the bytes as
25712
- * `(bytes signature, uint256 timestamp, uint256 versionType)` and uses the
25713
- * embedded acceptance signature to verify — retrospectively, via the
25714
- * agreements service `/contract/resolve` — that the lender signed the
25715
- * loan-contract text. The ABI tuple and the packing are consensus-critical:
25716
- * these bytes go on chain.
25717
- *
25718
- * kasu-ui encodes this with viem, kasu-mobile with ethers v5 (viem is not
25719
- * available on Expo). This is the ethers v5 implementation, and
25720
- * `loan-contract.test.ts` pins its output byte-for-byte against fixtures
25721
- * produced by the viem version, so the two apps can never diverge here.
25722
- *
25723
- * @param args.signature EIP-191 signature from the lender accepting
25724
- * `contractMessage`, as a 0x-prefixed hex string.
25725
- * @param args.timestamp ms-epoch from the contract response.
25726
- */
25727
- function encodeDepositData(args) {
25728
- const versionType = buildContractVersionType(args.contractVersion, args.contractType);
25729
- return ethers.utils.defaultAbiCoder.encode(['bytes', 'uint256', 'uint256'], [
25730
- args.signature,
25731
- ethers.BigNumber.from(args.timestamp),
25732
- ethers.BigNumber.from(versionType),
25733
- ]);
25734
- }
25735
- // ---------------------------------------------------------------------------
25736
- // The signed messages
25737
- // ---------------------------------------------------------------------------
25738
- const MONTH_NAMES = [
25739
- 'January',
25740
- 'February',
25741
- 'March',
25742
- 'April',
25743
- 'May',
25744
- 'June',
25745
- 'July',
25746
- 'August',
25747
- 'September',
25748
- 'October',
25749
- 'November',
25750
- 'December',
25751
- ];
25752
- /**
25753
- * Format a unix timestamp as `{day} {MonthName} {yyyy}, {HH}:{mm}` in UTC.
25754
- * Day is non-padded; hour and minute are zero-padded to two digits (24h). A
25755
- * timestamp with >= 13 digits is treated as milliseconds, otherwise as seconds
25756
- * — the same auto-detection kasu-backend applies.
25757
- *
25758
- * Deliberately a manual formatter with English month names: no locale, no
25759
- * `Intl`, so the output is byte-identical across runtimes and time zones. This
25760
- * is not a display date. It goes inside a signed message.
25761
- *
25762
- * e.g. 1785313320000 → `"29 July 2026, 08:22"`
25763
- */
25764
- function formatSignTimestampUtc(timestamp) {
25765
- const ms = timestamp.toString().length >= 13 ? timestamp : timestamp * 1000;
25766
- const date = new Date(ms);
25767
- const day = date.getUTCDate();
25768
- const month = MONTH_NAMES[date.getUTCMonth()];
25769
- const year = date.getUTCFullYear();
25770
- const hours = String(date.getUTCHours()).padStart(2, '0');
25771
- const minutes = String(date.getUTCMinutes()).padStart(2, '0');
25772
- return `${day} ${month} ${year}, ${hours}:${minutes}`;
25773
- }
25774
- /**
25775
- * The 4-line human-readable message a lender signs to generate their loan
25776
- * agreement for review — `POST /contract/generate`.
25777
- *
25778
- * ⚠️ BYTE-EXACT PROTOCOL STRING. kasu-backend rebuilds this string from the
25779
- * request body and verifies the signature against it, so the wording,
25780
- * ordering, separators, line breaks and date format are all part of the wire
25781
- * contract. The separator between the line-2 fields is a MIDDLE DOT U+00B7
25782
- * (·) with a single space on each side; the four lines are joined with `\n`.
25783
- *
25784
- * The backend takes this format only when all four display fields are present
25785
- * and non-empty, and it cross-checks `amountLabel`'s leading number against
25786
- * the `depositAmount` it was sent (thousands separators stripped) — a message
25787
- * that states an amount other than the one being executed is refused.
25788
- */
25789
- function buildLoanAgreementSignMessage(p) {
25790
- return [
25791
- 'Generate my Loan Agreement for review:',
25792
- `${p.strategyName} · ${p.region} · ${p.optionName} · ${p.amountLabel}.`,
25793
- `Request made ${formatSignTimestampUtc(p.timestamp)} UTC.`,
25794
- 'This request does not commit me to lend.',
25795
- ].join('\n');
25796
- }
25797
- /**
25798
- * The legacy `/contract/generate` and `/contract/resolve` message.
25799
- *
25800
- * ⚠️ BYTE-EXACT PROTOCOL STRING. kasu-backend rebuilds it as
25801
- * `` `I request contract content for ${address} at ${timestamp}.` `` from the
25802
- * `address` and `timestamp` fields of the request body — so the string signed
25803
- * and the body sent must agree exactly, INCLUDING the address casing. This
25804
- * builder lowercases, and the request body must carry the same lowercased
25805
- * address; that is what both apps signing this format do today.
25806
- *
25807
- * The backend takes this path whenever the four human-readable display fields
25808
- * are absent, and documents it as permanent until the legacy app is
25809
- * decommissioned. `/contract/resolve` has no other format — every consumer
25810
- * signs this one to retrieve an existing agreement.
25811
- *
25812
- * @param timestampMs ms-epoch, and the same value sent as the body's
25813
- * `timestamp`.
25814
- */
25815
- function buildLegacyContractRequestMessage(address, timestampMs) {
25816
- return `I request contract content for ${address.toLowerCase()} at ${timestampMs}.`;
25817
- }
25818
- /**
25819
- * The `POST /contract/fullname` message.
25820
- *
25821
- * ⚠️ BYTE-EXACT PROTOCOL STRING, on the same terms as
25822
- * `buildLegacyContractRequestMessage`: kasu-backend rebuilds
25823
- * `` `I request my full name for ${address} at ${timestamp}.` `` from the
25824
- * request body and verifies the signature against it, so the body must carry
25825
- * the same lowercased address this builder signs.
25826
- *
25827
- * @param timestampMs ms-epoch, and the same value sent as the body's
25828
- * `timestamp`.
25829
- */
25830
- function buildFullNameRequestMessage(address, timestampMs) {
25831
- return `I request my full name for ${address.toLowerCase()} at ${timestampMs}.`;
25832
- }
25833
-
25834
27007
  /**
25835
27008
  * Cycles and the clearing window — the protocol's weekly clock, as numbers.
25836
27009
  *
@@ -25977,60 +27150,4 @@ function getTrancheDisplayName(trancheName, pool) {
25977
27150
  : trancheName;
25978
27151
  }
25979
27152
 
25980
- /**
25981
- * Wallet and RPC error predicates — pure functions over `unknown`.
25982
- *
25983
- * Every consumer has to tell three things apart when a write fails: the lender
25984
- * changed their mind, the call would revert, and everything else. The first
25985
- * two must never be reported as a failure the lender should retry or contact
25986
- * support about, and each wallet spells them differently, so the shapes are
25987
- * enumerated once here.
25988
- *
25989
- * Lifted from kasu-ui's `src/lib/web3/is-user-rejected.ts` and kasu-mobile's
25990
- * `src/features/lending/lib/errors.ts`.
25991
- */
25992
- /**
25993
- * Did the lender reject the request in their wallet?
25994
- *
25995
- * Providers surface a rejection in different shapes:
25996
- * - MetaMask and most EIP-1193 wallets: `code: 4001`
25997
- * - WalletConnect and some Privy paths: `Error('User rejected the request')`
25998
- * - ethers v5 wraps it as `ACTION_REJECTED`
25999
- * - Coinbase Wallet sometimes: `code: 'ACTION_REJECTED'` as a string
26000
- *
26001
- * This is kasu-ui's implementation verbatim. kasu-mobile's copy additionally
26002
- * reads a nested `error.code` / `error.message`, an ethers `reason`, and the
26003
- * words "request rejected" / "declined"; a consumer that needs those shapes
26004
- * should keep its own check on top rather than assume they are covered here.
26005
- */
26006
- function isUserRejected(err) {
26007
- if (!err)
26008
- return false;
26009
- if (typeof err === 'object') {
26010
- const code = err.code;
26011
- if (code === 4001 || code === 'ACTION_REJECTED')
26012
- return true;
26013
- }
26014
- const msg = err instanceof Error ? err.message : String(err);
26015
- const lower = msg.toLowerCase();
26016
- return (lower.includes('user rejected') ||
26017
- lower.includes('user denied') ||
26018
- lower.includes('rejected the request') ||
26019
- lower.includes('action_rejected'));
26020
- }
26021
- /**
26022
- * Did the wallet or RPC signal that the on-chain call would revert?
26023
- *
26024
- * ethers v5 raises `UNPREDICTABLE_GAS_LIMIT` when gas estimation reverts —
26025
- * most often an underlying `transferFrom` failing on an insufficient balance
26026
- * or allowance. Distinct from a rejection: nothing was refused by the lender,
26027
- * the transaction simply cannot succeed as composed, so the caller should
26028
- * re-check its preconditions rather than invite a retry.
26029
- */
26030
- function isUnpredictableGas(err) {
26031
- if (!err || typeof err !== 'object')
26032
- return false;
26033
- return err.code === 'UNPREDICTABLE_GAS_LIMIT';
26034
- }
26035
-
26036
- export { APXIUM, AU_ALPHA3, AU_MIN_CUMULATIVE_BY_STABLE, CHAIN_CONFIGS, CLEARING_WINDOW_SECONDS, DepositsFacade, EPOCHS_IN_YEAR, INVOICEMATE, Kasu, KasuSdk, MAX_LENDING_AMOUNT_FALLBACK, MIN_LENDING_AMOUNT_FALLBACK, MIN_TRANCHE_CAPACITY, NO_DIRECTUS_URL_MESSAGE, PortfolioFacade, RIXON_CAPITAL, SdkConfig, StrategiesFacade, UPPER_MEZZANINE, apyToEpochRate, asContractType, auMinimumRemaining, auThresholdFor, buildContractVersionType, buildFullNameRequestMessage, buildLegacyContractRequestMessage, buildLoanAgreementSignMessage, ceilToCents, compareTrancheSeniority, computeSettlementWindow, countSubmissions, deriveCycleDates, derivePoolStatus, deriveRequestState, encodeDepositData, epochRateToApy, fetchUnusedPoolIds, firstSubmissionTimestamp, floorToCents, formatSignTimestampUtc, getCreditOriginator, getInstitutionalLender, getTrancheDisplayName, isAuMinimumExempt, isAustralianKyc, isBelowMinimumCapacity, isCycleClosed, isUnpredictableGas, isUserRejected, maxNetRateCeiling, netEffectiveApy, netTrancheApyBounds, nextCycleBoundary, parseFormattedMessage, parseMinorUnits, parseTrancheBound, pickDefaultTrancheId, pickHighestYieldTranche, poolAllTranchesFull, poolMaxApy, resolveBoundShortcuts, resolveDepositBounds, selectVisiblePools, submissionEvents, trancheApyBounds, trancheHasCapacity, trancheRiskRank };
27153
+ export { APXIUM, AU_ALPHA3, AU_MIN_CUMULATIVE_BY_STABLE, CHAIN_CONFIGS, CLEARING_WINDOW_SECONDS, CONTRACT_TTL_MS, DepositFlow, DepositsFacade, EPOCHS_IN_YEAR, Flow, FlowStore, FlowsFacade, INVALID_ACCEPTANCE_SIGNATURE_MESSAGE, INVALID_AUTH_SIGNATURE_MESSAGE, INVOICEMATE, Kasu, KasuSdk, MAX_LENDING_AMOUNT_FALLBACK, MIN_LENDING_AMOUNT_FALLBACK, MIN_TRANCHE_CAPACITY, NO_DIRECTUS_URL_MESSAGE, NO_KYC_PARAMS_MESSAGE, NO_SPENDER_MESSAGE, PortfolioFacade, READ_ONLY_MESSAGE, RIXON_CAPITAL, SdkConfig, StrategiesFacade, UPPER_MEZZANINE, WithdrawFlow, apyToEpochRate, asContractType, auMinimumRemaining, auThresholdFor, buildContractVersionType, buildFullNameRequestMessage, buildLegacyContractRequestMessage, buildLoanAgreementSignMessage, ceilToCents, classifyWalletFailure, compareTrancheSeniority, computeSettlementWindow, countSubmissions, decodeRevert, deriveCycleDates, derivePoolStatus, deriveRequestState, encodeDepositData, epochRateToApy, extractRevertData, fetchUnusedPoolIds, firstSubmissionTimestamp, floorToCents, formatSignTimestampUtc, getCreditOriginator, getInstitutionalLender, getTrancheDisplayName, isAuMinimumExempt, isAustralianKyc, isBelowMinimumCapacity, isCycleClosed, isUnpredictableGas, isUserRejected, lastEventTimestamp, maxNetRateCeiling, netEffectiveApy, netTrancheApyBounds, nextCycleBoundary, parseFormattedMessage, parseMinorUnits, parseTrancheBound, pickDefaultTrancheId, pickHighestYieldTranche, poolAllTranchesFull, poolMaxApy, resolveBoundShortcuts, resolveDepositBounds, selectVisiblePools, submissionEvents, trancheApyBounds, trancheHasCapacity, trancheRiskRank };