@kasufinance/kasu-sdk 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/README.md +128 -3
  2. package/dist/bundle.cjs.js +1119 -254
  3. package/dist/bundle.esm.js +1109 -255
  4. package/dist/domain/index.d.ts +3 -2
  5. package/dist/domain/index.js +2 -2
  6. package/dist/domain/index.js.map +1 -1
  7. package/dist/domain/requests.d.ts +42 -4
  8. package/dist/domain/requests.js +20 -4
  9. package/dist/domain/requests.js.map +1 -1
  10. package/dist/domain/wallet-errors.d.ts +63 -8
  11. package/dist/domain/wallet-errors.js +115 -16
  12. package/dist/domain/wallet-errors.js.map +1 -1
  13. package/dist/facade/deposits.js +2 -1
  14. package/dist/facade/deposits.js.map +1 -1
  15. package/dist/facade/flows.d.ts +95 -0
  16. package/dist/facade/flows.js +116 -0
  17. package/dist/facade/flows.js.map +1 -0
  18. package/dist/facade/index.d.ts +3 -0
  19. package/dist/facade/index.js +3 -0
  20. package/dist/facade/index.js.map +1 -1
  21. package/dist/facade/kasu.d.ts +6 -2
  22. package/dist/facade/kasu.js +28 -3
  23. package/dist/facade/kasu.js.map +1 -1
  24. package/dist/facade/read-only.d.ts +12 -0
  25. package/dist/facade/read-only.js +13 -0
  26. package/dist/facade/read-only.js.map +1 -0
  27. package/dist/flows/deposit-flow.d.ts +301 -0
  28. package/dist/flows/deposit-flow.js +358 -0
  29. package/dist/flows/deposit-flow.js.map +1 -0
  30. package/dist/flows/flow.d.ts +72 -0
  31. package/dist/flows/flow.js +110 -0
  32. package/dist/flows/flow.js.map +1 -0
  33. package/dist/flows/index.d.ts +19 -0
  34. package/dist/flows/index.js +17 -0
  35. package/dist/flows/index.js.map +1 -0
  36. package/dist/flows/observable.d.ts +59 -0
  37. package/dist/flows/observable.js +81 -0
  38. package/dist/flows/observable.js.map +1 -0
  39. package/dist/flows/withdraw-flow.d.ts +99 -0
  40. package/dist/flows/withdraw-flow.js +83 -0
  41. package/dist/flows/withdraw-flow.js.map +1 -0
  42. package/dist/index.d.ts +1 -0
  43. package/dist/index.js +6 -0
  44. package/dist/index.js.map +1 -1
  45. package/dist/services/DataService/data-service.js +0 -1
  46. package/dist/services/DataService/data-service.js.map +1 -1
  47. package/package.json +8 -2
  48. package/src/domain/index.ts +7 -1
  49. package/src/domain/requests.ts +57 -4
  50. package/src/domain/wallet-errors.ts +135 -18
  51. package/src/facade/deposits.ts +2 -3
  52. package/src/facade/flows.ts +172 -0
  53. package/src/facade/index.ts +8 -0
  54. package/src/facade/kasu.ts +43 -3
  55. package/src/facade/read-only.ts +13 -0
  56. package/src/flows/deposit-flow.ts +775 -0
  57. package/src/flows/flow.ts +108 -0
  58. package/src/flows/index.ts +45 -0
  59. package/src/flows/observable.ts +97 -0
  60. package/src/flows/withdraw-flow.ts +210 -0
  61. package/src/index.ts +7 -0
  62. package/src/services/DataService/data-service.ts +0 -1
  63. package/dist/domain/au-minimum.test.d.ts +0 -1
  64. package/dist/domain/au-minimum.test.js +0 -202
  65. package/dist/domain/au-minimum.test.js.map +0 -1
  66. package/dist/domain/deposit-bounds.test.d.ts +0 -1
  67. package/dist/domain/deposit-bounds.test.js +0 -135
  68. package/dist/domain/deposit-bounds.test.js.map +0 -1
  69. package/dist/domain/loan-contract.test.d.ts +0 -1
  70. package/dist/domain/loan-contract.test.js +0 -255
  71. package/dist/domain/loan-contract.test.js.map +0 -1
  72. package/dist/domain/partners.test.d.ts +0 -1
  73. package/dist/domain/partners.test.js +0 -53
  74. package/dist/domain/partners.test.js.map +0 -1
  75. package/dist/domain/pools.test.d.ts +0 -1
  76. package/dist/domain/pools.test.js +0 -184
  77. package/dist/domain/pools.test.js.map +0 -1
  78. package/dist/domain/rates.test.d.ts +0 -1
  79. package/dist/domain/rates.test.js +0 -181
  80. package/dist/domain/rates.test.js.map +0 -1
  81. package/dist/domain/requests.test.d.ts +0 -1
  82. package/dist/domain/requests.test.js +0 -470
  83. package/dist/domain/requests.test.js.map +0 -1
  84. package/dist/domain/settlement.test.d.ts +0 -1
  85. package/dist/domain/settlement.test.js +0 -152
  86. package/dist/domain/settlement.test.js.map +0 -1
  87. package/dist/domain/tranche-display-name.test.d.ts +0 -1
  88. package/dist/domain/tranche-display-name.test.js +0 -58
  89. package/dist/domain/tranche-display-name.test.js.map +0 -1
  90. package/dist/domain/tranches.test.d.ts +0 -1
  91. package/dist/domain/tranches.test.js +0 -206
  92. package/dist/domain/tranches.test.js.map +0 -1
  93. package/dist/domain/wallet-errors.test.d.ts +0 -1
  94. package/dist/domain/wallet-errors.test.js +0 -71
  95. package/dist/domain/wallet-errors.test.js.map +0 -1
  96. package/dist/facade/config.test.d.ts +0 -1
  97. package/dist/facade/config.test.js +0 -216
  98. package/dist/facade/config.test.js.map +0 -1
  99. package/dist/facade/facade.test.d.ts +0 -1
  100. package/dist/facade/facade.test.js +0 -278
  101. package/dist/facade/facade.test.js.map +0 -1
  102. package/dist/services/Locking/calculate-apy.test.d.ts +0 -1
  103. package/dist/services/Locking/calculate-apy.test.js +0 -41
  104. package/dist/services/Locking/calculate-apy.test.js.map +0 -1
  105. package/dist/tests/sample.test.d.ts +0 -1
  106. package/dist/tests/sample.test.js +0 -59
  107. package/dist/tests/sample.test.js.map +0 -1
  108. package/src/domain/au-minimum.test.ts +0 -371
  109. package/src/domain/deposit-bounds.test.ts +0 -200
  110. package/src/domain/loan-contract.test.ts +0 -343
  111. package/src/domain/partners.test.ts +0 -83
  112. package/src/domain/pools.test.ts +0 -260
  113. package/src/domain/rates.test.ts +0 -254
  114. package/src/domain/requests.test.ts +0 -653
  115. package/src/domain/settlement.test.ts +0 -198
  116. package/src/domain/tranche-display-name.test.ts +0 -96
  117. package/src/domain/tranches.test.ts +0 -300
  118. package/src/domain/wallet-errors.test.ts +0 -100
  119. package/src/facade/config.test.ts +0 -265
  120. package/src/facade/facade.test.ts +0 -374
  121. package/src/services/Locking/calculate-apy.test.ts +0 -52
  122. package/src/tests/sample.test.ts +0 -63
@@ -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([
@@ -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,1067 @@ 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
+ * Wallet and RPC error predicates — pure functions over `unknown`.
24809
+ *
24810
+ * Every consumer has to tell three things apart when a write fails: the lender
24811
+ * changed their mind, the call would revert, and everything else. The first
24812
+ * two must never be reported as a failure the lender should retry or contact
24813
+ * support about, and each wallet spells them differently, so the shapes are
24814
+ * enumerated once here.
24815
+ *
24816
+ * Lifted from kasu-ui's `src/lib/web3/is-user-rejected.ts` and kasu-mobile's
24817
+ * `src/features/lending/lib/errors.ts` — and now the UNION of the two, so
24818
+ * neither app has to keep a wrapper on top of this one.
24819
+ */
24820
+ /**
24821
+ * Did the lender reject the request in their wallet?
24822
+ *
24823
+ * Providers surface a rejection in different shapes, and the union of them is
24824
+ * the point of this function existing once:
24825
+ * - MetaMask and most EIP-1193 wallets: `code: 4001`
24826
+ * - Coinbase Wallet and ethers v5: `code: 'ACTION_REJECTED'`
24827
+ * - viem: a `UserRejectedRequestError` name
24828
+ * - WalletConnect and some Privy paths: `Error('User rejected the request')`
24829
+ * - a provider error WRAPPED by another layer, carrying the real code and
24830
+ * message on a nested `error` — the shape Privy's embedded wallet
24831
+ * surfaces on Expo, where the outer object says nothing useful
24832
+ * - ethers' own `reason` field, which is often the only place the text lands
24833
+ * - a PLAIN OBJECT carrying `message`, which `String(err)` would read as
24834
+ * `"[object Object]"`
24835
+ *
24836
+ * Previously kasu-ui's implementation verbatim, with kasu-mobile keeping its
24837
+ * own superset on top. That is precisely the drift this layer exists to stop —
24838
+ * a rejection kasu-mobile recognised and kasu-ui did not was reported to the
24839
+ * same lender as a failure on one app and a cancellation on the other. The
24840
+ * union lives here; the mobile wrapper goes.
24841
+ *
24842
+ * ## The text is read for a SUBJECT, not for a keyword
24843
+ *
24844
+ * The words alone are not the signal. "Declined" and "request rejected" are
24845
+ * also what a rate limiter, a risk engine and a KYC decision say, and those
24846
+ * arrive wrapped in exactly the same envelope a wallet error does — ethers'
24847
+ * `SERVER_ERROR` around `-32603` carries the upstream body on a nested
24848
+ * `error.message`, so `{ error: { message: 'request rejected: rate limit
24849
+ * exceeded' } }` is an RPC refusing to serve us, not a lender refusing to
24850
+ * sign. Reporting one as the other tells a lender they cancelled something
24851
+ * they never saw, and DROPS the real error on the floor.
24852
+ *
24853
+ * So a rejection is a machine-readable wallet code, or a sentence that names
24854
+ * the party who did it: "user rejected", "declined by the user", "cancelled by
24855
+ * the wallet". A bare "declined" is not a rejection, whatever else is on the
24856
+ * envelope.
24857
+ *
24858
+ * Within that rule, being generous is the safe direction: calling a genuine
24859
+ * fault a cancellation costs a lender one retry, while calling a deliberate
24860
+ * rejection a failure sends them to support to report a bug that does not
24861
+ * exist.
24862
+ */
24863
+ function isUserRejected(err) {
24864
+ var _a;
24865
+ if (!err)
24866
+ return false;
24867
+ if (typeof err === 'object') {
24868
+ const e = err;
24869
+ if (isRejectionCode(e.code))
24870
+ return true;
24871
+ // A wrapped provider error: the outer layer's code is its own, the
24872
+ // inner one is the wallet's.
24873
+ if (isRejectionCode((_a = e.error) === null || _a === void 0 ? void 0 : _a.code))
24874
+ return true;
24875
+ }
24876
+ const lower = rejectionText(err).toLowerCase();
24877
+ return USER_REJECTION_PATTERNS.some((pattern) => pattern.test(lower));
24878
+ }
24879
+ function isRejectionCode(code) {
24880
+ return code === 4001 || code === 'ACTION_REJECTED';
24881
+ }
24882
+ /**
24883
+ * The wordings that name the wallet or the person at it.
24884
+ *
24885
+ * Each one carries a SUBJECT — the identifier a wallet library uses, or the
24886
+ * verb with the party who performed it. That is what separates a lender
24887
+ * pressing Reject from a server declining to answer, and it is why none of
24888
+ * these is a bare "declined" or "rejected".
24889
+ */
24890
+ const USER_REJECTION_PATTERNS = [
24891
+ // Machine-readable markers that only a wallet layer emits, arriving as
24892
+ // text because something in between stringified the error.
24893
+ /action_rejected/,
24894
+ /user_rejected/,
24895
+ /userrejectedrequest/,
24896
+ // "the user did it", in the orders the wallets write it.
24897
+ /user\s+(?:has\s+)?(?:rejected|denied|declined|refused|cancell?ed)/,
24898
+ /(?:rejected|denied|declined|refused|cancell?ed)\s+by\s+(?:the\s+)?(?:user|wallet|signer|owner)/,
24899
+ // The wallet as the subject, which is how some embedded wallets word it.
24900
+ /(?:wallet|signer)\s+(?:rejected|denied|declined|refused)/,
24901
+ ];
24902
+ /**
24903
+ * Every place a wallet might have put the words: the message, ethers' `reason`,
24904
+ * the error's `name` (viem puts the whole signal there), and a wrapped error's
24905
+ * own three. Joined rather than picked, because which one carries the text
24906
+ * depends on how many layers wrapped it.
24907
+ *
24908
+ * A separator is used rather than a bare space: two fields must not be able to
24909
+ * form a phrase across the join that neither of them said.
24910
+ */
24911
+ function rejectionText(err) {
24912
+ var _a, _b, _c;
24913
+ if (typeof err !== 'object' || err === null)
24914
+ return String(err);
24915
+ const e = err;
24916
+ return [
24917
+ e.message,
24918
+ e.reason,
24919
+ e.name,
24920
+ (_a = e.error) === null || _a === void 0 ? void 0 : _a.message,
24921
+ (_b = e.error) === null || _b === void 0 ? void 0 : _b.reason,
24922
+ (_c = e.error) === null || _c === void 0 ? void 0 : _c.name,
24923
+ ]
24924
+ .filter((part) => typeof part === 'string')
24925
+ .join(' | ');
24926
+ }
24927
+ /**
24928
+ * Did the wallet or RPC signal that the on-chain call would revert?
24929
+ *
24930
+ * ethers v5 raises `UNPREDICTABLE_GAS_LIMIT` when gas estimation reverts —
24931
+ * most often an underlying `transferFrom` failing on an insufficient balance
24932
+ * or allowance. Distinct from a rejection: nothing was refused by the lender,
24933
+ * the transaction simply cannot succeed as composed, so the caller should
24934
+ * re-check its preconditions rather than invite a retry.
24935
+ */
24936
+ function isUnpredictableGas(err) {
24937
+ if (!err || typeof err !== 'object')
24938
+ return false;
24939
+ return err.code === 'UNPREDICTABLE_GAS_LIMIT';
24940
+ }
24941
+ /**
24942
+ * The `cancelled` / `failed` split, for a WALLET call on any step of any flow.
24943
+ *
24944
+ * A lender who pressed Reject is not a fault. Reporting one as the other is
24945
+ * how a support queue fills with people who did exactly what they meant to.
24946
+ *
24947
+ * Generic in the step so both flows share one implementation — it was
24948
+ * duplicated byte-for-byte in each of them, which is the same drift this
24949
+ * layer exists to stop, one level up.
24950
+ *
24951
+ * Only pass it an error a WALLET produced. An HTTP port's throw is always a
24952
+ * `failed`: the lender's wallet was not involved in it, so a backend that
24953
+ * happens to word a refusal "declined" must never be shown to them as
24954
+ * something they did.
24955
+ */
24956
+ function classifyWalletFailure(step, err) {
24957
+ return isUserRejected(err)
24958
+ ? { step, reason: 'cancelled' }
24959
+ : { step, reason: 'failed', error: err };
24960
+ }
24961
+
24962
+ /** Generated agreements are valid for five minutes upstream. */
24963
+ const CONTRACT_TTL_MS = 5 * 60 * 1000;
24964
+ /** What a run without a spender, from either source, fails with. */
24965
+ const NO_SPENDER_MESSAGE = 'DepositFlow: no ERC-20 spender; build the flow with kasu.flows.deposit() or pass `spender` on the input';
24966
+ const INITIAL$1 = {
24967
+ phase: 'idle',
24968
+ step: null,
24969
+ stepIndex: 0,
24970
+ stepTotal: 4,
24971
+ approvalRequired: true,
24972
+ contract: null,
24973
+ failure: null,
24974
+ };
24975
+ /** 1-based badge position, with `approve` dropped when it is out of scope. */
24976
+ function stepIndexOf(step, approvalRequired) {
24977
+ const order = approvalRequired
24978
+ ? ['generate', 'confirm', 'approve', 'request']
24979
+ : ['generate', 'confirm', 'request'];
24980
+ return order.indexOf(step) + 1;
24981
+ }
24982
+ function badgeFor(step, approvalRequired) {
24983
+ return {
24984
+ step,
24985
+ stepIndex: stepIndexOf(step, approvalRequired),
24986
+ stepTotal: approvalRequired ? 4 : 3,
24987
+ };
24988
+ }
24989
+ /**
24990
+ * The request step has a third outcome. `UNPREDICTABLE_GAS_LIMIT` here is
24991
+ * almost always `transferFrom` reverting on a balance that cannot cover the
24992
+ * deposit, and it takes precedence: nothing was refused by the lender, so
24993
+ * inviting a retry would just reproduce it.
24994
+ */
24995
+ function classifyRequest(err) {
24996
+ if (isUnpredictableGas(err)) {
24997
+ return { step: 'request', reason: 'insufficient-balance', error: err };
24998
+ }
24999
+ return classifyWalletFailure('request', err);
25000
+ }
25001
+ // ---------------------------------------------------------------------------
25002
+ // The flow
25003
+ // ---------------------------------------------------------------------------
25004
+ class DepositFlow extends Flow {
25005
+ constructor(_ports, opts) {
25006
+ var _a;
25007
+ super(INITIAL$1);
25008
+ this._ports = _ports;
25009
+ /**
25010
+ * The accept handshake. The run parks on this promise; `acceptContract`,
25011
+ * `declineContract` and `reset` each settle it with an `AcceptOutcome`.
25012
+ * Cleared the moment it settles so a stale resolver from an abandoned run
25013
+ * can never leak into the next one.
25014
+ */
25015
+ this._accept = null;
25016
+ /**
25017
+ * The run token that is between `acceptContract()` and the wallet
25018
+ * settling, or `null`.
25019
+ *
25020
+ * A token rather than a boolean, because the flag has to belong to the RUN
25021
+ * that set it: after `reset()` out of a wallet prompt that never answers,
25022
+ * the abandoned run's `finally` may not arrive for minutes, and a boolean
25023
+ * left standing refuses both Accept and Decline on every run after it.
25024
+ * A stale token simply is not the current generation.
25025
+ */
25026
+ this._acceptingFor = null;
25027
+ this._ttlMs = (_a = opts === null || opts === void 0 ? void 0 : opts.contractTtlMs) !== null && _a !== void 0 ? _a : CONTRACT_TTL_MS;
25028
+ this._defaultSpender = opts === null || opts === void 0 ? void 0 : opts.spender;
25029
+ // Called through the ports object, never captured off it: a consumer
25030
+ // whose clock is a method on its own object keeps its `this`.
25031
+ 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(); };
25032
+ }
25033
+ /**
25034
+ * Sign the agreement and resume the parked run. A no-op when nothing is
25035
+ * parked, so a double tap cannot sign twice.
25036
+ */
25037
+ acceptContract() {
25038
+ return __awaiter(this, void 0, void 0, function* () {
25039
+ const bridge = this._accept;
25040
+ const contract = this._store.state.contract;
25041
+ if (!bridge || !contract || this._isAccepting())
25042
+ return;
25043
+ const token = this._store.generation;
25044
+ this._acceptingFor = token;
25045
+ this._store.patch(Object.assign({ phase: 'accepting-sign' }, badgeFor('confirm', this._store.state.approvalRequired)), token);
25046
+ try {
25047
+ const signature = yield this._ports.signMessage(contract.contractMessage);
25048
+ bridge.settle({ kind: 'accepted', signature });
25049
+ }
25050
+ catch (err) {
25051
+ // A WALLET error, and the only one this flow classifies as a
25052
+ // possible cancellation on the confirm step.
25053
+ bridge.settle({ kind: 'failed', error: err });
25054
+ }
25055
+ finally {
25056
+ // Only if this run still holds it: a `reset()` during the prompt
25057
+ // may have started another one, and that one's flag is its own.
25058
+ if (this._acceptingFor === token)
25059
+ this._acceptingFor = null;
25060
+ }
25061
+ });
25062
+ }
25063
+ /**
25064
+ * Back out of the agreement. The run ends on `declined` — a legitimate
25065
+ * choice, not a failure, and `state.failure` stays null.
25066
+ *
25067
+ * Ignored once `acceptContract()` has opened the wallet: an agreement in
25068
+ * the middle of being signed cannot also be refused. `reset()` is the way
25069
+ * out of a prompt that never answers.
25070
+ */
25071
+ declineContract() {
25072
+ const bridge = this._accept;
25073
+ if (!bridge || this._isAccepting())
25074
+ return;
25075
+ this._accept = null;
25076
+ bridge.settle({ kind: 'declined' });
25077
+ }
25078
+ /** True only while THIS generation is waiting on the acceptance signature. */
25079
+ _isAccepting() {
25080
+ return (this._acceptingFor !== null &&
25081
+ this._store.isCurrent(this._acceptingFor));
25082
+ }
25083
+ /** `reset()`: unpark the abandoned run and drop its handshake. */
25084
+ _onAbandon() {
25085
+ const bridge = this._accept;
25086
+ this._accept = null;
25087
+ this._acceptingFor = null;
25088
+ bridge === null || bridge === void 0 ? void 0 : bridge.settle({ kind: 'abandoned' });
25089
+ }
25090
+ // -----------------------------------------------------------------------
25091
+ _run(input, token) {
25092
+ return __awaiter(this, void 0, void 0, function* () {
25093
+ var _a;
25094
+ this._accept = null;
25095
+ this._acceptingFor = null;
25096
+ const ports = this._ports;
25097
+ const owner = input.userAddress.toLowerCase();
25098
+ // 0. The spender, from the input or from the chain config the facade
25099
+ // built this flow with. Without one there is nothing to read an
25100
+ // allowance against and nothing to approve — and guessing would
25101
+ // grant an approval to the wrong contract.
25102
+ const spender = (_a = input.spender) !== null && _a !== void 0 ? _a : this._defaultSpender;
25103
+ if (!spender) {
25104
+ this._fail(token, true, {
25105
+ step: 'generate',
25106
+ reason: 'failed',
25107
+ error: new Error(NO_SPENDER_MESSAGE),
25108
+ });
25109
+ return;
25110
+ }
25111
+ // 1. Allowance pre-check. Decides `approvalRequired` — and therefore
25112
+ // the badge total — before the lender is shown a single step. Read
25113
+ // live, never cached: an exact-amount approval is fully consumed by
25114
+ // the deposit it paid for, so a stale allowance is exactly the value
25115
+ // that would wrongly skip the approve and revert the deposit.
25116
+ let approvalRequired = true;
25117
+ try {
25118
+ const allowance = yield ports.readAllowance(owner, spender);
25119
+ approvalRequired = allowance.lt(input.amount);
25120
+ }
25121
+ catch (_b) {
25122
+ // A read failure is not a reason to skip an approval. Assume one is
25123
+ // needed: the cost is a redundant approve, the alternative is a
25124
+ // reverted deposit.
25125
+ approvalRequired = true;
25126
+ }
25127
+ if (!this._store.isCurrent(token))
25128
+ return;
25129
+ // 2. Generate — sign the auth message.
25130
+ this._store.patch(Object.assign({ approvalRequired, phase: 'generating-sign' }, badgeFor('generate', approvalRequired)), token);
25131
+ const timestamp = this._now();
25132
+ const signedMessage = buildAuthMessage(input, owner, timestamp);
25133
+ let signature;
25134
+ try {
25135
+ signature = yield ports.signMessage(signedMessage);
25136
+ }
25137
+ catch (err) {
25138
+ this._fail(token, approvalRequired, classifyWalletFailure('generate', err));
25139
+ return;
25140
+ }
25141
+ if (!this._store.isCurrent(token))
25142
+ return;
25143
+ // 3. Generate — POST the request.
25144
+ this._store.patch(Object.assign({ phase: 'generating-fetch' }, badgeFor('generate', approvalRequired)), token);
25145
+ let contract;
25146
+ try {
25147
+ contract = yield ports.generateContract(Object.assign({ address: owner, signature,
25148
+ timestamp,
25149
+ signedMessage, poolId: input.poolId, trancheId: input.trancheId, fixedTermConfigId: input.fixedTermConfigId, depositAmount: input.depositAmount }, displayFieldsOf(input.contractMessage)));
25150
+ }
25151
+ catch (err) {
25152
+ // Never a wallet rejection: this step is an HTTP call, and the
25153
+ // lender's wallet was not involved in it. A backend that happened
25154
+ // to echo the words "user rejected" must not be reported to them as
25155
+ // something they did.
25156
+ this._fail(token, approvalRequired, {
25157
+ step: 'generate',
25158
+ reason: 'failed',
25159
+ error: err,
25160
+ });
25161
+ return;
25162
+ }
25163
+ if (!this._store.isCurrent(token))
25164
+ return;
25165
+ // 4. Park on the agreement until the consumer accepts or declines.
25166
+ const outcome = yield new Promise((resolve) => {
25167
+ this._accept = { settle: resolve };
25168
+ this._store.patch(Object.assign({ phase: 'awaiting-accept', contract }, badgeFor('confirm', approvalRequired)), token);
25169
+ });
25170
+ this._accept = null;
25171
+ // An abandoned run lands here too — `reset()` unparks it. The token
25172
+ // check is what tells the two apart.
25173
+ if (!this._store.isCurrent(token))
25174
+ return;
25175
+ if (outcome.kind === 'declined') {
25176
+ this._store.patch(Object.assign({ phase: 'declined' }, badgeFor('confirm', approvalRequired)), token);
25177
+ return;
25178
+ }
25179
+ if (outcome.kind !== 'accepted') {
25180
+ if (outcome.kind === 'failed') {
25181
+ this._fail(token, approvalRequired, classifyWalletFailure('confirm', outcome.error));
25182
+ }
25183
+ return;
25184
+ }
25185
+ // 5. TTL guard. Checked here because this is where the idling happens:
25186
+ // the lender has just spent as long as they wanted reading. An
25187
+ // expired agreement is refused rather than broadcast — the on-chain
25188
+ // call would revert, after a wallet prompt and a gas estimate, with
25189
+ // nothing on screen explaining why.
25190
+ if (this._now() > contract.timestamp + this._ttlMs) {
25191
+ this._fail(token, approvalRequired, {
25192
+ step: 'request',
25193
+ reason: 'contract-expired',
25194
+ });
25195
+ return;
25196
+ }
25197
+ const depositData = encodeDepositData({
25198
+ signature: outcome.signature,
25199
+ timestamp: contract.timestamp,
25200
+ contractVersion: contract.contractVersion,
25201
+ contractType: asContractType(contract.contractType),
25202
+ });
25203
+ // 6. Approve — the EXACT amount, never `MaxUint256`. House rule: an
25204
+ // unlimited allowance outlives the deposit it was granted for, and a
25205
+ // later exploit of the spender would drain a wallet that has long
25206
+ // since stopped lending.
25207
+ if (approvalRequired) {
25208
+ this._store.patch(Object.assign({ phase: 'approve' }, badgeFor('approve', approvalRequired)), token);
25209
+ try {
25210
+ const tx = yield ports.approve(spender, input.amount);
25211
+ yield tx.wait();
25212
+ }
25213
+ catch (err) {
25214
+ this._fail(token, approvalRequired, classifyWalletFailure('approve', err));
25215
+ return;
25216
+ }
25217
+ if (!this._store.isCurrent(token))
25218
+ return;
25219
+ }
25220
+ // 7. Request — KYC signature, then the deposit and its receipt.
25221
+ this._store.patch(Object.assign({ phase: 'request-sign' }, badgeFor('request', approvalRequired)), token);
25222
+ // The two KYC ports reach the consumer's own backend, so they fail the
25223
+ // way the generate step does: `failed`, with the error kept. Running
25224
+ // them through the rejection classifier would let a backend wording —
25225
+ // "Declined", "request rejected" — end a run as "you cancelled in your
25226
+ // wallet", with the real error discarded and nothing to report.
25227
+ let kyc;
25228
+ try {
25229
+ const kycParams = yield ports.buildKycParams(owner);
25230
+ kyc = yield ports.getKycSignature(kycParams);
25231
+ }
25232
+ catch (err) {
25233
+ this._fail(token, approvalRequired, {
25234
+ step: 'request',
25235
+ reason: 'failed',
25236
+ error: err,
25237
+ });
25238
+ return;
25239
+ }
25240
+ if (!this._store.isCurrent(token))
25241
+ return;
25242
+ try {
25243
+ const tx = yield ports.deposit({
25244
+ poolId: input.poolId,
25245
+ trancheId: input.trancheId,
25246
+ amount: input.amount,
25247
+ kycSignature: {
25248
+ blockExpiration: kyc.blockExpiration,
25249
+ signature: kyc.signature,
25250
+ },
25251
+ depositData,
25252
+ fixedTermConfigId: input.fixedTermConfigId,
25253
+ });
25254
+ this._store.patch(Object.assign({ phase: 'request-confirm' }, badgeFor('request', approvalRequired)), token);
25255
+ yield tx.wait();
25256
+ }
25257
+ catch (err) {
25258
+ this._fail(token, approvalRequired, classifyRequest(err));
25259
+ return;
25260
+ }
25261
+ if (!this._store.isCurrent(token))
25262
+ return;
25263
+ this._store.patch(Object.assign({ phase: 'success' }, badgeFor('request', approvalRequired)), token);
25264
+ });
25265
+ }
25266
+ _fail(token, approvalRequired, failure) {
25267
+ this._store.patch(Object.assign({ phase: 'error', failure }, badgeFor(failure.step, approvalRequired)), token);
25268
+ }
25269
+ }
25270
+ // ---------------------------------------------------------------------------
25271
+ // Message building
25272
+ // ---------------------------------------------------------------------------
25273
+ /**
25274
+ * The auth message, in whichever format the consumer asked for. Both builders
25275
+ * are the byte-exact protocol strings from `domain/loan-contract` — the string
25276
+ * signed here and the body posted from `_run` state the SAME timestamp and the
25277
+ * SAME lowercased address, because kasu-backend rebuilds one from the other.
25278
+ */
25279
+ function buildAuthMessage(input, owner, timestamp) {
25280
+ if (input.contractMessage.format === 'legacy') {
25281
+ return buildLegacyContractRequestMessage(owner, timestamp);
25282
+ }
25283
+ const { strategyName, region, optionName, amountLabel } = input.contractMessage;
25284
+ return buildLoanAgreementSignMessage({
25285
+ strategyName,
25286
+ region,
25287
+ optionName,
25288
+ amountLabel,
25289
+ timestamp,
25290
+ });
25291
+ }
25292
+ /**
25293
+ * The four display fields, present only on the new format. The backend picks
25294
+ * its verification path on their presence: all four → the human-readable
25295
+ * format, any missing → the legacy string.
25296
+ */
25297
+ function displayFieldsOf(message) {
25298
+ if (message.format === 'legacy')
25299
+ return {};
25300
+ return {
25301
+ strategyName: message.strategyName,
25302
+ region: message.region,
25303
+ optionName: message.optionName,
25304
+ amountLabel: message.amountLabel,
25305
+ };
25306
+ }
25307
+
25308
+ const INITIAL = {
25309
+ phase: 'idle',
25310
+ step: null,
25311
+ isMax: false,
25312
+ failure: null,
25313
+ };
25314
+ /** What a KYC pre-check with no `buildKycParams` to call fails with. */
25315
+ const NO_KYC_PARAMS_MESSAGE = 'WithdrawFlow: getKycSignature was supplied without buildKycParams; build the flow with kasu.flows.withdraw() or pass both';
25316
+ // ---------------------------------------------------------------------------
25317
+ // The flow
25318
+ // ---------------------------------------------------------------------------
25319
+ class WithdrawFlow extends Flow {
25320
+ constructor(_ports) {
25321
+ super(INITIAL);
25322
+ this._ports = _ports;
25323
+ }
25324
+ _run(input, token) {
25325
+ return __awaiter(this, void 0, void 0, function* () {
25326
+ const ports = this._ports;
25327
+ const isMax = input.amount === 'max';
25328
+ // 1. The optional KYC pre-check: build the params, exchange them for a
25329
+ // signature. Both ports reach the application's own backend, so a
25330
+ // throw here is ALWAYS `failed` — running it through the wallet
25331
+ // rejection classifier would let a backend's "Declined" be reported
25332
+ // to a lender as something they did, with the real error dropped.
25333
+ if (ports.getKycSignature) {
25334
+ this._store.patch({ phase: 'checking-kyc', step: 'kyc', isMax }, token);
25335
+ try {
25336
+ if (!ports.buildKycParams) {
25337
+ throw new Error(NO_KYC_PARAMS_MESSAGE);
25338
+ }
25339
+ const params = yield ports.buildKycParams(input.userAddress);
25340
+ yield ports.getKycSignature(params);
25341
+ }
25342
+ catch (err) {
25343
+ this._store.patch({
25344
+ phase: 'error',
25345
+ failure: { step: 'kyc', reason: 'failed', error: err },
25346
+ }, token);
25347
+ return;
25348
+ }
25349
+ if (!this._store.isCurrent(token))
25350
+ return;
25351
+ }
25352
+ // 2. The submission. This one IS a wallet call, so it keeps the
25353
+ // `cancelled` / `failed` split.
25354
+ this._store.patch({ phase: 'request-sign', step: 'request', isMax }, token);
25355
+ try {
25356
+ const tx = input.amount === 'max'
25357
+ ? yield ports.withdrawMax(input.poolId, input.trancheId, input.userAddress.toLowerCase())
25358
+ : yield ports.withdraw({
25359
+ poolId: input.poolId,
25360
+ trancheId: input.trancheId,
25361
+ amount: input.amount,
25362
+ });
25363
+ this._store.patch({ phase: 'request-confirm' }, token);
25364
+ yield tx.wait();
25365
+ }
25366
+ catch (err) {
25367
+ this._store.patch({
25368
+ phase: 'error',
25369
+ failure: classifyWalletFailure('request', err),
25370
+ }, token);
25371
+ return;
25372
+ }
25373
+ if (!this._store.isCurrent(token))
25374
+ return;
25375
+ this._store.patch({ phase: 'success' }, token);
25376
+ });
25377
+ }
25378
+ }
25379
+
25380
+ /**
25381
+ * Builds `DepositFlow` / `WithdrawFlow` instances wired to THIS Kasu instance:
25382
+ * its chain's stable token, its `LendingPoolManager`, its signer.
25383
+ *
25384
+ * ```ts
25385
+ * const flow = kasu.connect(signer).flows.deposit({
25386
+ * signMessage: (m) => signer.signMessage(m),
25387
+ * generateContract: (req) => postToMyProxy(req),
25388
+ * getKycSignature: (p) => postToMyBackend(p),
25389
+ * });
25390
+ * ```
25391
+ *
25392
+ * A flow built from a read-only instance constructs fine and reads fine — the
25393
+ * write ports throw `READ_ONLY_MESSAGE` when the run reaches them, exactly as
25394
+ * `kasu.deposits.deposit` does. Constructing is not the mistake; submitting is.
25395
+ *
25396
+ * It holds the `DepositsFacade` and NOTHING the facade already owns: no
25397
+ * `UserLending`, no chain id, no signer. Two paths to one behaviour is how the
25398
+ * KYC params a flow built came to differ from the ones `kasu.deposits`
25399
+ * built — the same class of drift the flows themselves exist to end.
25400
+ */
25401
+ class FlowsFacade {
25402
+ constructor(_deposits,
25403
+ /**
25404
+ * The chain's stable token, bound to whatever the Kasu instance holds.
25405
+ * A factory rather than a contract: it is one `new Contract`, and a
25406
+ * cached binding would outlive the config it was built from.
24411
25407
  */
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
- }
25408
+ _erc20,
25409
+ /** The read-only flag `Kasu` already computed never re-derived here. */
25410
+ _isReadOnly,
24418
25411
  /**
24419
- * Withdraw the entire balance from a tranche.
25412
+ * The ERC-20 spender every deposit run approves: this chain's
25413
+ * `LendingPoolManager`, which is the only contract the default deposit
25414
+ * port calls. Passed to the flow so a consumer never has to hand-wire
25415
+ * an address whose only wrong value grants an approval to the wrong
25416
+ * contract.
24420
25417
  */
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
- });
25418
+ _spender) {
25419
+ this._deposits = _deposits;
25420
+ this._erc20 = _erc20;
25421
+ this._isReadOnly = _isReadOnly;
25422
+ this._spender = _spender;
24426
25423
  }
24427
25424
  /**
24428
- * Build KYC signature parameters for the Nexera verification flow.
25425
+ * A deposit pipeline. `readAllowance`, `approve`, `deposit` and
25426
+ * `buildKycParams` default to the SDK's own implementations; pass any of
25427
+ * them to override (kasu-ui approves through its sponsored-gas path, for
25428
+ * one).
24429
25429
  *
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).
25430
+ * Each default is applied per key with `??`, not by spreading `ports` over
25431
+ * them: `{ ...defaults, ...ports }` lets an EXPLICITLY undefined value
25432
+ * delete the default it was meant to keep, and
25433
+ * `approve: sponsoredGas ? sponsoredApprove : undefined` is exactly how a
25434
+ * consumer writes a conditional override.
24439
25435
  */
24440
- isClearingPending(poolId) {
24441
- return __awaiter(this, void 0, void 0, function* () {
24442
- return yield this._userLending.isClearingPending(poolId);
25436
+ deposit(ports, opts) {
25437
+ var _a, _b, _c, _d, _e;
25438
+ return new DepositFlow({
25439
+ signMessage: ports.signMessage,
25440
+ generateContract: ports.generateContract,
25441
+ getKycSignature: ports.getKycSignature,
25442
+ buildKycParams: (_a = ports.buildKycParams) !== null && _a !== void 0 ? _a : ((userAddress) => this._deposits.buildKycParams(userAddress)),
25443
+ readAllowance: (_b = ports.readAllowance) !== null && _b !== void 0 ? _b : ((owner, spender) => this._erc20().allowance(owner, spender)),
25444
+ approve: (_c = ports.approve) !== null && _c !== void 0 ? _c : ((spender, amount) => __awaiter(this, void 0, void 0, function* () {
25445
+ this._assertWritable();
25446
+ // The EXACT amount the flow asked for. Nothing here
25447
+ // rounds it up, and nothing here substitutes
25448
+ // MaxUint256.
25449
+ return yield this._erc20().approve(spender, amount);
25450
+ })),
25451
+ deposit: (_d = ports.deposit) !== null && _d !== void 0 ? _d : ((params) => this._deposits.deposit(params)),
25452
+ now: ports.now,
25453
+ }, {
25454
+ contractTtlMs: opts === null || opts === void 0 ? void 0 : opts.contractTtlMs,
25455
+ // Per key here too, for the same reason the ports are: an
25456
+ // explicit `spender: undefined` must not delete the default.
25457
+ spender: (_e = opts === null || opts === void 0 ? void 0 : opts.spender) !== null && _e !== void 0 ? _e : this._spender,
24443
25458
  });
24444
25459
  }
24445
25460
  /**
24446
- * Get the current epoch number.
25461
+ * A withdrawal pipeline. Both write ports and `buildKycParams` default to
25462
+ * this instance; supplying `getKycSignature` turns the KYC pre-check on.
25463
+ * Defaults are applied per key, for the reason `deposit()` gives.
24447
25464
  */
24448
- getCurrentEpoch() {
24449
- return __awaiter(this, void 0, void 0, function* () {
24450
- return yield this._userLending.getCurrentEpoch();
25465
+ withdraw(ports = {}) {
25466
+ var _a, _b, _c;
25467
+ return new WithdrawFlow({
25468
+ buildKycParams: (_a = ports.buildKycParams) !== null && _a !== void 0 ? _a : ((userAddress) => this._deposits.buildKycParams(userAddress)),
25469
+ getKycSignature: ports.getKycSignature,
25470
+ withdraw: (_b = ports.withdraw) !== null && _b !== void 0 ? _b : ((params) => this._deposits.withdraw({
25471
+ poolId: params.poolId,
25472
+ trancheId: params.trancheId,
25473
+ amount: params.amount,
25474
+ })),
25475
+ withdrawMax: (_c = ports.withdrawMax) !== null && _c !== void 0 ? _c : ((poolId, trancheId, userAddress) => this._deposits.withdrawMax(poolId, trancheId, userAddress)),
24451
25476
  });
24452
25477
  }
25478
+ _assertWritable() {
25479
+ if (this._isReadOnly) {
25480
+ throw new Error(READ_ONLY_MESSAGE);
25481
+ }
25482
+ }
24453
25483
  }
24454
25484
 
24455
25485
  /**
@@ -24908,6 +25938,16 @@ function firstSubmissionTimestamp(events, fallback) {
24908
25938
  return fallback;
24909
25939
  return submissions.reduce((min, e) => (e.timestamp < min ? e.timestamp : min), Infinity);
24910
25940
  }
25941
+ /**
25942
+ * The LATEST event timestamp, or `fallback` when the timeline is empty — or
25943
+ * when every event predates it, because `fallback` seeds the reduction. That
25944
+ * seeding is deliberate and is kasu-ui's behaviour: `request.timestamp` is a
25945
+ * fact about the request, and an event indexed with an earlier clock must not
25946
+ * make the row look older than the request itself.
25947
+ */
25948
+ function lastEventTimestamp(events, fallback) {
25949
+ return events.reduce((max, e) => (e.timestamp > max ? e.timestamp : max), fallback);
25950
+ }
24911
25951
  /**
24912
25952
  * Has THIS request's cycle closed? — the single open/closed signal behind the
24913
25953
  * status vocabulary and behind Cancel.
@@ -24991,10 +26031,10 @@ const numOrNull = (str) => {
24991
26031
  * status would strand it.
24992
26032
  *
24993
26033
  * 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 —
26034
+ * it; the tranche display rename (`getTrancheDisplayName` on `trancheName`
26035
+ * and on `reallocationTargetTrancheName`, both of which are RAW here); the
26036
+ * pool-name split; the amount format. The "view loan agreement" affordance is
26037
+ * a fact, and it follows from two fields already here —
24998
26038
  * `requestType === 'Deposit' && statusCode !== 'cancelled' && statusCode !== 'rejected'`
24999
26039
  * — because neither a cancelled nor a fully-rejected deposit ever issued one,
25000
26040
  * and withdrawals sign no agreement at all.
@@ -25029,6 +26069,12 @@ function deriveRequestState(request) {
25029
26069
  initiatedAmount: initiated
25030
26070
  ? initiatedAmountOf(request.events)
25031
26071
  : null,
26072
+ rejectedAmount: rejected,
26073
+ reallocatedOutAmount: reallocation ? num(reallocation.assetAmount) : 0,
26074
+ reallocationTargetTrancheName: reallocation
26075
+ ? reallocation.trancheName
26076
+ : null,
26077
+ lastTimestamp: lastEventTimestamp(request.events, request.timestamp),
25032
26078
  submissionCount: countSubmissions(request.events),
25033
26079
  // `firstSubmissionTimestamp` needs a fallback it will never use here:
25034
26080
  // the bundle is non-empty on every path that reaches the call.
@@ -25148,8 +26194,9 @@ class PortfolioFacade {
25148
26194
  /**
25149
26195
  * High-level entry point for external integrators.
25150
26196
  *
25151
- * Provides three domain facades — `strategies`, `deposits`, `portfolio` — and
25152
- * exposes the underlying `KasuSdk` services via `.services` for power-users.
26197
+ * Provides four domain facades — `strategies`, `deposits`, `portfolio`,
26198
+ * `flows` — and exposes the underlying `KasuSdk` services via `.services` for
26199
+ * power-users.
25153
26200
  *
25154
26201
  * ```ts
25155
26202
  * import { Kasu } from '@kasufinance/kasu-sdk';
@@ -25173,8 +26220,13 @@ class Kasu {
25173
26220
  this._signerOrProvider = signerOrProvider;
25174
26221
  this._configOverrides = configOverrides;
25175
26222
  this.strategies = new StrategiesFacade(sdk.DataService, sdk.UserLending);
25176
- this.deposits = new DepositsFacade(sdk.UserLending, chainConfig.chainId.toString(), !Signer.isSigner(signerOrProvider));
26223
+ // Derived ONCE and handed to every facade that needs it. Each of them
26224
+ // re-deriving `Signer.isSigner` is how two facades come to disagree
26225
+ // about whether the same instance can write.
26226
+ const isReadOnly = !Signer.isSigner(signerOrProvider);
26227
+ this.deposits = new DepositsFacade(sdk.UserLending, chainConfig.chainId.toString(), isReadOnly);
25177
26228
  this.portfolio = new PortfolioFacade(sdk.DataService, sdk.UserLending, sdk.Portfolio);
26229
+ this.flows = new FlowsFacade(this.deposits, () => erc20Of(chainConfig, signerOrProvider), isReadOnly, chainConfig.contracts.LendingPoolManager);
25178
26230
  }
25179
26231
  /**
25180
26232
  * Create a Kasu instance with built-in chain config.
@@ -25306,6 +26358,23 @@ function rpcUrlsOf(chainConfig) {
25306
26358
  var _a;
25307
26359
  return (_a = chainConfig.rpcUrls) !== null && _a !== void 0 ? _a : [];
25308
26360
  }
26361
+ /**
26362
+ * The chain's stable token, bound to whatever this instance holds.
26363
+ *
26364
+ * Built per call rather than cached: it is one `new Contract`, and a cached
26365
+ * binding would outlive the signer a `connect()` replaced. A config with no
26366
+ * `stableAsset` (a hand-written entry from before 2.5.0) throws here rather
26367
+ * than inside ethers, naming the two ports that make the flow work without
26368
+ * one.
26369
+ */
26370
+ function erc20Of(chainConfig, signerOrProvider) {
26371
+ var _a;
26372
+ const address = (_a = stableAssetOf(chainConfig)) === null || _a === void 0 ? void 0 : _a.address;
26373
+ if (!address) {
26374
+ throw new Error('Kasu: this chain config has no stableAsset; pass readAllowance and approve ports explicitly');
26375
+ }
26376
+ return IERC20MetadataAbi__factory.connect(address, signerOrProvider);
26377
+ }
25309
26378
  /**
25310
26379
  * The read-only provider used when the caller passes no `signerOrProvider`.
25311
26380
  *
@@ -25672,165 +26741,6 @@ function getInstitutionalLender(originator) {
25672
26741
  return originator.name === APXIUM.name ? RIXON_CAPITAL : null;
25673
26742
  }
25674
26743
 
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
26744
  /**
25835
26745
  * Cycles and the clearing window — the protocol's weekly clock, as numbers.
25836
26746
  *
@@ -25977,60 +26887,4 @@ function getTrancheDisplayName(trancheName, pool) {
25977
26887
  : trancheName;
25978
26888
  }
25979
26889
 
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 };
26890
+ 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, 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, deriveCycleDates, derivePoolStatus, deriveRequestState, encodeDepositData, epochRateToApy, 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 };