@kasufinance/kasu-sdk 2.5.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 (128) hide show
  1. package/README.md +144 -7
  2. package/dist/bundle.cjs.js +1667 -21
  3. package/dist/bundle.esm.js +1630 -22
  4. package/dist/domain/au-minimum.d.ts +135 -0
  5. package/dist/domain/au-minimum.js +154 -0
  6. package/dist/domain/au-minimum.js.map +1 -0
  7. package/dist/domain/index.d.ts +18 -3
  8. package/dist/domain/index.js +13 -3
  9. package/dist/domain/index.js.map +1 -1
  10. package/dist/domain/loan-contract.d.ts +174 -0
  11. package/dist/domain/loan-contract.js +160 -0
  12. package/dist/domain/loan-contract.js.map +1 -0
  13. package/dist/domain/requests.d.ts +219 -0
  14. package/dist/domain/requests.js +218 -0
  15. package/dist/domain/requests.js.map +1 -0
  16. package/dist/domain/settlement.d.ts +97 -0
  17. package/dist/domain/settlement.js +117 -0
  18. package/dist/domain/settlement.js.map +1 -0
  19. package/dist/domain/wallet-errors.d.ts +92 -0
  20. package/dist/domain/wallet-errors.js +155 -0
  21. package/dist/domain/wallet-errors.js.map +1 -0
  22. package/dist/facade/chain-configs.js +7 -1
  23. package/dist/facade/chain-configs.js.map +1 -1
  24. package/dist/facade/deposits.js +2 -1
  25. package/dist/facade/deposits.js.map +1 -1
  26. package/dist/facade/flows.d.ts +95 -0
  27. package/dist/facade/flows.js +116 -0
  28. package/dist/facade/flows.js.map +1 -0
  29. package/dist/facade/index.d.ts +3 -0
  30. package/dist/facade/index.js +3 -0
  31. package/dist/facade/index.js.map +1 -1
  32. package/dist/facade/kasu.d.ts +6 -2
  33. package/dist/facade/kasu.js +28 -3
  34. package/dist/facade/kasu.js.map +1 -1
  35. package/dist/facade/read-only.d.ts +12 -0
  36. package/dist/facade/read-only.js +13 -0
  37. package/dist/facade/read-only.js.map +1 -0
  38. package/dist/facade/user-portfolio.d.ts +18 -0
  39. package/dist/facade/user-portfolio.js +23 -0
  40. package/dist/facade/user-portfolio.js.map +1 -1
  41. package/dist/flows/deposit-flow.d.ts +301 -0
  42. package/dist/flows/deposit-flow.js +358 -0
  43. package/dist/flows/deposit-flow.js.map +1 -0
  44. package/dist/flows/flow.d.ts +72 -0
  45. package/dist/flows/flow.js +110 -0
  46. package/dist/flows/flow.js.map +1 -0
  47. package/dist/flows/index.d.ts +19 -0
  48. package/dist/flows/index.js +17 -0
  49. package/dist/flows/index.js.map +1 -0
  50. package/dist/flows/observable.d.ts +59 -0
  51. package/dist/flows/observable.js +81 -0
  52. package/dist/flows/observable.js.map +1 -0
  53. package/dist/flows/withdraw-flow.d.ts +99 -0
  54. package/dist/flows/withdraw-flow.js +83 -0
  55. package/dist/flows/withdraw-flow.js.map +1 -0
  56. package/dist/index.d.ts +2 -0
  57. package/dist/index.js +7 -0
  58. package/dist/index.js.map +1 -1
  59. package/dist/services/DataService/data-service.js +3 -11
  60. package/dist/services/DataService/data-service.js.map +1 -1
  61. package/dist/services/DataService/directus-client.d.ts +26 -0
  62. package/dist/services/DataService/directus-client.js +38 -0
  63. package/dist/services/DataService/directus-client.js.map +1 -0
  64. package/dist/services/UserLending/user-lending.js +11 -7
  65. package/dist/services/UserLending/user-lending.js.map +1 -1
  66. package/package.json +8 -2
  67. package/src/domain/au-minimum.ts +192 -0
  68. package/src/domain/index.ts +73 -3
  69. package/src/domain/loan-contract.ts +275 -0
  70. package/src/domain/requests.ts +467 -0
  71. package/src/domain/settlement.ts +161 -0
  72. package/src/domain/wallet-errors.ts +173 -0
  73. package/src/facade/chain-configs.ts +7 -1
  74. package/src/facade/deposits.ts +2 -3
  75. package/src/facade/flows.ts +172 -0
  76. package/src/facade/index.ts +8 -0
  77. package/src/facade/kasu.ts +43 -3
  78. package/src/facade/read-only.ts +13 -0
  79. package/src/facade/user-portfolio.ts +24 -0
  80. package/src/flows/deposit-flow.ts +775 -0
  81. package/src/flows/flow.ts +108 -0
  82. package/src/flows/index.ts +45 -0
  83. package/src/flows/observable.ts +97 -0
  84. package/src/flows/withdraw-flow.ts +210 -0
  85. package/src/index.ts +9 -0
  86. package/src/services/DataService/data-service.ts +7 -25
  87. package/src/services/DataService/directus-client.ts +54 -0
  88. package/src/services/UserLending/user-lending.ts +17 -21
  89. package/dist/domain/deposit-bounds.test.d.ts +0 -1
  90. package/dist/domain/deposit-bounds.test.js +0 -135
  91. package/dist/domain/deposit-bounds.test.js.map +0 -1
  92. package/dist/domain/partners.test.d.ts +0 -1
  93. package/dist/domain/partners.test.js +0 -53
  94. package/dist/domain/partners.test.js.map +0 -1
  95. package/dist/domain/pools.test.d.ts +0 -1
  96. package/dist/domain/pools.test.js +0 -184
  97. package/dist/domain/pools.test.js.map +0 -1
  98. package/dist/domain/rates.test.d.ts +0 -1
  99. package/dist/domain/rates.test.js +0 -181
  100. package/dist/domain/rates.test.js.map +0 -1
  101. package/dist/domain/tranche-display-name.test.d.ts +0 -1
  102. package/dist/domain/tranche-display-name.test.js +0 -58
  103. package/dist/domain/tranche-display-name.test.js.map +0 -1
  104. package/dist/domain/tranches.test.d.ts +0 -1
  105. package/dist/domain/tranches.test.js +0 -206
  106. package/dist/domain/tranches.test.js.map +0 -1
  107. package/dist/facade/config.test.d.ts +0 -1
  108. package/dist/facade/config.test.js +0 -216
  109. package/dist/facade/config.test.js.map +0 -1
  110. package/dist/facade/facade.test.d.ts +0 -1
  111. package/dist/facade/facade.test.js +0 -201
  112. package/dist/facade/facade.test.js.map +0 -1
  113. package/dist/services/Locking/calculate-apy.test.d.ts +0 -1
  114. package/dist/services/Locking/calculate-apy.test.js +0 -41
  115. package/dist/services/Locking/calculate-apy.test.js.map +0 -1
  116. package/dist/tests/sample.test.d.ts +0 -1
  117. package/dist/tests/sample.test.js +0 -59
  118. package/dist/tests/sample.test.js.map +0 -1
  119. package/src/domain/deposit-bounds.test.ts +0 -200
  120. package/src/domain/partners.test.ts +0 -83
  121. package/src/domain/pools.test.ts +0 -260
  122. package/src/domain/rates.test.ts +0 -254
  123. package/src/domain/tranche-display-name.test.ts +0 -96
  124. package/src/domain/tranches.test.ts +0 -300
  125. package/src/facade/config.test.ts +0 -265
  126. package/src/facade/facade.test.ts +0 -250
  127. package/src/services/Locking/calculate-apy.test.ts +0 -52
  128. package/src/tests/sample.test.ts +0 -63
@@ -15719,6 +15719,43 @@ function filterArray(array, id_in) {
15719
15719
  }
15720
15720
  }
15721
15721
 
15722
+ /**
15723
+ * The error a CMS-only call raises on a deployment configured without
15724
+ * Directus. Named so a caller can match on it rather than on the message.
15725
+ */
15726
+ const NO_DIRECTUS_URL_MESSAGE = 'Kasu: this call needs Directus, but the SDK was configured without a ' +
15727
+ '`directusUrl`. On-chain data (pools, tranches, positions, requests) ' +
15728
+ 'works without one; CMS content does not.';
15729
+ /**
15730
+ * Build the Directus client, or a stand-in that refuses clearly.
15731
+ *
15732
+ * `directusUrl` is documented optional, and most of the SDK genuinely does not
15733
+ * need it — pools, tranches, positions and request history all come from the
15734
+ * subgraph and the chain. But `createDirectus('')` throws `Invalid URL` inside
15735
+ * the constructor, so omitting the URL used to make the whole SDK
15736
+ * unconstructable rather than merely CMS-less.
15737
+ *
15738
+ * With no URL, the services skip Directus where they can degrade (pool
15739
+ * descriptions, images and Directus pool names simply do not appear, and the
15740
+ * raw subgraph names are used instead), and a call that exists ONLY to read
15741
+ * CMS content rejects with `NO_DIRECTUS_URL_MESSAGE` — a sentence that says
15742
+ * what to configure, rather than a `null` dereference thrown from inside a
15743
+ * vendor SDK.
15744
+ */
15745
+ function createDirectusClient(directusUrl) {
15746
+ if (directusUrl) {
15747
+ return le(directusUrl)
15748
+ .with(ne())
15749
+ .with(Zp());
15750
+ }
15751
+ const refuse = () => {
15752
+ throw new Error(NO_DIRECTUS_URL_MESSAGE);
15753
+ };
15754
+ // A stand-in, not a client: every entry point the services use goes
15755
+ // through `request`, so refusing there covers all of them.
15756
+ return { request: refuse };
15757
+ }
15758
+
15722
15759
  const getPoolOverviewQuery = (ids) => gql `
15723
15760
  query getAllPoolOverview($epochId: String!, $unusedPools: [String]!) {
15724
15761
  lendingPools(
@@ -15874,15 +15911,7 @@ class DataService {
15874
15911
  this._kasuConfig = _kasuConfig;
15875
15912
  this._externalTvlAbi = KasuPoolExternalTVLAbi__factory.connect(_kasuConfig.contracts.ExternalTVL, signerOrProvider);
15876
15913
  this._graph = new GraphQLClient(_kasuConfig.subgraphUrl);
15877
- if (_kasuConfig.directusUrl) {
15878
- this._directus = le(_kasuConfig.directusUrl)
15879
- .with(ne())
15880
- .with(Zp());
15881
- }
15882
- else {
15883
- // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-explicit-any
15884
- this._directus = null;
15885
- }
15914
+ this._directus = createDirectusClient(_kasuConfig.directusUrl);
15886
15915
  }
15887
15916
  getUrlFromFile(fileName) {
15888
15917
  return `${this._kasuConfig.directusUrl}assets/${fileName}`;
@@ -16176,7 +16205,6 @@ class DataService {
16176
16205
  return __awaiter(this, void 0, void 0, function* () {
16177
16206
  var _a;
16178
16207
  const poolDelegateProfileAndHistoryDirectus = (yield this._directus.request(bs('PoolDelegateProfileAndHistory', {
16179
- // @ts-ignore Directus' deep-fields typing is fragile across versions
16180
16208
  fields: ['*', { otherPools: ['*'] }],
16181
16209
  })));
16182
16210
  const [poolNames, directusPoolNames] = yield Promise.all([
@@ -17136,9 +17164,7 @@ class UserLending {
17136
17164
  this._clearingCoordinatorAbi = IClearingCoordinatorAbi__factory.connect(_kasuConfig.contracts.ClearingCoordinator, signerOrProvider);
17137
17165
  this._systemVariablesAbi = ISystemVariablesAbi__factory.connect(_kasuConfig.contracts.SystemVariables, signerOrProvider);
17138
17166
  this._dataService = new DataService(_kasuConfig, signerOrProvider);
17139
- this._directus = le(_kasuConfig.directusUrl)
17140
- .with(ne())
17141
- .with(Zp());
17167
+ this._directus = createDirectusClient(_kasuConfig.directusUrl);
17142
17168
  }
17143
17169
  getUserTotalPendingAndActiveDepositedAmount(user) {
17144
17170
  return __awaiter(this, void 0, void 0, function* () {
@@ -17256,9 +17282,14 @@ class UserLending {
17256
17282
  unusedPools: this._kasuConfig.UNUSED_LENDING_POOL_IDS,
17257
17283
  epochId,
17258
17284
  }),
17259
- this._directus.request(bs('PoolOverview', {
17260
- fields: ['id', 'poolName', 'subheading'],
17261
- })),
17285
+ // Directus supplies the display pool NAME only; without it the
17286
+ // raw subgraph name is used, which is what the fallback below
17287
+ // already does for a pool with no CMS entry.
17288
+ this._kasuConfig.directusUrl
17289
+ ? this._directus.request(bs('PoolOverview', {
17290
+ fields: ['id', 'poolName', 'subheading'],
17291
+ }))
17292
+ : [],
17262
17293
  ]);
17263
17294
  const retn = [];
17264
17295
  for (const userRequest of subgraphResult.userRequests) {
@@ -24293,7 +24324,13 @@ const CHAIN_CONFIGS = {
24293
24324
  ClearingCoordinator: '',
24294
24325
  ExternalTVL: '',
24295
24326
  },
24296
- subgraphUrl: 'https://api.goldsky.com/api/public/project_cmgzlpxm300765np2a19421om/subgraphs/kasu-plume/prod',
24327
+ // The frozen Plume history is indexed on the LEGACY Goldsky project,
24328
+ // not the one the live chains use: the same path under the current
24329
+ // project 404s. Verified 2026-09-05 — this URL answers
24330
+ // `{ lendingPools { id name } }` with the three Plume pools; the
24331
+ // current-project spelling returns HTTP 404. Note the `/gn` suffix,
24332
+ // which the current project's URLs do not carry.
24333
+ subgraphUrl: 'https://api.goldsky.com/api/public/project_cm9t3064xeuyn01tgctdo3c17/subgraphs/kasu-plume/prod/gn',
24297
24334
  directusUrl: 'https://kasu-finance.directus.app/',
24298
24335
  unusedPoolIds: [],
24299
24336
  poolMetadataMapping: undefined,
@@ -24313,6 +24350,19 @@ const CHAIN_CONFIGS = {
24313
24350
  },
24314
24351
  };
24315
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
+
24316
24366
  /**
24317
24367
  * High-level facade for deposit and withdrawal operations.
24318
24368
  *
@@ -24341,7 +24391,7 @@ class DepositsFacade {
24341
24391
  */
24342
24392
  assertWritable() {
24343
24393
  if (this._isReadOnly) {
24344
- throw new Error('Kasu: this instance is read-only; call kasu.connect(signer) first');
24394
+ throw new Error(READ_ONLY_MESSAGE);
24345
24395
  }
24346
24396
  }
24347
24397
  /**
@@ -24414,6 +24464,1024 @@ class DepositsFacade {
24414
24464
  }
24415
24465
  }
24416
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.
25407
+ */
25408
+ _erc20,
25409
+ /** The read-only flag `Kasu` already computed — never re-derived here. */
25410
+ _isReadOnly,
25411
+ /**
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.
25417
+ */
25418
+ _spender) {
25419
+ this._deposits = _deposits;
25420
+ this._erc20 = _erc20;
25421
+ this._isReadOnly = _isReadOnly;
25422
+ this._spender = _spender;
25423
+ }
25424
+ /**
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).
25429
+ *
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.
25435
+ */
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,
25458
+ });
25459
+ }
25460
+ /**
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.
25464
+ */
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)),
25476
+ });
25477
+ }
25478
+ _assertWritable() {
25479
+ if (this._isReadOnly) {
25480
+ throw new Error(READ_ONLY_MESSAGE);
25481
+ }
25482
+ }
25483
+ }
25484
+
24417
25485
  /**
24418
25486
  * Minimum remaining capacity (in stable-asset units) for a tranche to be
24419
25487
  * selectable. Mirrors `MIN_CAPACITY = toBigNumber('1')` in kasu-fe-next's
@@ -24833,6 +25901,230 @@ class StrategiesFacade {
24833
25901
  }
24834
25902
  }
24835
25903
 
25904
+ var UserRequestStatus;
25905
+ (function (UserRequestStatus) {
25906
+ UserRequestStatus["REQUESTED"] = "Requested";
25907
+ UserRequestStatus["PROCESSING"] = "Processing";
25908
+ UserRequestStatus["PROCESSED"] = "Processed";
25909
+ })(UserRequestStatus || (UserRequestStatus = {}));
25910
+
25911
+ /**
25912
+ * Events that represent a lender SUBMISSION into the bundle. A dNFT position
25913
+ * aggregates every submission the lender made into the same pool/tranche this
25914
+ * cycle: the first is `Initiated`, each subsequent top-up is `Increased`.
25915
+ * Everything else on the timeline (Accepted / Rejected / Cancelled /
25916
+ * Reallocated / Forced) is an OUTCOME, not a request, and must not be counted.
25917
+ */
25918
+ const SUBMISSION_EVENTS = new Set(['Initiated', 'Increased']);
25919
+ /**
25920
+ * The submissions bundled into one dNFT-aggregate request row, input order
25921
+ * preserved — one loan agreement per submission.
25922
+ */
25923
+ function submissionEvents(events) {
25924
+ return events.filter((e) => SUBMISSION_EVENTS.has(e.requestType));
25925
+ }
25926
+ /** Count the submissions bundled into one dNFT-aggregate request row. */
25927
+ function countSubmissions(events) {
25928
+ return submissionEvents(events).length;
25929
+ }
25930
+ /**
25931
+ * Timestamp of the FIRST submission in the bundle. Falls back to `fallback`
25932
+ * when the `Initiated` event has not indexed yet — the caller decides what
25933
+ * that is (kasu-ui passes the request's own timestamp).
25934
+ */
25935
+ function firstSubmissionTimestamp(events, fallback) {
25936
+ const submissions = submissionEvents(events);
25937
+ if (submissions.length === 0)
25938
+ return fallback;
25939
+ return submissions.reduce((min, e) => (e.timestamp < min ? e.timestamp : min), Infinity);
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
+ }
25951
+ /**
25952
+ * Has THIS request's cycle closed? — the single open/closed signal behind the
25953
+ * status vocabulary and behind Cancel.
25954
+ *
25955
+ * `request.canCancel` is the SDK's `isCancelable(status, poolId)` —
25956
+ * `status !== 'Processed' && !isLendingPoolClearingPending(pool)`. It is
25957
+ * per-POOL and reads the same condition the contract enforces on the cancel
25958
+ * call — but it reads it ONCE, when the request was fetched. Nothing about
25959
+ * this value is live, so a client that holds a request across a cycle close
25960
+ * must refetch before acting on it.
25961
+ *
25962
+ * The raw subgraph `status` must NOT feed this: `'Processing'` is a STICKY
25963
+ * historical marker set on the first partial fill and never reset, so gating
25964
+ * on it would freeze a partly-filled request in Processing forever. A global
25965
+ * settlement clock is equally wrong here — it is blind to whether THIS
25966
+ * request's pool is already clearing.
25967
+ */
25968
+ function isCycleClosed(request) {
25969
+ return !request.canCancel;
25970
+ }
25971
+ const isCancelled = (events) => events.some((e) => e.requestType === 'Cancelled');
25972
+ const isForced = (events) => events.some((e) => e.requestType === 'Forced');
25973
+ const initiatedEvent = (events) => events.find((e) => e.requestType === 'Initiated');
25974
+ /**
25975
+ * Subgraph behaviour: when a request is cancelled, the on-request
25976
+ * `requestedAmount` field is reset to 0 (the lender's effective balance is
25977
+ * restored). The original amount survives on the `Initiated` event's
25978
+ * `assetAmount`. Recover from there so cancelled rows still carry the amount
25979
+ * the lender originally asked for.
25980
+ */
25981
+ const initiatedAmountOf = (events) => {
25982
+ const initiated = initiatedEvent(events);
25983
+ return initiated ? Number(initiated.assetAmount || '0') : 0;
25984
+ };
25985
+ /**
25986
+ * A deposit is REALLOCATED when the timeline carries a `Reallocated` event, or
25987
+ * an `Accepted` event into a tranche other than the one requested.
25988
+ */
25989
+ const findReallocation = (events, originalTrancheId) => events.find((e) => e.requestType === 'Reallocated' ||
25990
+ (e.requestType === 'Accepted' &&
25991
+ e.trancheId.toLowerCase() !==
25992
+ originalTrancheId.toLowerCase()));
25993
+ /** kasu-ui's `num`: an absent or unparseable figure reads as 0. */
25994
+ const num = (str) => {
25995
+ const n = Number(str !== null && str !== void 0 ? str : '0');
25996
+ return Number.isFinite(n) ? n : 0;
25997
+ };
25998
+ /** The same parse, keeping "the subgraph reported nothing" distinct from 0. */
25999
+ const numOrNull = (str) => {
26000
+ if (str === undefined || str === null || str.trim() === '')
26001
+ return null;
26002
+ const n = Number(str);
26003
+ return Number.isFinite(n) ? n : null;
26004
+ };
26005
+ /**
26006
+ * Convert a `UserRequest` into a `RequestState`. Pure — no clock, no network,
26007
+ * no copy.
26008
+ *
26009
+ * BRANCH ORDER (this IS the behaviour; it reproduces kasu-ui's
26010
+ * `deriveTransactionView` check for check):
26011
+ *
26012
+ * 1. a `Cancelled` event → `cancelled`, neutral, 0
26013
+ * 2. a withdrawal with a `Forced` event → `forced`, outflow, −accepted
26014
+ * 3. a reallocated deposit → `reallocated`, inflow, +accepted
26015
+ * 4. a withdrawal partly filled with a LIVE
26016
+ * remainder (cycle still open) → `partial`, outflow, −accepted
26017
+ * 5. resolved (`status === 'Processed'`):
26018
+ * withdrawal, partly filled → `partial`, outflow, −accepted
26019
+ * withdrawal, fully filled → `complete`, outflow, −accepted
26020
+ * deposit, nothing accepted → `rejected`, neutral, 0
26021
+ * deposit, part rejected → `partial`, inflow, +accepted
26022
+ * deposit, fully accepted → `complete`, inflow, +accepted
26023
+ * 6. otherwise → `pending`, ±requested
26024
+ *
26025
+ * `cancelled` is reachable ONLY from branch 1 — a Cancelled EVENT. No
26026
+ * processing or resolved state can derive it.
26027
+ *
26028
+ * Branch 4 is checked BEFORE the resolved branch and gates on `isCycleClosed`
26029
+ * (i.e. `canCancel`), never on the sticky raw status: a withdrawal that was
26030
+ * partly filled returns to the queue with a live Cancel, and reading the raw
26031
+ * status would strand it.
26032
+ *
26033
+ * WHAT THE APPLICATION STILL OWNS: the status word and the detail line beneath
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 —
26038
+ * `requestType === 'Deposit' && statusCode !== 'cancelled' && statusCode !== 'rejected'`
26039
+ * — because neither a cancelled nor a fully-rejected deposit ever issued one,
26040
+ * and withdrawals sign no agreement at all.
26041
+ */
26042
+ function deriveRequestState(request) {
26043
+ var _a, _b, _c;
26044
+ const isWithdrawal = request.requestType === 'Withdrawal';
26045
+ const cancelled = isCancelled(request.events);
26046
+ // Cancelled requests have `requestedAmount` zeroed on the request itself;
26047
+ // pull the original value from the Initiated event so the row still
26048
+ // carries "100 cancelled" instead of "0 cancelled".
26049
+ const requested = cancelled
26050
+ ? num(request.requestedAmount) || initiatedAmountOf(request.events)
26051
+ : num(request.requestedAmount);
26052
+ const accepted = num(request.acceptedAmount);
26053
+ const rejected = num(request.rejectedAmount);
26054
+ const forced = isWithdrawal && isForced(request.events);
26055
+ const reallocation = !isWithdrawal && findReallocation(request.events, request.trancheId);
26056
+ const initiated = initiatedEvent(request.events);
26057
+ const base = {
26058
+ id: request.id,
26059
+ contractId: (_a = initiated === null || initiated === void 0 ? void 0 : initiated.id) !== null && _a !== void 0 ? _a : '',
26060
+ poolId: request.lendingPool.id.toLowerCase(),
26061
+ poolName: request.lendingPool.name,
26062
+ trancheName: request.trancheName,
26063
+ trancheId: request.trancheId,
26064
+ fixedTermConfigId: (_c = (_b = request.fixedTermConfig) === null || _b === void 0 ? void 0 : _b.configId) !== null && _c !== void 0 ? _c : '0',
26065
+ requestType: request.requestType,
26066
+ rawStatus: request.status,
26067
+ requestedAmount: requested,
26068
+ acceptedAmount: numOrNull(request.acceptedAmount),
26069
+ initiatedAmount: initiated
26070
+ ? initiatedAmountOf(request.events)
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),
26078
+ submissionCount: countSubmissions(request.events),
26079
+ // `firstSubmissionTimestamp` needs a fallback it will never use here:
26080
+ // the bundle is non-empty on every path that reaches the call.
26081
+ firstSubmissionTimestamp: countSubmissions(request.events) === 0
26082
+ ? null
26083
+ : firstSubmissionTimestamp(request.events, 0),
26084
+ cycleClosed: isCycleClosed(request),
26085
+ canCancel: request.canCancel,
26086
+ };
26087
+ // 1. Cancelled wins over everything — the ONLY path to `cancelled`.
26088
+ if (cancelled) {
26089
+ return Object.assign(Object.assign({}, base), { kind: 'neutral', amount: 0, statusCode: 'cancelled' });
26090
+ }
26091
+ // 2. Forced withdrawal (credit originator returned funds early).
26092
+ if (forced) {
26093
+ return Object.assign(Object.assign({}, base), { kind: 'outflow', amount: -accepted, statusCode: 'forced' });
26094
+ }
26095
+ // 3. Reallocated deposit (accepted into a different lending option).
26096
+ if (reallocation) {
26097
+ return Object.assign(Object.assign({}, base), { kind: 'inflow', amount: accepted, statusCode: 'reallocated' });
26098
+ }
26099
+ // 4. Withdrawal partly filled with a LIVE remainder: the request returns
26100
+ // to the queue with a live Cancel. Checked BEFORE the resolved branch and
26101
+ // via `isCycleClosed`, never via the sticky raw status.
26102
+ if (isWithdrawal &&
26103
+ accepted > 0 &&
26104
+ accepted < requested &&
26105
+ !isCycleClosed(request)) {
26106
+ return Object.assign(Object.assign({}, base), { kind: 'outflow', amount: -accepted, statusCode: 'partial' });
26107
+ }
26108
+ // 5. Resolved — a rejection IS a resolution.
26109
+ if (request.status === UserRequestStatus.PROCESSED) {
26110
+ if (isWithdrawal) {
26111
+ const partly = accepted < requested;
26112
+ return Object.assign(Object.assign({}, base), { kind: 'outflow', amount: -accepted, statusCode: partly ? 'partial' : 'complete' });
26113
+ }
26114
+ // Deposit: full reject vs partial vs full accept.
26115
+ if (accepted === 0) {
26116
+ return Object.assign(Object.assign({}, base), { kind: 'neutral', amount: 0, statusCode: 'rejected' });
26117
+ }
26118
+ if (rejected > 0) {
26119
+ return Object.assign(Object.assign({}, base), { kind: 'inflow', amount: accepted, statusCode: 'partial' });
26120
+ }
26121
+ return Object.assign(Object.assign({}, base), { kind: 'inflow', amount: accepted, statusCode: 'complete' });
26122
+ }
26123
+ // 6. Unresolved. `cycleClosed` tells the caller whether to render its
26124
+ // "queued" or its "processing" word; the code is the same either way.
26125
+ return Object.assign(Object.assign({}, base), { kind: isWithdrawal ? 'outflow' : 'inflow', amount: isWithdrawal ? -requested : requested, statusCode: 'pending' });
26126
+ }
26127
+
24836
26128
  /**
24837
26129
  * High-level facade for querying a user's portfolio, positions, and history.
24838
26130
  *
@@ -24875,13 +26167,36 @@ class PortfolioFacade {
24875
26167
  return yield this._userLending.getUserRequests(userAddress, currentEpoch);
24876
26168
  });
24877
26169
  }
26170
+ /**
26171
+ * The same history, already derived into `RequestState` rows — status
26172
+ * code, kind, signed amount, the cancelled-amount recovery, the bundled
26173
+ * submission count and the cycle-open signal.
26174
+ *
26175
+ * ```ts
26176
+ * const rows = await kasu.portfolio.getRequestStates('0xUser...');
26177
+ * rows.filter((r) => r.statusCode === 'pending');
26178
+ * ```
26179
+ *
26180
+ * Every application derives this from `getTransactionHistory` anyway, and
26181
+ * the derivation is the part they were each getting subtly differently.
26182
+ * Words are still the caller's: render `statusCode` in your own
26183
+ * vocabulary, and call `getTrancheDisplayName` on `trancheName` at the
26184
+ * view boundary.
26185
+ */
26186
+ getRequestStates(userAddress) {
26187
+ return __awaiter(this, void 0, void 0, function* () {
26188
+ const requests = yield this.getTransactionHistory(userAddress);
26189
+ return requests.map(deriveRequestState);
26190
+ });
26191
+ }
24878
26192
  }
24879
26193
 
24880
26194
  /**
24881
26195
  * High-level entry point for external integrators.
24882
26196
  *
24883
- * Provides three domain facades — `strategies`, `deposits`, `portfolio` — and
24884
- * 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.
24885
26200
  *
24886
26201
  * ```ts
24887
26202
  * import { Kasu } from '@kasufinance/kasu-sdk';
@@ -24905,8 +26220,13 @@ class Kasu {
24905
26220
  this._signerOrProvider = signerOrProvider;
24906
26221
  this._configOverrides = configOverrides;
24907
26222
  this.strategies = new StrategiesFacade(sdk.DataService, sdk.UserLending);
24908
- 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);
24909
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);
24910
26230
  }
24911
26231
  /**
24912
26232
  * Create a Kasu instance with built-in chain config.
@@ -25038,6 +26358,23 @@ function rpcUrlsOf(chainConfig) {
25038
26358
  var _a;
25039
26359
  return (_a = chainConfig.rpcUrls) !== null && _a !== void 0 ? _a : [];
25040
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
+ }
25041
26378
  /**
25042
26379
  * The read-only provider used when the caller passes no `signerOrProvider`.
25043
26380
  *
@@ -25123,6 +26460,160 @@ function fetchUnusedPoolIds() {
25123
26460
  });
25124
26461
  }
25125
26462
 
26463
+ /**
26464
+ * The AU cumulative-lending minimum — the numeric half.
26465
+ *
26466
+ * RULE: a lender whose verified KYC country is Australia may only lend when
26467
+ * their existing deposited position on THIS deployment, plus the amount they
26468
+ * are asking for, reaches the deployment's threshold.
26469
+ *
26470
+ * This is UX PRE-VALIDATION ONLY. kasu-backend enforces the rule
26471
+ * authoritatively at contract generation and refuses with HTTP 403
26472
+ * `AU_WHOLESALE_MINIMUM_NOT_MET`; a lender who gets past this check is still
26473
+ * stopped there. What these helpers exist for is to raise the amount field's
26474
+ * minimum so the lender learns the rule while typing rather than at the end.
26475
+ *
26476
+ * FAIL-OPEN by design: an absent or unknown country is NOT restricted, and an
26477
+ * unlisted stable symbol has no threshold. An UNKNOWN existing position is
26478
+ * treated as 0 — strict, so the floor is never advertised lower than the
26479
+ * backend will accept, and it relaxes once the position loads.
26480
+ *
26481
+ * Arithmetic is integer bigint in minor units (10^decimals) so no two
26482
+ * consumers can disagree at the boundary. Parsing TRUNCATES, never rounds up —
26483
+ * a position can never be inflated into passing. `BigInt(...)` calls only, no
26484
+ * bigint literals, so consumers on an older target still compile.
26485
+ *
26486
+ * Lifted from kasu-ui's `features/lending/lib/au-lending-restriction.ts`. The
26487
+ * two toast strings that live there are copy and stay in the applications.
26488
+ */
26489
+ const ZERO = BigInt(0);
26490
+ /** ISO 3166-1 alpha-3 for Australia — the collapsed KYC country field. */
26491
+ const AU_ALPHA3 = 'AUS';
26492
+ /**
26493
+ * Is this the Australian KYC country? Case-insensitive and
26494
+ * whitespace-tolerant. Anything that is not a string — including the
26495
+ * `undefined` of an unloaded KYC record — is not restricted (fail-open).
26496
+ *
26497
+ * The alpha-2 `'AU'` deliberately does NOT match: the KYC country reaching
26498
+ * this rule is normalised to alpha-3 upstream, and a bare two-letter code
26499
+ * here means something else went wrong.
26500
+ */
26501
+ function isAustralianKyc(country) {
26502
+ if (typeof country !== 'string')
26503
+ return false;
26504
+ return country.trim().toUpperCase() === AU_ALPHA3;
26505
+ }
26506
+ /**
26507
+ * Minimum CUMULATIVE position, in WHOLE stable units, keyed on the
26508
+ * deployment's stable-asset symbol (a property of the currency, not the
26509
+ * chain). Must match kasu-backend's table exactly.
26510
+ */
26511
+ const AU_MIN_CUMULATIVE_BY_STABLE = {
26512
+ USDC: 360000,
26513
+ AUDD: 500000,
26514
+ };
26515
+ /**
26516
+ * Threshold in whole units, or `undefined` for an unlisted stable — a
26517
+ * deployment whose currency has no configured minimum is unrestricted.
26518
+ */
26519
+ function auThresholdFor(symbol) {
26520
+ if (typeof symbol !== 'string')
26521
+ return undefined;
26522
+ return AU_MIN_CUMULATIVE_BY_STABLE[symbol.trim().toUpperCase()];
26523
+ }
26524
+ /**
26525
+ * Is this wallet released from the minimum entirely, whatever its country,
26526
+ * stable or position says?
26527
+ *
26528
+ * `exemptAddresses` is DEPLOYMENT CONFIGURATION the caller supplies, not a
26529
+ * constant of this package. kasu-sdk is published publicly; the exempt list is
26530
+ * a compliance carve-out naming particular lender wallets, so it does not
26531
+ * belong in a public tarball. Read it from wherever the application keeps its
26532
+ * deployment configuration, and keep it identical to kasu-backend's
26533
+ * `AU_WHOLESALE_EXEMPT_ADDRESSES` — that is where the rule is actually
26534
+ * enforced. An address exempt here but not there sees no raised minimum in the
26535
+ * form and is refused at the end, which is worse than not exempting it at all.
26536
+ *
26537
+ * The address matched must be the CONNECTED wallet — the one that owns the KYC
26538
+ * record and signs the agreement request. kasu-backend verifies that signature
26539
+ * before the gate, so an exemption cannot be claimed by asserting someone
26540
+ * else's address; it takes their private key. Never match a "view as" address.
26541
+ *
26542
+ * Comparison is case-insensitive and whitespace-tolerant. Anything that is not
26543
+ * a string is NOT exempt (fail closed), and so is anything when the list is
26544
+ * absent.
26545
+ */
26546
+ function isAuMinimumExempt(address, exemptAddresses) {
26547
+ if (typeof address !== 'string' || !exemptAddresses)
26548
+ return false;
26549
+ const needle = address.trim().toLowerCase();
26550
+ return exemptAddresses.some((a) => a.trim().toLowerCase() === needle);
26551
+ }
26552
+ const DECIMAL_RE = /^(\d+)?(?:\.(\d*))?$/;
26553
+ /**
26554
+ * Truncating, partial-input-tolerant decimal → minor-unit parse.
26555
+ * `'10.'` → `10000000n` · `'1.23456789'` → `1234567n` (truncated at 6dp).
26556
+ * `''` / `'abc'` / negative / null → `null`.
26557
+ *
26558
+ * Tolerant of mid-typing states because it runs on an amount field as the
26559
+ * lender types, and truncating because rounding up would let a position that
26560
+ * is a fraction short read as passing.
26561
+ */
26562
+ function parseMinorUnits(value, decimals) {
26563
+ if (value === null || value === undefined)
26564
+ return null;
26565
+ const raw = typeof value === 'number' ? String(value) : value.trim();
26566
+ if (!raw)
26567
+ return null;
26568
+ const match = DECIMAL_RE.exec(raw);
26569
+ if (!match || (!match[1] && !match[2]))
26570
+ return null;
26571
+ // Both capture groups are optional, so either can be absent at runtime.
26572
+ // A fractional group that matched EMPTY ('10.') is not absent, and the
26573
+ // destructuring defaults leave it alone — only `undefined` takes them.
26574
+ const [, whole = '0', fracDigits = ''] = match;
26575
+ const frac = fracDigits.slice(0, decimals).padEnd(decimals, '0');
26576
+ return BigInt(whole + frac);
26577
+ }
26578
+ /**
26579
+ * The amount, in WHOLE stable units, an Australian lender still needs in order
26580
+ * to reach the deployment's cumulative minimum. Apply it as the amount field's
26581
+ * floor via `max(trancheMin, auMinimumRemaining(...))`.
26582
+ *
26583
+ * Returns 0 for everyone the rule does not restrict (fail-open), 0 for an
26584
+ * exempt address, and 0 once the lender's existing position already satisfies
26585
+ * the threshold.
26586
+ *
26587
+ * The exemption is tested FIRST and unconditionally: an exempt wallet has no
26588
+ * minimum whatever its country, stable or position says. kasu-backend
26589
+ * deliberately tests country first and the exemption second — the two orders
26590
+ * are not in conflict, both return "no minimum" for the same inputs. There,
26591
+ * the exemption sets a flag that drives a compliance log, so it must not fire
26592
+ * for a lender the rule never engaged for. Here nothing is logged, so
26593
+ * exemption-first is preferred: it makes this function right on its own,
26594
+ * whatever country a caller happens to pass.
26595
+ */
26596
+ function auMinimumRemaining(input) {
26597
+ var _a, _b;
26598
+ if (isAuMinimumExempt(input.address, input.exemptAddresses))
26599
+ return 0;
26600
+ if (!isAustralianKyc(input.country))
26601
+ return 0;
26602
+ const threshold = auThresholdFor(input.stableSymbol);
26603
+ if (threshold === undefined)
26604
+ return 0;
26605
+ const { existingDeposited, decimals } = input;
26606
+ // A table threshold always parses; `?? ZERO` keeps the rule fail-open
26607
+ // rather than asserting, so an unparseable one yields no minimum at all.
26608
+ const thresholdMinor = (_a = parseMinorUnits(threshold, decimals)) !== null && _a !== void 0 ? _a : ZERO;
26609
+ const existingMinor = (_b = parseMinorUnits(existingDeposited, decimals)) !== null && _b !== void 0 ? _b : ZERO;
26610
+ const remaining = thresholdMinor - existingMinor;
26611
+ if (remaining <= ZERO)
26612
+ return 0;
26613
+ const base = BigInt('1' + '0'.repeat(decimals));
26614
+ return Number(remaining / base) + Number(remaining % base) / Number(base);
26615
+ }
26616
+
25126
26617
  // Fallbacks if the selected tranche's on-chain min/max are 0 / NaN (some
25127
26618
  // "coming soon" pools haven't been configured yet).
25128
26619
  const MIN_LENDING_AMOUNT_FALLBACK = 500;
@@ -25250,6 +26741,123 @@ function getInstitutionalLender(originator) {
25250
26741
  return originator.name === APXIUM.name ? RIXON_CAPITAL : null;
25251
26742
  }
25252
26743
 
26744
+ /**
26745
+ * Cycles and the clearing window — the protocol's weekly clock, as numbers.
26746
+ *
26747
+ * Lifted verbatim from kasu-ui's `features/portfolio/lib/settlement-window.ts`
26748
+ * and `features/lending/lib/cycle-dates.ts`. The two formatters that live
26749
+ * beside `deriveCycleDates` there (`formatCycleDate`, `formatCycleCloseUtc`)
26750
+ * print words and stay in the applications; everything here is unix seconds in
26751
+ * and unix seconds out.
26752
+ *
26753
+ * The clearing window is the fixed 48 hours immediately preceding an epoch
26754
+ * end. Inside it, pending requests are being processed and cannot be modified,
26755
+ * and the countdown runs to the epoch end. Outside it, the countdown runs to
26756
+ * the next clearing-window start.
26757
+ *
26758
+ * The epoch end comes straight from the chain (`nextEpochStartTimestamp`, i.e.
26759
+ * the SDK's `getNextEpochDate`) — the same value the protocol's own
26760
+ * `getNextClearingPeriodDate` derives from — so the window always lines up
26761
+ * with the real weekly schedule (Tue 06:00 → Thu 06:00 UTC on Base) instead of
26762
+ * a projected subgraph timestamp that can drift off the grid.
26763
+ */
26764
+ /**
26765
+ * Clearing-window length — a fixed 48h protocol constant. Exported so every
26766
+ * consumer derives the window from the same number this module runs on.
26767
+ */
26768
+ const CLEARING_WINDOW_SECONDS = 48 * 60 * 60;
26769
+ /**
26770
+ * Weekly cadence — the epoch schedule is fixed weekly (Tue → Thu UTC on Base).
26771
+ * Used only to roll a cycle forward when a request lands inside a window that
26772
+ * has already closed.
26773
+ */
26774
+ const WEEK_SECONDS = 7 * 24 * 60 * 60;
26775
+ /**
26776
+ * Which phase of the weekly cycle `nowSeconds` falls in, and how long is left
26777
+ * of it.
26778
+ *
26779
+ * `'unknown'` when no epoch boundary has been loaded yet, or when the one on
26780
+ * hand is stale (it has already elapsed — the on-chain value refetches to the
26781
+ * next boundary shortly after rollover). A caller must render its "no cycle
26782
+ * loaded" state there, never a zeroed countdown.
26783
+ */
26784
+ function computeSettlementWindow({ nowSeconds, nextEpochStart, clearingWindowSeconds = CLEARING_WINDOW_SECONDS, }) {
26785
+ // No epoch boundary loaded yet, or a stale one that already elapsed.
26786
+ if (nextEpochStart <= 0 || nextEpochStart <= nowSeconds) {
26787
+ return { phase: 'unknown' };
26788
+ }
26789
+ const clearingStart = nextEpochStart - clearingWindowSeconds;
26790
+ if (nowSeconds < clearingStart) {
26791
+ return {
26792
+ phase: 'awaiting',
26793
+ secondsUntilClearing: clearingStart - nowSeconds,
26794
+ nextClearingStart: clearingStart,
26795
+ };
26796
+ }
26797
+ // nowSeconds is in [clearingStart, nextEpochStart) — inside the window.
26798
+ return {
26799
+ phase: 'clearing',
26800
+ secondsUntilEpochEnd: nextEpochStart - nowSeconds,
26801
+ epochEnd: nextEpochStart,
26802
+ };
26803
+ }
26804
+ /**
26805
+ * The next cycle boundary strictly after `nowSeconds`, in unix seconds — the
26806
+ * cycle close (`nextEpochStart − 48h`) while the window is still open, the
26807
+ * epoch end once we are inside it.
26808
+ *
26809
+ * `undefined` when there is no boundary left to wait for: no epoch boundary
26810
+ * loaded, or a cached one that has already elapsed — the same staleness rule
26811
+ * `computeSettlementWindow` applies before it reports `'unknown'`.
26812
+ *
26813
+ * Split out of the state machine because some consumers need the INSTANT
26814
+ * rather than the phase: one to flush the cycle-dependent caches when the
26815
+ * clock crosses it, one to move a pre-commit screen's snapshot clock at the
26816
+ * same moment.
26817
+ */
26818
+ function nextCycleBoundary(nextEpochStart, nowSeconds, clearingWindowSeconds = CLEARING_WINDOW_SECONDS) {
26819
+ if (!nextEpochStart || nextEpochStart <= 0)
26820
+ return undefined;
26821
+ const clearingStart = nextEpochStart - clearingWindowSeconds;
26822
+ if (nowSeconds < clearingStart)
26823
+ return clearingStart;
26824
+ if (nowSeconds < nextEpochStart)
26825
+ return nextEpochStart;
26826
+ return undefined;
26827
+ }
26828
+ /**
26829
+ * The cycle-close and outcome dates for a request submitted `now`.
26830
+ *
26831
+ * - The cycle "closes" (stops accepting requests, starts processing) at the
26832
+ * start of the 48h clearing window, i.e. 48h before the epoch end.
26833
+ * - Processing takes up to 48h, so the outcome is confirmed by the epoch end
26834
+ * (close + 48h).
26835
+ *
26836
+ * Returns `null` when the epoch boundary is not available or is stale — a
26837
+ * caller then omits the dates entirely (omit, don't stub).
26838
+ *
26839
+ * The common case is a request submitted OUTSIDE the clearing window: the
26840
+ * close is `nextEpochStart − 48h` and the outcome is `nextEpochStart`. When
26841
+ * the request lands INSIDE the current clearing window (that close is already
26842
+ * in the past), it queues for the NEXT weekly cycle, so the close is advanced
26843
+ * by whole weeks until it is in the future.
26844
+ */
26845
+ function deriveCycleDates(nextEpochStart, nowSeconds) {
26846
+ // No boundary loaded, or a stale one that already elapsed — the same
26847
+ // staleness rule as `computeSettlementWindow`.
26848
+ if (!nextEpochStart || nextEpochStart <= nowSeconds)
26849
+ return null;
26850
+ let close = nextEpochStart - CLEARING_WINDOW_SECONDS;
26851
+ let outcome = nextEpochStart;
26852
+ // Inside the current clearing window the close already passed; a request
26853
+ // now is queued for the next weekly cycle.
26854
+ while (close <= nowSeconds) {
26855
+ close += WEEK_SECONDS;
26856
+ outcome += WEEK_SECONDS;
26857
+ }
26858
+ return { close, outcome };
26859
+ }
26860
+
25253
26861
  // Business rename (2026-07): Apxium strategies market their top retail tranche
25254
26862
  // as "Upper Mezzanine" — the true senior position is held by the institutional
25255
26863
  // lender (Rixon Capital), so retail lenders are never actually senior in the
@@ -25279,4 +26887,4 @@ function getTrancheDisplayName(trancheName, pool) {
25279
26887
  : trancheName;
25280
26888
  }
25281
26889
 
25282
- export { APXIUM, CHAIN_CONFIGS, DepositsFacade, EPOCHS_IN_YEAR, INVOICEMATE, Kasu, KasuSdk, MAX_LENDING_AMOUNT_FALLBACK, MIN_LENDING_AMOUNT_FALLBACK, MIN_TRANCHE_CAPACITY, PortfolioFacade, RIXON_CAPITAL, SdkConfig, StrategiesFacade, UPPER_MEZZANINE, apyToEpochRate, ceilToCents, compareTrancheSeniority, derivePoolStatus, epochRateToApy, fetchUnusedPoolIds, floorToCents, getCreditOriginator, getInstitutionalLender, getTrancheDisplayName, isBelowMinimumCapacity, maxNetRateCeiling, netEffectiveApy, netTrancheApyBounds, parseTrancheBound, pickDefaultTrancheId, pickHighestYieldTranche, poolAllTranchesFull, poolMaxApy, resolveBoundShortcuts, resolveDepositBounds, selectVisiblePools, 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 };