@kasufinance/kasu-sdk 2.4.2 → 2.6.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 (180) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +201 -253
  3. package/dist/bundle.cjs.js +5472 -1710
  4. package/dist/bundle.esm.js +5415 -1713
  5. package/dist/domain/au-minimum.d.ts +135 -0
  6. package/dist/domain/au-minimum.js +154 -0
  7. package/dist/domain/au-minimum.js.map +1 -0
  8. package/dist/domain/au-minimum.test.js +202 -0
  9. package/dist/domain/au-minimum.test.js.map +1 -0
  10. package/dist/domain/deposit-bounds.d.ts +62 -0
  11. package/dist/domain/deposit-bounds.js +84 -0
  12. package/dist/domain/deposit-bounds.js.map +1 -0
  13. package/dist/domain/deposit-bounds.test.d.ts +1 -0
  14. package/dist/domain/deposit-bounds.test.js +135 -0
  15. package/dist/domain/deposit-bounds.test.js.map +1 -0
  16. package/dist/domain/index.d.ts +40 -0
  17. package/dist/domain/index.js +33 -0
  18. package/dist/domain/index.js.map +1 -0
  19. package/dist/domain/loan-contract.d.ts +174 -0
  20. package/dist/domain/loan-contract.js +160 -0
  21. package/dist/domain/loan-contract.js.map +1 -0
  22. package/dist/domain/loan-contract.test.d.ts +1 -0
  23. package/dist/domain/loan-contract.test.js +255 -0
  24. package/dist/domain/loan-contract.test.js.map +1 -0
  25. package/dist/domain/partners.d.ts +34 -0
  26. package/dist/domain/partners.js +43 -0
  27. package/dist/domain/partners.js.map +1 -0
  28. package/dist/domain/partners.test.d.ts +1 -0
  29. package/dist/domain/partners.test.js +53 -0
  30. package/dist/domain/partners.test.js.map +1 -0
  31. package/dist/domain/pools.d.ts +70 -0
  32. package/dist/domain/pools.js +134 -0
  33. package/dist/domain/pools.js.map +1 -0
  34. package/dist/domain/pools.test.d.ts +1 -0
  35. package/dist/domain/pools.test.js +184 -0
  36. package/dist/domain/pools.test.js.map +1 -0
  37. package/dist/domain/rates.d.ts +83 -0
  38. package/dist/domain/rates.js +120 -0
  39. package/dist/domain/rates.js.map +1 -0
  40. package/dist/domain/rates.test.d.ts +1 -0
  41. package/dist/domain/rates.test.js +181 -0
  42. package/dist/domain/rates.test.js.map +1 -0
  43. package/dist/domain/requests.d.ts +181 -0
  44. package/dist/domain/requests.js +202 -0
  45. package/dist/domain/requests.js.map +1 -0
  46. package/dist/domain/requests.test.d.ts +1 -0
  47. package/dist/domain/requests.test.js +470 -0
  48. package/dist/domain/requests.test.js.map +1 -0
  49. package/dist/domain/settlement.d.ts +97 -0
  50. package/dist/domain/settlement.js +117 -0
  51. package/dist/domain/settlement.js.map +1 -0
  52. package/dist/domain/settlement.test.d.ts +1 -0
  53. package/dist/domain/settlement.test.js +152 -0
  54. package/dist/domain/settlement.test.js.map +1 -0
  55. package/dist/domain/tranche-display-name.d.ts +17 -0
  56. package/dist/domain/tranche-display-name.js +30 -0
  57. package/dist/domain/tranche-display-name.js.map +1 -0
  58. package/dist/domain/tranche-display-name.test.d.ts +1 -0
  59. package/dist/domain/tranche-display-name.test.js +58 -0
  60. package/dist/domain/tranche-display-name.test.js.map +1 -0
  61. package/dist/domain/tranches.d.ts +89 -0
  62. package/dist/domain/tranches.js +150 -0
  63. package/dist/domain/tranches.js.map +1 -0
  64. package/dist/domain/tranches.test.d.ts +1 -0
  65. package/dist/domain/tranches.test.js +206 -0
  66. package/dist/domain/tranches.test.js.map +1 -0
  67. package/dist/domain/wallet-errors.d.ts +37 -0
  68. package/dist/domain/wallet-errors.js +56 -0
  69. package/dist/domain/wallet-errors.js.map +1 -0
  70. package/dist/domain/wallet-errors.test.d.ts +1 -0
  71. package/dist/domain/wallet-errors.test.js +71 -0
  72. package/dist/domain/wallet-errors.test.js.map +1 -0
  73. package/dist/facade/chain-configs.js +61 -1
  74. package/dist/facade/chain-configs.js.map +1 -1
  75. package/dist/facade/config.test.d.ts +1 -0
  76. package/dist/facade/config.test.js +216 -0
  77. package/dist/facade/config.test.js.map +1 -0
  78. package/dist/facade/deposits.d.ts +22 -1
  79. package/dist/facade/deposits.js +24 -1
  80. package/dist/facade/deposits.js.map +1 -1
  81. package/dist/facade/facade.test.d.ts +1 -0
  82. package/dist/{tests → facade}/facade.test.js +87 -5
  83. package/dist/facade/facade.test.js.map +1 -0
  84. package/dist/facade/index.d.ts +2 -1
  85. package/dist/facade/index.js +2 -0
  86. package/dist/facade/index.js.map +1 -1
  87. package/dist/facade/kasu.d.ts +49 -8
  88. package/dist/facade/kasu.js +117 -13
  89. package/dist/facade/kasu.js.map +1 -1
  90. package/dist/facade/strategies.d.ts +25 -0
  91. package/dist/facade/strategies.js +36 -0
  92. package/dist/facade/strategies.js.map +1 -1
  93. package/dist/facade/types.d.ts +57 -2
  94. package/dist/facade/unused-pool-ids.d.ts +31 -0
  95. package/dist/facade/unused-pool-ids.js +57 -0
  96. package/dist/facade/unused-pool-ids.js.map +1 -0
  97. package/dist/facade/user-portfolio.d.ts +18 -0
  98. package/dist/facade/user-portfolio.js +23 -0
  99. package/dist/facade/user-portfolio.js.map +1 -1
  100. package/dist/index.d.ts +2 -0
  101. package/dist/index.js +6 -0
  102. package/dist/index.js.map +1 -1
  103. package/dist/sdk-config.d.ts +11 -0
  104. package/dist/sdk-config.js +8 -1
  105. package/dist/sdk-config.js.map +1 -1
  106. package/dist/services/DataService/data-service.d.ts +5 -0
  107. package/dist/services/DataService/data-service.js +10 -12
  108. package/dist/services/DataService/data-service.js.map +1 -1
  109. package/dist/services/DataService/directus-client.d.ts +26 -0
  110. package/dist/services/DataService/directus-client.js +38 -0
  111. package/dist/services/DataService/directus-client.js.map +1 -0
  112. package/dist/services/Locking/calculate-apy.test.d.ts +1 -0
  113. package/dist/services/Locking/calculate-apy.test.js +41 -0
  114. package/dist/services/Locking/calculate-apy.test.js.map +1 -0
  115. package/dist/services/Locking/locking.d.ts +14 -0
  116. package/dist/services/Locking/locking.js +16 -2
  117. package/dist/services/Locking/locking.js.map +1 -1
  118. package/dist/services/UserLending/user-lending.js +11 -7
  119. package/dist/services/UserLending/user-lending.js.map +1 -1
  120. package/dist/tests/sample.test.js +46 -25
  121. package/dist/tests/sample.test.js.map +1 -1
  122. package/package.json +43 -12
  123. package/src/domain/au-minimum.test.ts +371 -0
  124. package/src/domain/au-minimum.ts +192 -0
  125. package/src/domain/deposit-bounds.test.ts +200 -0
  126. package/src/domain/deposit-bounds.ts +118 -0
  127. package/src/domain/index.ts +134 -0
  128. package/src/domain/loan-contract.test.ts +343 -0
  129. package/src/domain/loan-contract.ts +275 -0
  130. package/src/domain/partners.test.ts +83 -0
  131. package/src/domain/partners.ts +66 -0
  132. package/src/domain/pools.test.ts +260 -0
  133. package/src/domain/pools.ts +150 -0
  134. package/src/domain/rates.test.ts +254 -0
  135. package/src/domain/rates.ts +120 -0
  136. package/src/domain/requests.test.ts +653 -0
  137. package/src/domain/requests.ts +414 -0
  138. package/src/domain/settlement.test.ts +198 -0
  139. package/src/domain/settlement.ts +161 -0
  140. package/src/domain/tranche-display-name.test.ts +96 -0
  141. package/src/domain/tranche-display-name.ts +34 -0
  142. package/src/domain/tranches.test.ts +300 -0
  143. package/src/domain/tranches.ts +177 -0
  144. package/src/domain/wallet-errors.test.ts +100 -0
  145. package/src/domain/wallet-errors.ts +56 -0
  146. package/src/facade/chain-configs.ts +62 -1
  147. package/src/facade/config.test.ts +265 -0
  148. package/src/facade/deposits.ts +25 -0
  149. package/src/{tests → facade}/facade.test.ts +134 -5
  150. package/src/facade/index.ts +4 -0
  151. package/src/facade/kasu.ts +155 -12
  152. package/src/facade/strategies.ts +36 -0
  153. package/src/facade/types.ts +60 -2
  154. package/src/facade/unused-pool-ids.ts +59 -0
  155. package/src/facade/user-portfolio.ts +24 -0
  156. package/src/index.ts +8 -0
  157. package/src/sdk-config.ts +19 -1
  158. package/src/services/DataService/data-service.ts +14 -26
  159. package/src/services/DataService/directus-client.ts +54 -0
  160. package/src/services/Locking/calculate-apy.test.ts +52 -0
  161. package/src/services/Locking/locking.ts +16 -2
  162. package/src/services/UserLending/user-lending.ts +17 -21
  163. package/src/tests/sample.test.ts +54 -33
  164. package/.eslintignore +0 -3
  165. package/.eslintrc.json +0 -90
  166. package/.github/workflows/ci.yml +0 -39
  167. package/.github/workflows/gitleaks.yml +0 -22
  168. package/.github/workflows/main.yml +0 -41
  169. package/.gitleaksignore +0 -19
  170. package/.prettierignore +0 -3
  171. package/.prettierrc +0 -28
  172. package/CLAUDE.md +0 -410
  173. package/copy-abi.ps1 +0 -15
  174. package/dist/tests/facade.test.js.map +0 -1
  175. package/index.ts +0 -2
  176. package/jest-config.ts +0 -9
  177. package/jest.config.js +0 -8
  178. package/rollup.config.js +0 -45
  179. package/tsconfig.json +0 -27
  180. /package/dist/{tests/facade.test.d.ts → domain/au-minimum.test.d.ts} +0 -0
@@ -0,0 +1,181 @@
1
+ import { UserRequest, UserRequestEvent } from '../services/UserLending/types';
2
+ /**
3
+ * The lending-request view model, as CODES.
4
+ *
5
+ * Lifted verbatim from kasu-ui's `derive-transaction-view.ts` +
6
+ * `request-bundle.ts`, minus every word. kasu-ui's `deriveTransactionView`
7
+ * produces a `TransactionView` that mixes derived FACTS (status code, amounts,
8
+ * kind, ids, submission count, timestamps) with COPY (the status word, the
9
+ * type label, the detail line beneath it, tooltip keys). Only the facts belong
10
+ * in this layer: the copy stays in each application, where the design system,
11
+ * the register and the visitor's language are.
12
+ *
13
+ * The branch ORDER below is the behaviour — cancelled beats forced beats
14
+ * reallocated beats a live withdrawal remainder beats the resolved outcomes
15
+ * beats pending. It reproduces `deriveTransactionView` check for check, so a
16
+ * consumer that renders its own words on top of `statusCode` gets exactly the
17
+ * row kasu-ui has been showing.
18
+ */
19
+ /**
20
+ * Stable status code for filters, tests and the caller's own status word.
21
+ * Independent of any user-facing copy — kasu-ui's four-value vocabulary
22
+ * (Queued / Processing / Completed / Cancelled) is a rendering of these seven
23
+ * codes, not a replacement for them.
24
+ */
25
+ export type RequestStatusCode = 'pending' | 'complete' | 'partial' | 'rejected' | 'reallocated' | 'cancelled' | 'forced';
26
+ /**
27
+ * Direction of value flow into / out of the lender's balance. `neutral`
28
+ * applies when the request was cancelled or fully rejected — nothing moved.
29
+ */
30
+ export type RequestKind = 'inflow' | 'outflow' | 'neutral';
31
+ /** One derived request row. Every field is a number, a code or an id. */
32
+ export interface RequestState {
33
+ /** `UserRequest.id`. */
34
+ id: string;
35
+ /**
36
+ * Id the loan contract is retrieved by — sourced from the `Initiated`
37
+ * event (format `${requestId}-${index}`). The agreements upstream keys
38
+ * contract metadata by EVENT id, not request id; passing `id` returns
39
+ * "Signature data not found". Empty string when there is no `Initiated`
40
+ * event (e.g. a withdrawal).
41
+ */
42
+ contractId: string;
43
+ /** Pool address, lowercased — the filter/join key. */
44
+ poolId: string;
45
+ /**
46
+ * Pool name exactly as it arrived. RAW: splitting it into a strategy name
47
+ * and its borrower-type subheading (kasu-ui's `splitPoolName`) is a
48
+ * display decision and stays in the application.
49
+ */
50
+ poolName: string;
51
+ /**
52
+ * Tranche name exactly as the subgraph reports it. RAW: apps call
53
+ * `getTrancheDisplayName(state.trancheName, { poolName: state.poolName })`
54
+ * at the view boundary. A renamed value must never reach matching or
55
+ * ranking code.
56
+ */
57
+ trancheName: string;
58
+ /** Tranche id — the resolve API re-renders a fixed-term contract against it. */
59
+ trancheId: string;
60
+ /** Fixed-term configId, `'0'` for a variable-rate request. */
61
+ fixedTermConfigId: string;
62
+ requestType: 'Deposit' | 'Withdrawal';
63
+ /** The subgraph status, untouched. Sticky — see `cycleClosed`. */
64
+ rawStatus: UserRequest['status'];
65
+ statusCode: RequestStatusCode;
66
+ kind: RequestKind;
67
+ /**
68
+ * The amount originally asked for, always positive. A cancelled request
69
+ * has its on-request `requestedAmount` zeroed by the subgraph, so the
70
+ * original is recovered from the `Initiated` event (see
71
+ * `initiatedAmount`).
72
+ */
73
+ requestedAmount: number;
74
+ /**
75
+ * The accepted figure as the subgraph reported it, or `null` when it
76
+ * reported none. `null` is NOT zero: an absent figure means "not known",
77
+ * and a caller that renders it as 0 states an outcome the chain has not
78
+ * given. The branch logic below reads `null` as 0 — exactly what kasu-ui's
79
+ * `num()` does — but the distinction survives into the row.
80
+ */
81
+ acceptedAmount: number | null;
82
+ /**
83
+ * `assetAmount` of the `Initiated` event, or `null` when the request
84
+ * carries no `Initiated` event. This is the cancelled-amount recovery:
85
+ * the subgraph resets a cancelled request's `requestedAmount` to 0 (the
86
+ * lender's effective balance is restored) and the original survives only
87
+ * here.
88
+ */
89
+ initiatedAmount: number | null;
90
+ /**
91
+ * The signed figure the row shows, chosen by the same branch logic
92
+ * kasu-ui uses: positive for an inflow, negative for an outflow, 0 for a
93
+ * cancelled or fully-rejected request.
94
+ */
95
+ amount: number;
96
+ /**
97
+ * Submissions bundled into this dNFT-aggregate row (`Initiated` +
98
+ * `Increased`). `> 1` is what drives kasu-ui's inline "(x2)".
99
+ */
100
+ submissionCount: number;
101
+ /**
102
+ * Timestamp of the FIRST submission in the bundle, or `null` when the
103
+ * bundle carries no submission event yet (the `Initiated` event has not
104
+ * indexed). kasu-ui substitutes `request.timestamp` there; that fallback
105
+ * is the application's to choose, so this layer reports the absence.
106
+ */
107
+ firstSubmissionTimestamp: number | null;
108
+ /** Has THIS request's cycle closed? — `!canCancel`. See `isCycleClosed`. */
109
+ cycleClosed: boolean;
110
+ /** The SDK's per-pool cancel signal, passed through. */
111
+ canCancel: boolean;
112
+ }
113
+ /**
114
+ * The submissions bundled into one dNFT-aggregate request row, input order
115
+ * preserved — one loan agreement per submission.
116
+ */
117
+ export declare function submissionEvents<T extends Pick<UserRequestEvent, 'requestType'>>(events: T[]): T[];
118
+ /** Count the submissions bundled into one dNFT-aggregate request row. */
119
+ export declare function countSubmissions(events: Pick<UserRequestEvent, 'requestType'>[]): number;
120
+ /**
121
+ * Timestamp of the FIRST submission in the bundle. Falls back to `fallback`
122
+ * when the `Initiated` event has not indexed yet — the caller decides what
123
+ * that is (kasu-ui passes the request's own timestamp).
124
+ */
125
+ export declare function firstSubmissionTimestamp(events: Pick<UserRequestEvent, 'requestType' | 'timestamp'>[], fallback: number): number;
126
+ /**
127
+ * Has THIS request's cycle closed? — the single open/closed signal behind the
128
+ * status vocabulary and behind Cancel.
129
+ *
130
+ * `request.canCancel` is the SDK's `isCancelable(status, poolId)` —
131
+ * `status !== 'Processed' && !isLendingPoolClearingPending(pool)`. It is
132
+ * per-POOL and reads the same condition the contract enforces on the cancel
133
+ * call — but it reads it ONCE, when the request was fetched. Nothing about
134
+ * this value is live, so a client that holds a request across a cycle close
135
+ * must refetch before acting on it.
136
+ *
137
+ * The raw subgraph `status` must NOT feed this: `'Processing'` is a STICKY
138
+ * historical marker set on the first partial fill and never reset, so gating
139
+ * on it would freeze a partly-filled request in Processing forever. A global
140
+ * settlement clock is equally wrong here — it is blind to whether THIS
141
+ * request's pool is already clearing.
142
+ */
143
+ export declare function isCycleClosed(request: Pick<UserRequest, 'canCancel'>): boolean;
144
+ /**
145
+ * Convert a `UserRequest` into a `RequestState`. Pure — no clock, no network,
146
+ * no copy.
147
+ *
148
+ * BRANCH ORDER (this IS the behaviour; it reproduces kasu-ui's
149
+ * `deriveTransactionView` check for check):
150
+ *
151
+ * 1. a `Cancelled` event → `cancelled`, neutral, 0
152
+ * 2. a withdrawal with a `Forced` event → `forced`, outflow, −accepted
153
+ * 3. a reallocated deposit → `reallocated`, inflow, +accepted
154
+ * 4. a withdrawal partly filled with a LIVE
155
+ * remainder (cycle still open) → `partial`, outflow, −accepted
156
+ * 5. resolved (`status === 'Processed'`):
157
+ * withdrawal, partly filled → `partial`, outflow, −accepted
158
+ * withdrawal, fully filled → `complete`, outflow, −accepted
159
+ * deposit, nothing accepted → `rejected`, neutral, 0
160
+ * deposit, part rejected → `partial`, inflow, +accepted
161
+ * deposit, fully accepted → `complete`, inflow, +accepted
162
+ * 6. otherwise → `pending`, ±requested
163
+ *
164
+ * `cancelled` is reachable ONLY from branch 1 — a Cancelled EVENT. No
165
+ * processing or resolved state can derive it.
166
+ *
167
+ * Branch 4 is checked BEFORE the resolved branch and gates on `isCycleClosed`
168
+ * (i.e. `canCancel`), never on the sticky raw status: a withdrawal that was
169
+ * partly filled returns to the queue with a live Cancel, and reading the raw
170
+ * status would strand it.
171
+ *
172
+ * WHAT THE APPLICATION STILL OWNS: the status word and the detail line beneath
173
+ * it; the tranche display rename (`getTrancheDisplayName` on `trancheName`,
174
+ * and on the reallocation destination read off `request.events`); the pool-name
175
+ * split; the amount format. The "view loan agreement" affordance is a fact, and
176
+ * it follows from two fields already here —
177
+ * `requestType === 'Deposit' && statusCode !== 'cancelled' && statusCode !== 'rejected'`
178
+ * — because neither a cancelled nor a fully-rejected deposit ever issued one,
179
+ * and withdrawals sign no agreement at all.
180
+ */
181
+ export declare function deriveRequestState(request: UserRequest): RequestState;
@@ -0,0 +1,202 @@
1
+ import { UserRequestStatus } from '../services/UserLending/subgraph-types';
2
+ /**
3
+ * Events that represent a lender SUBMISSION into the bundle. A dNFT position
4
+ * aggregates every submission the lender made into the same pool/tranche this
5
+ * cycle: the first is `Initiated`, each subsequent top-up is `Increased`.
6
+ * Everything else on the timeline (Accepted / Rejected / Cancelled /
7
+ * Reallocated / Forced) is an OUTCOME, not a request, and must not be counted.
8
+ */
9
+ const SUBMISSION_EVENTS = new Set(['Initiated', 'Increased']);
10
+ /**
11
+ * The submissions bundled into one dNFT-aggregate request row, input order
12
+ * preserved — one loan agreement per submission.
13
+ */
14
+ export function submissionEvents(events) {
15
+ return events.filter((e) => SUBMISSION_EVENTS.has(e.requestType));
16
+ }
17
+ /** Count the submissions bundled into one dNFT-aggregate request row. */
18
+ export function countSubmissions(events) {
19
+ return submissionEvents(events).length;
20
+ }
21
+ /**
22
+ * Timestamp of the FIRST submission in the bundle. Falls back to `fallback`
23
+ * when the `Initiated` event has not indexed yet — the caller decides what
24
+ * that is (kasu-ui passes the request's own timestamp).
25
+ */
26
+ export function firstSubmissionTimestamp(events, fallback) {
27
+ const submissions = submissionEvents(events);
28
+ if (submissions.length === 0)
29
+ return fallback;
30
+ return submissions.reduce((min, e) => (e.timestamp < min ? e.timestamp : min), Infinity);
31
+ }
32
+ /**
33
+ * Has THIS request's cycle closed? — the single open/closed signal behind the
34
+ * status vocabulary and behind Cancel.
35
+ *
36
+ * `request.canCancel` is the SDK's `isCancelable(status, poolId)` —
37
+ * `status !== 'Processed' && !isLendingPoolClearingPending(pool)`. It is
38
+ * per-POOL and reads the same condition the contract enforces on the cancel
39
+ * call — but it reads it ONCE, when the request was fetched. Nothing about
40
+ * this value is live, so a client that holds a request across a cycle close
41
+ * must refetch before acting on it.
42
+ *
43
+ * The raw subgraph `status` must NOT feed this: `'Processing'` is a STICKY
44
+ * historical marker set on the first partial fill and never reset, so gating
45
+ * on it would freeze a partly-filled request in Processing forever. A global
46
+ * settlement clock is equally wrong here — it is blind to whether THIS
47
+ * request's pool is already clearing.
48
+ */
49
+ export function isCycleClosed(request) {
50
+ return !request.canCancel;
51
+ }
52
+ const isCancelled = (events) => events.some((e) => e.requestType === 'Cancelled');
53
+ const isForced = (events) => events.some((e) => e.requestType === 'Forced');
54
+ const initiatedEvent = (events) => events.find((e) => e.requestType === 'Initiated');
55
+ /**
56
+ * Subgraph behaviour: when a request is cancelled, the on-request
57
+ * `requestedAmount` field is reset to 0 (the lender's effective balance is
58
+ * restored). The original amount survives on the `Initiated` event's
59
+ * `assetAmount`. Recover from there so cancelled rows still carry the amount
60
+ * the lender originally asked for.
61
+ */
62
+ const initiatedAmountOf = (events) => {
63
+ const initiated = initiatedEvent(events);
64
+ return initiated ? Number(initiated.assetAmount || '0') : 0;
65
+ };
66
+ /**
67
+ * A deposit is REALLOCATED when the timeline carries a `Reallocated` event, or
68
+ * an `Accepted` event into a tranche other than the one requested.
69
+ */
70
+ const findReallocation = (events, originalTrancheId) => events.find((e) => e.requestType === 'Reallocated' ||
71
+ (e.requestType === 'Accepted' &&
72
+ e.trancheId.toLowerCase() !==
73
+ originalTrancheId.toLowerCase()));
74
+ /** kasu-ui's `num`: an absent or unparseable figure reads as 0. */
75
+ const num = (str) => {
76
+ const n = Number(str !== null && str !== void 0 ? str : '0');
77
+ return Number.isFinite(n) ? n : 0;
78
+ };
79
+ /** The same parse, keeping "the subgraph reported nothing" distinct from 0. */
80
+ const numOrNull = (str) => {
81
+ if (str === undefined || str === null || str.trim() === '')
82
+ return null;
83
+ const n = Number(str);
84
+ return Number.isFinite(n) ? n : null;
85
+ };
86
+ /**
87
+ * Convert a `UserRequest` into a `RequestState`. Pure — no clock, no network,
88
+ * no copy.
89
+ *
90
+ * BRANCH ORDER (this IS the behaviour; it reproduces kasu-ui's
91
+ * `deriveTransactionView` check for check):
92
+ *
93
+ * 1. a `Cancelled` event → `cancelled`, neutral, 0
94
+ * 2. a withdrawal with a `Forced` event → `forced`, outflow, −accepted
95
+ * 3. a reallocated deposit → `reallocated`, inflow, +accepted
96
+ * 4. a withdrawal partly filled with a LIVE
97
+ * remainder (cycle still open) → `partial`, outflow, −accepted
98
+ * 5. resolved (`status === 'Processed'`):
99
+ * withdrawal, partly filled → `partial`, outflow, −accepted
100
+ * withdrawal, fully filled → `complete`, outflow, −accepted
101
+ * deposit, nothing accepted → `rejected`, neutral, 0
102
+ * deposit, part rejected → `partial`, inflow, +accepted
103
+ * deposit, fully accepted → `complete`, inflow, +accepted
104
+ * 6. otherwise → `pending`, ±requested
105
+ *
106
+ * `cancelled` is reachable ONLY from branch 1 — a Cancelled EVENT. No
107
+ * processing or resolved state can derive it.
108
+ *
109
+ * Branch 4 is checked BEFORE the resolved branch and gates on `isCycleClosed`
110
+ * (i.e. `canCancel`), never on the sticky raw status: a withdrawal that was
111
+ * partly filled returns to the queue with a live Cancel, and reading the raw
112
+ * status would strand it.
113
+ *
114
+ * WHAT THE APPLICATION STILL OWNS: the status word and the detail line beneath
115
+ * it; the tranche display rename (`getTrancheDisplayName` on `trancheName`,
116
+ * and on the reallocation destination read off `request.events`); the pool-name
117
+ * split; the amount format. The "view loan agreement" affordance is a fact, and
118
+ * it follows from two fields already here —
119
+ * `requestType === 'Deposit' && statusCode !== 'cancelled' && statusCode !== 'rejected'`
120
+ * — because neither a cancelled nor a fully-rejected deposit ever issued one,
121
+ * and withdrawals sign no agreement at all.
122
+ */
123
+ export function deriveRequestState(request) {
124
+ var _a, _b, _c;
125
+ const isWithdrawal = request.requestType === 'Withdrawal';
126
+ const cancelled = isCancelled(request.events);
127
+ // Cancelled requests have `requestedAmount` zeroed on the request itself;
128
+ // pull the original value from the Initiated event so the row still
129
+ // carries "100 cancelled" instead of "0 cancelled".
130
+ const requested = cancelled
131
+ ? num(request.requestedAmount) || initiatedAmountOf(request.events)
132
+ : num(request.requestedAmount);
133
+ const accepted = num(request.acceptedAmount);
134
+ const rejected = num(request.rejectedAmount);
135
+ const forced = isWithdrawal && isForced(request.events);
136
+ const reallocation = !isWithdrawal && findReallocation(request.events, request.trancheId);
137
+ const initiated = initiatedEvent(request.events);
138
+ const base = {
139
+ id: request.id,
140
+ contractId: (_a = initiated === null || initiated === void 0 ? void 0 : initiated.id) !== null && _a !== void 0 ? _a : '',
141
+ poolId: request.lendingPool.id.toLowerCase(),
142
+ poolName: request.lendingPool.name,
143
+ trancheName: request.trancheName,
144
+ trancheId: request.trancheId,
145
+ fixedTermConfigId: (_c = (_b = request.fixedTermConfig) === null || _b === void 0 ? void 0 : _b.configId) !== null && _c !== void 0 ? _c : '0',
146
+ requestType: request.requestType,
147
+ rawStatus: request.status,
148
+ requestedAmount: requested,
149
+ acceptedAmount: numOrNull(request.acceptedAmount),
150
+ initiatedAmount: initiated
151
+ ? initiatedAmountOf(request.events)
152
+ : null,
153
+ submissionCount: countSubmissions(request.events),
154
+ // `firstSubmissionTimestamp` needs a fallback it will never use here:
155
+ // the bundle is non-empty on every path that reaches the call.
156
+ firstSubmissionTimestamp: countSubmissions(request.events) === 0
157
+ ? null
158
+ : firstSubmissionTimestamp(request.events, 0),
159
+ cycleClosed: isCycleClosed(request),
160
+ canCancel: request.canCancel,
161
+ };
162
+ // 1. Cancelled wins over everything — the ONLY path to `cancelled`.
163
+ if (cancelled) {
164
+ return Object.assign(Object.assign({}, base), { kind: 'neutral', amount: 0, statusCode: 'cancelled' });
165
+ }
166
+ // 2. Forced withdrawal (credit originator returned funds early).
167
+ if (forced) {
168
+ return Object.assign(Object.assign({}, base), { kind: 'outflow', amount: -accepted, statusCode: 'forced' });
169
+ }
170
+ // 3. Reallocated deposit (accepted into a different lending option).
171
+ if (reallocation) {
172
+ return Object.assign(Object.assign({}, base), { kind: 'inflow', amount: accepted, statusCode: 'reallocated' });
173
+ }
174
+ // 4. Withdrawal partly filled with a LIVE remainder: the request returns
175
+ // to the queue with a live Cancel. Checked BEFORE the resolved branch and
176
+ // via `isCycleClosed`, never via the sticky raw status.
177
+ if (isWithdrawal &&
178
+ accepted > 0 &&
179
+ accepted < requested &&
180
+ !isCycleClosed(request)) {
181
+ return Object.assign(Object.assign({}, base), { kind: 'outflow', amount: -accepted, statusCode: 'partial' });
182
+ }
183
+ // 5. Resolved — a rejection IS a resolution.
184
+ if (request.status === UserRequestStatus.PROCESSED) {
185
+ if (isWithdrawal) {
186
+ const partly = accepted < requested;
187
+ return Object.assign(Object.assign({}, base), { kind: 'outflow', amount: -accepted, statusCode: partly ? 'partial' : 'complete' });
188
+ }
189
+ // Deposit: full reject vs partial vs full accept.
190
+ if (accepted === 0) {
191
+ return Object.assign(Object.assign({}, base), { kind: 'neutral', amount: 0, statusCode: 'rejected' });
192
+ }
193
+ if (rejected > 0) {
194
+ return Object.assign(Object.assign({}, base), { kind: 'inflow', amount: accepted, statusCode: 'partial' });
195
+ }
196
+ return Object.assign(Object.assign({}, base), { kind: 'inflow', amount: accepted, statusCode: 'complete' });
197
+ }
198
+ // 6. Unresolved. `cycleClosed` tells the caller whether to render its
199
+ // "queued" or its "processing" word; the code is the same either way.
200
+ return Object.assign(Object.assign({}, base), { kind: isWithdrawal ? 'outflow' : 'inflow', amount: isWithdrawal ? -requested : requested, statusCode: 'pending' });
201
+ }
202
+ //# sourceMappingURL=requests.js.map
@@ -0,0 +1 @@
1
+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