@kasufinance/kasu-sdk 2.13.1 → 2.15.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 (56) hide show
  1. package/README.md +68 -5
  2. package/dist/bundle.cjs.js +1038 -29
  3. package/dist/bundle.esm.js +1026 -30
  4. package/dist/domain/index.d.ts +8 -3
  5. package/dist/domain/index.js +6 -2
  6. package/dist/domain/index.js.map +1 -1
  7. package/dist/domain/loan-contract.d.ts +16 -5
  8. package/dist/domain/loan-contract.js +16 -5
  9. package/dist/domain/loan-contract.js.map +1 -1
  10. package/dist/domain/pool-tvl.d.ts +104 -0
  11. package/dist/domain/pool-tvl.js +179 -0
  12. package/dist/domain/pool-tvl.js.map +1 -1
  13. package/dist/domain/requests.js +29 -19
  14. package/dist/domain/requests.js.map +1 -1
  15. package/dist/domain/strategy-details.d.ts +262 -0
  16. package/dist/domain/strategy-details.js +375 -0
  17. package/dist/domain/strategy-details.js.map +1 -0
  18. package/dist/facade/index.d.ts +3 -1
  19. package/dist/facade/index.js +2 -0
  20. package/dist/facade/index.js.map +1 -1
  21. package/dist/facade/strategies.d.ts +102 -4
  22. package/dist/facade/strategies.js +182 -6
  23. package/dist/facade/strategies.js.map +1 -1
  24. package/dist/facade/strategy-deployments.d.ts +65 -0
  25. package/dist/facade/strategy-deployments.js +97 -0
  26. package/dist/facade/strategy-deployments.js.map +1 -0
  27. package/dist/facade/types.d.ts +82 -0
  28. package/dist/flows/deposit-flow.d.ts +19 -5
  29. package/dist/flows/deposit-flow.js.map +1 -1
  30. package/dist/index.d.ts +1 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/services/DataService/data-service.d.ts +29 -1
  33. package/dist/services/DataService/data-service.js +80 -9
  34. package/dist/services/DataService/data-service.js.map +1 -1
  35. package/dist/services/DataService/tvl-history.d.ts +49 -0
  36. package/dist/services/DataService/tvl-history.js +89 -0
  37. package/dist/services/DataService/tvl-history.js.map +1 -1
  38. package/dist/services/UserLending/queries.js +2 -7
  39. package/dist/services/UserLending/queries.js.map +1 -1
  40. package/dist/services/UserLending/subgraph-types.js.map +1 -1
  41. package/dist/services/UserLending/types.js.map +1 -1
  42. package/dist/services/UserLending/user-lending.js +72 -16
  43. package/dist/services/UserLending/user-lending.js.map +1 -1
  44. package/package.json +1 -1
  45. package/src/domain/index.ts +34 -3
  46. package/src/domain/loan-contract.ts +16 -5
  47. package/src/domain/pool-tvl.ts +281 -0
  48. package/src/domain/strategy-details.ts +528 -0
  49. package/src/facade/index.ts +13 -0
  50. package/src/facade/strategies.ts +231 -11
  51. package/src/facade/strategy-deployments.ts +161 -0
  52. package/src/facade/types.ts +85 -0
  53. package/src/flows/deposit-flow.ts +19 -5
  54. package/src/index.ts +4 -1
  55. package/src/services/DataService/data-service.ts +103 -7
  56. package/src/services/DataService/tvl-history.ts +131 -0
@@ -0,0 +1,528 @@
1
+ /**
2
+ * The CMS-authored figures and text a strategy's Details screen shows, read
3
+ * the way kasu-ui's Details tab reads them, so every app shows the same
4
+ * thing.
5
+ *
6
+ * Lifted from kasu-ui (`lib/details-fields.ts`, `lib/directus-text.ts` and
7
+ * the parsers inside `deposit-dialog/details-tab.tsx`). The rules are facts
8
+ * about how the CMS is authored, not presentation:
9
+ *
10
+ * - EMPTY IS UNAUTHORED. The CMS stores an emptied field as `''`, and its
11
+ * "numeric" fields arrive as a number, a numeric string, `''` or `null`.
12
+ * Anything that is not real data reads as `undefined` — never a `0`, a
13
+ * placeholder or a sentence of the SDK's own. A field the caller cannot
14
+ * read is a row the caller omits.
15
+ * - A START DATE MUST DATE. A value that is not an ISO date, or a real
16
+ * calendar date, or is before 2000 or in the future, is refused: rendered
17
+ * as elapsed time it would claim a history nobody authored.
18
+ * - SOME FIELDS CARRY TWO LINES IN ONE STRING. Business Types and Facility
19
+ * Type are a primary value and a qualifying clause; risk-item
20
+ * descriptions can be numbered enumerations. Splitting them is the same
21
+ * everywhere, so it lives here.
22
+ *
23
+ * Like `pickShortDescription`, this authors no string of its own: it selects,
24
+ * splits and trims text the CMS already holds. None of it is sanitised —
25
+ * render every string as text, never as HTML or markdown.
26
+ *
27
+ * Pure. No clock: the date reader takes `now` from its caller.
28
+ */
29
+
30
+ // ---------------------------------------------------------------------------
31
+ // Start dates
32
+ // ---------------------------------------------------------------------------
33
+
34
+ /**
35
+ * `YYYY-MM-DD`, optionally followed by a time part — the two shapes a CMS
36
+ * date column serialises to. Checked BEFORE any parse: `new Date('Jun 2024')`
37
+ * is a valid date in V8, so an editorial string would otherwise become a
38
+ * confident duration.
39
+ */
40
+ const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})(?:[T ].*)?$/;
41
+
42
+ /** Nothing on Kasu has a lending history from before this year. */
43
+ const EARLIEST_YEAR = 2000;
44
+
45
+ export interface CmsStartDateOptions {
46
+ /**
47
+ * Also accept a finite number as unix SECONDS. kasu-ui's duration
48
+ * formatter reads a numeric value that way, and the originator's
49
+ * `delegateLendingHistory` is typed as a number although the live CMS
50
+ * serves an ISO date. Off by default: a strategy's `operatingSince` is a
51
+ * date column, and kasu-ui refuses a number there.
52
+ */
53
+ unixSeconds?: boolean;
54
+ }
55
+
56
+ /**
57
+ * A CMS start date as its `YYYY-MM-DD` date head, or `undefined`.
58
+ *
59
+ * Accepts an ISO date, optionally with a time part (only the date head is
60
+ * kept — a time changes nothing at year/month granularity, and converting it
61
+ * through a timezone could move it a day). Refused, as `undefined`:
62
+ *
63
+ * - anything that is not a string (or, with `unixSeconds`, a number);
64
+ * - an empty or blank string (unauthored);
65
+ * - a string that is not ISO-shaped (`'Jun 2024'`);
66
+ * - a date that does not exist (`'2024-02-30'`, `'2024-13-01'`) — never
67
+ * rolled over into the next month;
68
+ * - a year before 2000;
69
+ * - a date after `now` (a typo such as 2062 for 2026 — no history has
70
+ * begun in the future).
71
+ *
72
+ * `now` is the caller's clock; the facade passes the current time.
73
+ */
74
+ export function readCmsStartDate(
75
+ value: unknown,
76
+ now: Date,
77
+ options: CmsStartDateOptions = {},
78
+ ): string | undefined {
79
+ let head: string;
80
+ if (typeof value === 'number' && options.unixSeconds) {
81
+ // `0` is formatDuration's "unset" sentinel; negatives are pre-1970.
82
+ if (!Number.isFinite(value) || value <= 0) return undefined;
83
+ const date = new Date(value * 1000);
84
+ if (Number.isNaN(date.getTime())) return undefined;
85
+ head = date.toISOString().slice(0, 10);
86
+ } else if (typeof value === 'string') {
87
+ const trimmed = value.trim();
88
+ if (!ISO_DATE.test(trimmed)) return undefined;
89
+ head = trimmed.slice(0, 10);
90
+ } else {
91
+ return undefined;
92
+ }
93
+
94
+ const match = ISO_DATE.exec(head);
95
+ if (!match) return undefined;
96
+ const year = Number(match[1]);
97
+ const month = Number(match[2]);
98
+ const day = Number(match[3]);
99
+ // Round-trip through UTC: a day or month out of range comes back as a
100
+ // different date, which is how a non-existent date is caught.
101
+ const utc = new Date(Date.UTC(year, month - 1, day));
102
+ if (
103
+ utc.getUTCFullYear() !== year ||
104
+ utc.getUTCMonth() !== month - 1 ||
105
+ utc.getUTCDate() !== day
106
+ ) {
107
+ return undefined;
108
+ }
109
+ if (year < EARLIEST_YEAR) return undefined;
110
+ if (utc.getTime() > now.getTime()) return undefined;
111
+ return head;
112
+ }
113
+
114
+ // ---------------------------------------------------------------------------
115
+ // End Borrowers
116
+ // ---------------------------------------------------------------------------
117
+
118
+ /** A CMS value split into its primary line and an optional qualifying clause. */
119
+ export interface CmsTwoLineValue {
120
+ /** The value itself — never empty. */
121
+ primary: string;
122
+ /** The qualifying clause beneath it. Absent when none is authored. */
123
+ detail?: string;
124
+ }
125
+
126
+ /**
127
+ * Business Types (the CMS `industryExposure`), split into the value and its
128
+ * supporting clause on the FIRST newline, else the FIRST parenthesised
129
+ * segment (a trailing `)` dropped):
130
+ *
131
+ * `'SMEs & Large Businesses (diversified industries – exclusions apply)'`
132
+ * → `{ primary: 'SMEs & Large Businesses', detail: 'diversified industries – exclusions apply' }`
133
+ *
134
+ * A value with neither delimiter is `{ primary }` alone. `undefined` for a
135
+ * missing, non-string, empty or blank value.
136
+ *
137
+ * REFINED over kasu-ui: a value that OPENS with `(` would split to an empty
138
+ * primary there; here the whole value is the primary instead, so `primary`
139
+ * is never empty. No live record has that shape.
140
+ */
141
+ export function splitBusinessTypes(raw: unknown): CmsTwoLineValue | undefined {
142
+ const value = typeof raw === 'string' ? raw.trim() : '';
143
+ if (!value) return undefined;
144
+
145
+ let primary = value;
146
+ let detail = '';
147
+ const newlineAt = value.indexOf('\n');
148
+ if (newlineAt !== -1) {
149
+ primary = value.slice(0, newlineAt).trim();
150
+ detail = value.slice(newlineAt + 1).trim();
151
+ } else {
152
+ const parenAt = value.indexOf('(');
153
+ if (parenAt !== -1) {
154
+ primary = value.slice(0, parenAt).trim();
155
+ detail = value.slice(parenAt + 1).trim();
156
+ if (detail.endsWith(')')) detail = detail.slice(0, -1).trim();
157
+ }
158
+ }
159
+ if (!primary) return { primary: value };
160
+ return detail ? { primary, detail } : { primary };
161
+ }
162
+
163
+ /** Facility Type: the authored label, its clause, and whether it revolves. */
164
+ export interface StrategyFacility {
165
+ /** The facility's label (`'Revolving Instalment Facility'`) — never empty. */
166
+ label: string;
167
+ /** The qualifying clause beneath it. Absent when none is authored. */
168
+ detail?: string;
169
+ /**
170
+ * The LABEL names a revolving facility (`'Revolving'`, `'Revolving
171
+ * Instalment Facility'`), matched case-insensitively on a word starting
172
+ * `revolv`. Never true for a negated label: `'Non-Revolving Term
173
+ * Facility'` is false, because a hyphen before the word does not count as
174
+ * a word boundary here. The clause is not read, so a clause that merely
175
+ * mentions redraw does not make a facility revolve.
176
+ *
177
+ * kasu-ui hangs an explanatory ⓘ off a revolving label; that copy is the
178
+ * app's own.
179
+ */
180
+ revolving: boolean;
181
+ }
182
+
183
+ /**
184
+ * The start of the label, or a character that is neither a word character
185
+ * nor a hyphen, before `revolv` — not `\b`, which treats a hyphen as a
186
+ * boundary, so "Non-Revolving" would match. kasu-ui writes the same rule as
187
+ * the lookbehind `(?<![\w-])`; this form needs no lookbehind support from the
188
+ * JavaScript engine.
189
+ */
190
+ const REVOLVING_FACILITY = /(?:^|[^\w-])revolv\w*\b/i;
191
+
192
+ /**
193
+ * Facility Type (the CMS `loanStructure`): the label on the FIRST line, and
194
+ * everything after the first newline as its clause, so a clause with line
195
+ * breaks of its own stays whole.
196
+ *
197
+ * `'Revolving Instalment Facility\n12-24 months instalment loan, subject to annual review'`
198
+ * → `{ label: 'Revolving Instalment Facility', detail: '12-24 months …', revolving: true }`
199
+ *
200
+ * `undefined` for a missing, non-string, empty or blank value. The value is
201
+ * trimmed first, so a leading blank line still yields a label.
202
+ */
203
+ export function parseFacility(raw: unknown): StrategyFacility | undefined {
204
+ const value = typeof raw === 'string' ? raw.trim() : '';
205
+ if (!value) return undefined;
206
+ const breakAt = value.indexOf('\n');
207
+ const label = (breakAt === -1 ? value : value.slice(0, breakAt)).trim();
208
+ const detail = breakAt === -1 ? '' : value.slice(breakAt + 1).trim();
209
+ const revolving = REVOLVING_FACILITY.test(label);
210
+ return detail ? { label, detail, revolving } : { label, revolving };
211
+ }
212
+
213
+ // ---------------------------------------------------------------------------
214
+ // Risk Management
215
+ // ---------------------------------------------------------------------------
216
+
217
+ /**
218
+ * The order the Risk Management groups read in, by group name (compared
219
+ * trimmed, case-insensitively). The CMS returns items in authoring order,
220
+ * which is not this. A group not listed still appears — after these, in CMS
221
+ * order.
222
+ */
223
+ export const RISK_GROUP_ORDER: readonly string[] = Object.freeze([
224
+ 'Security & Recourse',
225
+ 'Structural Controls',
226
+ 'Financial Covenants',
227
+ 'Reporting Covenants',
228
+ 'Key Eligibility Criteria',
229
+ ]);
230
+
231
+ /** Zero-width paste artifacts, which `\s` does not match. */
232
+ const ZERO_WIDTH = /[​-‍]/g;
233
+ /** An `N)` marker at the start, or after a `;` / `; and,` separator. */
234
+ const HAS_ENUMERATION = /(?:^\d+\)|;\s*(?:and,?\s*)?\d+\))/;
235
+ const ENUMERATION_SPLIT = /(?:^|\s*;\s*(?:and,?\s*)?)\d+\)\s*/;
236
+ /** kasu-ui's stub for an unauthored description; never a clause. */
237
+ const EMPTY_DESCRIPTION = '—';
238
+
239
+ /**
240
+ * A risk-item description as the lines beneath the item's name.
241
+ *
242
+ * A numbered enumeration (`'1) Foo; and, 2) Bar'`, or one that omits its
243
+ * leading `1)`: `'Foo; 2) Bar'`) is one line per clause; anything else is
244
+ * one line. Zero-width characters are stripped first. An unauthored
245
+ * description is NO lines (`[]`), never a dash.
246
+ */
247
+ export function splitNumberedClauses(description: unknown): string[] {
248
+ const raw = cleanDescription(description);
249
+ if (!raw) return [];
250
+ const clauses = HAS_ENUMERATION.test(raw)
251
+ ? raw
252
+ .split(ENUMERATION_SPLIT)
253
+ .map((part) => part.trim())
254
+ .filter((part) => part.length > 0)
255
+ : [raw];
256
+ const lines = clauses.length > 0 ? clauses : [raw];
257
+ return lines.filter((line) => line !== EMPTY_DESCRIPTION);
258
+ }
259
+
260
+ /** A description with zero-width characters stripped, trimmed; `''` when not a string. */
261
+ function cleanDescription(description: unknown): string {
262
+ return typeof description === 'string'
263
+ ? description.replace(ZERO_WIDTH, '').trim()
264
+ : '';
265
+ }
266
+
267
+ /** One risk-management item as the CMS row carries it. */
268
+ export interface RiskManagementItemSource {
269
+ name?: unknown;
270
+ group?: unknown;
271
+ description?: unknown;
272
+ tooltip?: unknown;
273
+ }
274
+
275
+ /** One item in a Risk Management group. */
276
+ export interface StrategyRiskItem {
277
+ /** The item's name (`'Guarantee & Indemnity'`) — never empty. */
278
+ name: string;
279
+ /**
280
+ * The pool's own description of it — zero-width characters stripped,
281
+ * trimmed. Present exactly when `clauses` is non-empty: a description
282
+ * that yields no line (`''`, `'—'`, zero-width characters alone) is
283
+ * absent.
284
+ */
285
+ description?: string;
286
+ /** `description` as the lines beneath the name; `[]` when unauthored. */
287
+ clauses: string[];
288
+ /** The CMS explanation of the item (shared by every pool). Absent when unauthored. */
289
+ tooltip?: string;
290
+ }
291
+
292
+ /** One Risk Management group and its items, in CMS order. */
293
+ export interface StrategyRiskGroup {
294
+ /** The group's name as the CMS authors it (`'Security & Recourse'`). */
295
+ group: string;
296
+ /** Never empty. */
297
+ items: StrategyRiskItem[];
298
+ }
299
+
300
+ /**
301
+ * Risk-management items grouped by their group, the groups in
302
+ * `RISK_GROUP_ORDER` and, within a group, the items in CMS order.
303
+ *
304
+ * An item with no name, or no group, is left out: there is nothing to head
305
+ * its lines with, or no group to place it in. (The CMS joins items to groups
306
+ * by name, so neither occurs in live data.) No group is ever empty, so an
307
+ * item list with nothing usable gives `[]`.
308
+ */
309
+ export function groupRiskManagementItems(
310
+ items: readonly RiskManagementItemSource[],
311
+ ): StrategyRiskGroup[] {
312
+ const groups = new Map<string, StrategyRiskGroup>();
313
+ for (const source of items) {
314
+ const name = trimmedOrUndefined(source.name);
315
+ const group = trimmedOrUndefined(source.group);
316
+ if (!name || !group) continue;
317
+ const clauses = splitNumberedClauses(source.description);
318
+ // The same cleaned text the clauses come from, and only when they
319
+ // say something: a description of "—" or of zero-width characters
320
+ // alone is unauthored, so it is absent here too, never a stray dash.
321
+ const description =
322
+ clauses.length > 0 ? cleanDescription(source.description) : '';
323
+ const tooltip = trimmedOrUndefined(source.tooltip);
324
+ const item: StrategyRiskItem = {
325
+ name,
326
+ ...(description ? { description } : {}),
327
+ clauses,
328
+ ...(tooltip ? { tooltip } : {}),
329
+ };
330
+ const existing = groups.get(group);
331
+ if (existing) existing.items.push(item);
332
+ else groups.set(group, { group, items: [item] });
333
+ }
334
+ // Array.prototype.sort is stable, so unlisted groups keep CMS order.
335
+ return [...groups.values()].sort(
336
+ (a, b) => riskGroupRank(a.group) - riskGroupRank(b.group),
337
+ );
338
+ }
339
+
340
+ const RISK_GROUP_RANK = new Map(
341
+ RISK_GROUP_ORDER.map((group, index) => [group.toLowerCase(), index]),
342
+ );
343
+
344
+ function riskGroupRank(group: string): number {
345
+ return (
346
+ RISK_GROUP_RANK.get(group.trim().toLowerCase()) ??
347
+ RISK_GROUP_ORDER.length
348
+ );
349
+ }
350
+
351
+ /**
352
+ * The pool's security tags (the CMS `security` list), trimmed, blanks
353
+ * dropped. `undefined` when none remain.
354
+ *
355
+ * kasu-ui shows these under "Security Structure over End Borrowers" ONLY
356
+ * when the pool has no risk-management items.
357
+ */
358
+ export function securityStructureOf(raw: unknown): string[] | undefined {
359
+ if (!Array.isArray(raw)) return undefined;
360
+ const tags = raw
361
+ .map((tag) => trimmedOrUndefined(tag))
362
+ .filter((tag): tag is string => tag !== undefined);
363
+ return tags.length > 0 ? tags : undefined;
364
+ }
365
+
366
+ // ---------------------------------------------------------------------------
367
+ // Numbers
368
+ // ---------------------------------------------------------------------------
369
+
370
+ /**
371
+ * A CMS or subgraph "numeric" value as a finite number, or `undefined`. An
372
+ * empty or blank string is UNAUTHORED, not zero; a genuine `0` survives.
373
+ */
374
+ export function finiteOrUndefined(value: unknown): number | undefined {
375
+ if (typeof value === 'number') {
376
+ return Number.isFinite(value) ? value : undefined;
377
+ }
378
+ if (typeof value === 'string') {
379
+ if (value.trim() === '') return undefined;
380
+ const numeric = Number(value);
381
+ return Number.isFinite(numeric) ? numeric : undefined;
382
+ }
383
+ return undefined;
384
+ }
385
+
386
+ // ---------------------------------------------------------------------------
387
+ // A strategy's money across deployments
388
+ // ---------------------------------------------------------------------------
389
+
390
+ /** One deployment's pool of a strategy, for `strategyTotalsUsd`. */
391
+ export interface StrategyTotalsLeg {
392
+ /**
393
+ * Which deployment this leg is — the same key the caller lists in
394
+ * `expectedDeployments` (e.g. `StrategyDeployment.chain`: `'base'`,
395
+ * `'xdc'`). Compared exactly.
396
+ */
397
+ deployment: string;
398
+ /** The pool's TVL (`Strategy.tvl.total`), in its own stable token. */
399
+ totalActiveLending: string | number;
400
+ /**
401
+ * The pool's lender interest earned
402
+ * (`Strategy.strategyHistory.lenderInterestEarned`), in its own stable
403
+ * token.
404
+ */
405
+ lenderInterestEarned?: string | number;
406
+ /**
407
+ * USD per 1 unit of this deployment's stable token (`1` for USDC).
408
+ * `undefined` while the rate is not known.
409
+ */
410
+ usdRate: number | undefined;
411
+ }
412
+
413
+ /** A strategy's two money figures, summed over the legs given, in USD. */
414
+ export interface StrategyTotalsUsd {
415
+ totalActiveLendingUsd: number;
416
+ lenderInterestEarnedUsd: number;
417
+ /**
418
+ * `true` when some expected deployment has no leg — it failed to load,
419
+ * or has not loaded yet — so both figures cover only `legs`, NOT the
420
+ * whole strategy. A caller stating them as the strategy-wide figure must
421
+ * say so (kasu-ui adds a partial-regions note) or fall back.
422
+ */
423
+ isPartial: boolean;
424
+ /**
425
+ * The expected deployments with no leg, in `expectedDeployments` order.
426
+ * Empty exactly when `isPartial` is `false`.
427
+ */
428
+ missingDeployments: string[];
429
+ }
430
+
431
+ export type StrategyTotalsInputErrorCode = 'duplicate-leg' | 'unexpected-leg';
432
+
433
+ /**
434
+ * A leg `strategyTotalsUsd` cannot place: two legs for one deployment
435
+ * (`duplicate-leg`, which would double-count it), or a leg for a deployment
436
+ * not in `expectedDeployments` (`unexpected-leg`, a pool of some other
437
+ * strategy). Thrown, because both are caller bugs, not data states.
438
+ */
439
+ export class StrategyTotalsInputError extends Error {
440
+ constructor(
441
+ readonly code: StrategyTotalsInputErrorCode,
442
+ readonly deployment: string,
443
+ ) {
444
+ super(
445
+ code === 'duplicate-leg'
446
+ ? `strategyTotalsUsd: two legs for deployment "${deployment}"`
447
+ : `strategyTotalsUsd: leg for deployment "${deployment}" is not in expectedDeployments`,
448
+ );
449
+ this.name = 'StrategyTotalsInputError';
450
+ }
451
+ }
452
+
453
+ /**
454
+ * Total Active Lending and Lender Interest Earned for a strategy across the
455
+ * deployments it lends on, in USD: each leg's native amount times that leg's
456
+ * own `usdRate`, summed. Tax Pay lends on Base (USDC) and XDC (AUDD);
457
+ * 2,567,901 AUDD is not US$2,567,901.
458
+ *
459
+ * `expectedDeployments` is every deployment the strategy has a pool on —
460
+ * `strategyDeployments(poolId, chain).map((d) => d.chain)` — and `legs` the
461
+ * ones whose pool the caller actually loaded. What is guaranteed:
462
+ *
463
+ * - **`null` — WITHHELD** when there are no legs, or ANY leg's rate is
464
+ * missing or unusable (not a finite number above 0). The total is never
465
+ * built on a guessed rate, and never silently drops a loaded leg; the
466
+ * caller shows the held pool's own figure, or nothing.
467
+ * - **Otherwise the sum over `legs`**, with `isPartial` /
468
+ * `missingDeployments` stating exactly which expected deployments it
469
+ * does NOT cover. `isPartial: false` is the only case in which the
470
+ * figures are the whole strategy.
471
+ * - An amount that is absent or malformed contributes nothing (a real `0`
472
+ * is still `0`).
473
+ * - Throws `StrategyTotalsInputError` for a duplicated leg or one not in
474
+ * `expectedDeployments`, before summing anything.
475
+ *
476
+ * Only these two figures are summed. The CMS-authored ones — every
477
+ * originator figure, `operatingSince`, the loss rates — are shared by a
478
+ * strategy's pools and already strategy-wide: summing them double-counts.
479
+ *
480
+ * Mirrors the money half of kasu-ui's `aggregateStrategyPools` and its
481
+ * withhold gate.
482
+ */
483
+ export function strategyTotalsUsd(
484
+ legs: readonly StrategyTotalsLeg[],
485
+ expectedDeployments: readonly string[],
486
+ ): StrategyTotalsUsd | null {
487
+ const expected = new Set(expectedDeployments);
488
+ const seen = new Set<string>();
489
+ for (const leg of legs) {
490
+ if (seen.has(leg.deployment)) {
491
+ throw new StrategyTotalsInputError('duplicate-leg', leg.deployment);
492
+ }
493
+ if (!expected.has(leg.deployment)) {
494
+ throw new StrategyTotalsInputError(
495
+ 'unexpected-leg',
496
+ leg.deployment,
497
+ );
498
+ }
499
+ seen.add(leg.deployment);
500
+ }
501
+ if (legs.length === 0) return null;
502
+
503
+ let totalActiveLendingUsd = 0;
504
+ let lenderInterestEarnedUsd = 0;
505
+ for (const leg of legs) {
506
+ const rate = leg.usdRate;
507
+ if (typeof rate !== 'number' || !Number.isFinite(rate) || rate <= 0) {
508
+ return null;
509
+ }
510
+ totalActiveLendingUsd +=
511
+ (finiteOrUndefined(leg.totalActiveLending) ?? 0) * rate;
512
+ lenderInterestEarnedUsd +=
513
+ (finiteOrUndefined(leg.lenderInterestEarned) ?? 0) * rate;
514
+ }
515
+ const missingDeployments = [...expected].filter((d) => !seen.has(d));
516
+ return {
517
+ totalActiveLendingUsd,
518
+ lenderInterestEarnedUsd,
519
+ isPartial: missingDeployments.length > 0,
520
+ missingDeployments,
521
+ };
522
+ }
523
+
524
+ function trimmedOrUndefined(value: unknown): string | undefined {
525
+ if (typeof value !== 'string') return undefined;
526
+ const trimmed = value.trim();
527
+ return trimmed.length > 0 ? trimmed : undefined;
528
+ }
@@ -19,6 +19,16 @@ export { READ_ONLY_MESSAGE } from './read-only';
19
19
  // Chain configurations
20
20
  export { CHAIN_CONFIGS } from './chain-configs';
21
21
 
22
+ // Strategy ↔ deployment resolution (pure, over CHAIN_CONFIGS)
23
+ export {
24
+ StrategyDeploymentInputError,
25
+ strategyDeployments,
26
+ } from './strategy-deployments';
27
+ export type {
28
+ StrategyDeployment,
29
+ StrategyDeploymentInputErrorCode,
30
+ } from './strategy-deployments';
31
+
22
32
  // Directus-backed helpers (I/O — not part of `domain/`)
23
33
  export { fetchUnusedPoolIds } from './unused-pool-ids';
24
34
 
@@ -38,4 +48,7 @@ export type {
38
48
  UserPositions,
39
49
  PlatformStats,
40
50
  StrategyRiskPerformance,
51
+ StrategyHistory,
52
+ StrategyEndBorrowers,
53
+ OriginatorHistory,
41
54
  } from './types';