@kasufinance/kasu-sdk 2.13.1 → 2.14.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.
@@ -60,3 +60,107 @@ export interface PoolTvlHistoryEntry {
60
60
  /** `'clearing'` for a cycle boundary; `'current'` for the closing point. */
61
61
  kind: 'clearing' | 'current';
62
62
  }
63
+ /**
64
+ * One deployment's share of a strategy's history, for `combineTvlHistories`:
65
+ * that pool's `getPoolTvlHistoryWindow` result (`{ entries, opening }`) as it
66
+ * came back, and what one unit of the deployment's stable token is worth in
67
+ * USD (`1` for USDC; today's AUD→USD for AUDD). The SDK fetches no exchange
68
+ * rate: the caller passes it.
69
+ */
70
+ export interface TvlHistoryLeg {
71
+ /** At least one point: a real pool always returns its `current` point. */
72
+ entries: readonly PoolTvlHistoryEntry[];
73
+ /** USD per unit of the leg's stable token. Finite and above 0. */
74
+ usdRate: number;
75
+ /**
76
+ * The leg's step BEFORE its first entry: the newest clearing before the
77
+ * window, as `getPoolTvlHistoryWindow` read it at its own block. It
78
+ * counts from its own `timestamp` on, and the leg is 0 before that — no
79
+ * value is carried back to a time before it existed. A `'clearing'`
80
+ * point no later than the first entry; it is never drawn. `null` or
81
+ * absent: the pool has no clearing before the window (it started lending
82
+ * later, say) and counts 0 before its first entry.
83
+ */
84
+ opening?: PoolTvlHistoryEntry | null;
85
+ }
86
+ /**
87
+ * One point of a strategy's TVL summed across its deployments.
88
+ *
89
+ * There is no `epochId`: each chain clears at its own blocks and times, so a
90
+ * merged point belongs to no single epoch. Plot by `timestamp`.
91
+ */
92
+ export interface StrategyTvlHistoryEntry {
93
+ /** Unix SECONDS. Strictly ascending across the series. */
94
+ timestamp: number;
95
+ /** The sum over legs of each leg's TVL then, times its `usdRate`. */
96
+ tvlUsd: number;
97
+ /** `'clearing'` for a cycle boundary on any leg; `'current'` for the closing point. */
98
+ kind: 'clearing' | 'current';
99
+ }
100
+ /**
101
+ * What `combineTvlHistories` refuses, as a code:
102
+ *
103
+ * - `legs` — not a non-empty array (or one with holes);
104
+ * - `leg` — a leg that is not an object;
105
+ * - `usd-rate` — a rate that is not a finite number above 0;
106
+ * - `opening` — an opening that is not a well-formed `'clearing'` point at
107
+ * or before the leg's first entry (or `null`, or absent);
108
+ * - `entries` — a leg's `entries` is not an array;
109
+ * - `empty-leg` — a leg with no entries: pass only the legs you have;
110
+ * - `entry` — an entry that is not an object (or a hole);
111
+ * - `timestamp` / `tvl` — not a finite number at or above 0;
112
+ * - `kind` — neither `'clearing'` nor `'current'`;
113
+ * - `order` — timestamps going backwards within a leg;
114
+ * - `current` — a `current` point that is not the leg's last, or some legs
115
+ * ending in one and others not;
116
+ * - `overflow` — a sum too large to be a finite number.
117
+ */
118
+ export type TvlHistoryInputErrorCode = 'legs' | 'leg' | 'usd-rate' | 'opening' | 'entries' | 'empty-leg' | 'entry' | 'timestamp' | 'tvl' | 'kind' | 'order' | 'current' | 'overflow';
119
+ /**
120
+ * What `combineTvlHistories` throws instead of returning a number it cannot
121
+ * stand behind. `leg` and `entry` are the zero-based position of the
122
+ * offending input, when there is one.
123
+ */
124
+ export declare class TvlHistoryInputError extends Error {
125
+ readonly code: TvlHistoryInputErrorCode;
126
+ readonly leg: number | undefined;
127
+ readonly entry: number | undefined;
128
+ constructor(code: TvlHistoryInputErrorCode, leg?: number, entry?: number);
129
+ }
130
+ /**
131
+ * A strategy's TVL in USD over time, from its deployments' histories — Tax
132
+ * Pay runs on Base (USDC) and on XDC (AUDD), and its total lent is both.
133
+ * Pure: the caller fetches each leg (`strategyDeployments` names them) and
134
+ * passes the exchange rates.
135
+ *
136
+ * A step merge by time. At every distinct timestamp where any leg has a
137
+ * clearing, the value is the sum over legs of that leg's latest point at or
138
+ * before then, times its `usdRate`. A leg's `opening` — what it held just
139
+ * before the window — is one more step: it counts from its own timestamp
140
+ * until the leg's first entry, and the leg is 0 before it (or throughout,
141
+ * before its first entry, without one).
142
+ * Points that share a timestamp — clearings run in one block, or two chains
143
+ * clearing in the same second — are one output point. The series ends with
144
+ * one `current` point at the latest of the legs' `current` timestamps, equal
145
+ * to the sum of their `current` values. Every leg must end in a `current`
146
+ * point, or none may.
147
+ *
148
+ * The window is the union of the legs' windows: the series starts at the
149
+ * earliest first entry of any leg. An `opening` is a value, never a point.
150
+ * Without it, two windows cut at offset clearing times would count the
151
+ * later-starting leg 0 at the left edge and draw a false step up; with it,
152
+ * only a genuine late start (`opening: null`) counts 0.
153
+ *
154
+ * Every leg and entry is validated first: a bad input — an empty leg
155
+ * included — throws `TvlHistoryInputError` (its `code` says why), so the
156
+ * result never holds `NaN` or `Infinity`. The inputs are not modified.
157
+ *
158
+ * ```ts
159
+ * const window = { count: 52 };
160
+ * const points = combineTvlHistories([
161
+ * { ...(await base.strategies.getPoolTvlHistoryWindow(basePool, window)), usdRate: 1 },
162
+ * { ...(await xdc.strategies.getPoolTvlHistoryWindow(xdcPool, window)), usdRate: audToUsd },
163
+ * ]);
164
+ * ```
165
+ */
166
+ export declare function combineTvlHistories(legs: readonly TvlHistoryLeg[]): StrategyTvlHistoryEntry[];
@@ -8,5 +8,7 @@ export type { RequestWithdrawalCallParams } from './calls';
8
8
  export type { DepositFlowPortOverrides, WithdrawFlowPortOverrides, } from './flows';
9
9
  export { READ_ONLY_MESSAGE } from './read-only';
10
10
  export { CHAIN_CONFIGS } from './chain-configs';
11
+ export { StrategyDeploymentInputError, strategyDeployments, } from './strategy-deployments';
12
+ export type { StrategyDeployment, StrategyDeploymentInputErrorCode, } from './strategy-deployments';
11
13
  export { fetchUnusedPoolIds } from './unused-pool-ids';
12
14
  export type { SupportedChain, ChainConfigEntry, StableAsset, KasuOptions, Strategy, StrategyTranche, FixedTermOption, DepositParams, WithdrawParams, DepositLimits, KycParams, UserPositions, PlatformStats, StrategyRiskPerformance, } from './types';
@@ -1,6 +1,6 @@
1
1
  import { PoolTvlHistoryEntry } from '../domain/pool-tvl';
2
2
  import { DataService } from '../services/DataService/data-service';
3
- import { PoolTvlHistoryOptions } from '../services/DataService/tvl-history';
3
+ import { PoolTvlHistoryOptions, PoolTvlHistoryResult } from '../services/DataService/tvl-history';
4
4
  import { PoolDelegateProfileAndHistory } from '../services/DataService/types';
5
5
  import { UserLending } from '../services/UserLending/user-lending';
6
6
  import { DepositLimits, PlatformStats, Strategy, StrategyRiskPerformance, StrategyTranche } from './types';
@@ -104,6 +104,22 @@ export declare class StrategiesFacade {
104
104
  * ```
105
105
  */
106
106
  getPoolTvlHistory(poolId: string, options?: PoolTvlHistoryOptions): Promise<PoolTvlHistoryEntry[]>;
107
+ /**
108
+ * `getPoolTvlHistory` plus `opening` — the newest clearing before the
109
+ * window, read at its own block like every other point, or `null` when
110
+ * the pool has none — from the same read. Pass the result to
111
+ * `combineTvlHistories` as a leg with its `usdRate`: the opening is what
112
+ * the leg held before its first point, so a window cut at a different
113
+ * time on another chain does not count it 0. Same options and errors as
114
+ * `getPoolTvlHistory`; the extra cost is one clearing row (or, for
115
+ * `fromEpoch`, one small request) and one block.
116
+ *
117
+ * ```ts
118
+ * const leg = await kasu.strategies.getPoolTvlHistoryWindow(poolId, { count: 52 });
119
+ * // { entries: PoolTvlHistoryEntry[], opening: PoolTvlHistoryEntry | null }
120
+ * ```
121
+ */
122
+ getPoolTvlHistoryWindow(poolId: string, options?: PoolTvlHistoryOptions): Promise<PoolTvlHistoryResult>;
107
123
  /**
108
124
  * Fetch a single strategy by pool ID. Returns `null` if not found.
109
125
  */
@@ -0,0 +1,65 @@
1
+ import { ChainConfigEntry, SupportedChain } from './types';
2
+ /**
3
+ * Strategy ↔ deployment resolution. A lending strategy is not tied to one
4
+ * deployment: Tax Pay runs as one pool on Base (USDC) and another on XDC
5
+ * (AUDD), and the two share one CMS record keyed by the BASE pool id — the
6
+ * canonical id. Each chain config's `poolMetadataMapping` maps its
7
+ * chain-local ids to canonical ones; Base, being canonical, has none.
8
+ *
9
+ * Pure: it reads only the built-in `CHAIN_CONFIGS`. The same rules as
10
+ * kasu-ui's counterpart lookup, so both apps sum a strategy over the same
11
+ * pools.
12
+ */
13
+ /** The pool that represents a strategy on one deployment. */
14
+ export interface StrategyDeployment {
15
+ chain: SupportedChain;
16
+ /**
17
+ * Chain-local pool id, lowercase — what that chain's subgraph is keyed
18
+ * by.
19
+ */
20
+ poolId: string;
21
+ }
22
+ /**
23
+ * What `strategyDeployments` refuses, as a code:
24
+ *
25
+ * - `pool-id` — not a `0x` address;
26
+ * - `chain` — not a `SupportedChain`;
27
+ * - `wrong-chain` — the mapping places the id on ANOTHER deployment (an XDC
28
+ * chain-local id passed as Base, or a Base id passed as XDC). Querying one
29
+ * chain with another's address reads nothing, silently.
30
+ */
31
+ export type StrategyDeploymentInputErrorCode = 'pool-id' | 'chain' | 'wrong-chain';
32
+ /** What `strategyDeployments` throws for an id it cannot place. */
33
+ export declare class StrategyDeploymentInputError extends Error {
34
+ readonly code: StrategyDeploymentInputErrorCode;
35
+ constructor(code: StrategyDeploymentInputErrorCode);
36
+ }
37
+ type MappingConfigs = Readonly<Record<SupportedChain, Pick<ChainConfigEntry, 'poolMetadataMapping'>>>;
38
+ /**
39
+ * `strategyDeployments` over any configs — the export reads `CHAIN_CONFIGS`;
40
+ * the spec passes its own to cover shapes the built-in mapping lacks.
41
+ */
42
+ export declare function resolveStrategyDeployments(configs: MappingConfigs, poolId: string, chain: SupportedChain): StrategyDeployment[];
43
+ /**
44
+ * Every deployment a strategy has a pool on, canonical (Base) first, then the
45
+ * others in `CHAIN_CONFIGS` order — the legs to fetch and pass to
46
+ * `combineTvlHistories`. One entry for a strategy that lives on one chain
47
+ * only (PayFi, on Base).
48
+ *
49
+ * `chain` is the deployment `poolId` was read on — required, because an
50
+ * address alone does not say which chain it belongs to. From either side of
51
+ * a mapping the answer is the same set: Tax Pay's Base id on `'base'` and
52
+ * its XDC id on `'xdc'` both return both pools. An id the mapping does not
53
+ * know is a strategy of one on its own chain. Ids are compared
54
+ * case-insensitively and returned lowercase.
55
+ *
56
+ * Throws `StrategyDeploymentInputError` for a malformed id, an unknown chain,
57
+ * or an id the mapping places on another deployment (`'wrong-chain'`).
58
+ *
59
+ * ```ts
60
+ * strategyDeployments(strategy.id, 'base');
61
+ * // [{ chain: 'base', poolId: '0x…' }, { chain: 'xdc', poolId: '0x…' }]
62
+ * ```
63
+ */
64
+ export declare function strategyDeployments(poolId: string, chain: SupportedChain): StrategyDeployment[];
65
+ export {};
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ export type { PoolOverview, TrancheData, LendingTotals, PoolRepayment, RiskManag
6
6
  export type { UserRequest, UserRequestEvent, UserTrancheBalance, UserPoolBalance, UserApyBonus, PortfolioUserTrancheBalance, } from './services/UserLending/types';
7
7
  export type { PortfolioSummary, PortfolioLendingPool, PortfolioTranche, PortfolioRewards, PortfolioTrancheDepositDetails, } from './services/Portfolio/types';
8
8
  export type { YieldHistoryOptions } from './services/Portfolio/yield-history';
9
- export type { PoolTvlHistoryOptions } from './services/DataService/tvl-history';
9
+ export type { PoolTvlHistoryOptions, PoolTvlHistoryResult, } from './services/DataService/tvl-history';
10
10
  export { PastStateUnavailableError, PoolTvlHistoryAbortedError, PoolTvlHistoryTimeoutError, } from './services/DataService/tvl-history';
11
11
  export { NO_HISTORY_PROVIDER_MESSAGE } from './services/DataService/data-service';
12
12
  export type { UserLock, UserBonusData, LockPeriod, GQLGetLockingPeriods, SystemVariables, } from './services/Locking/types';
@@ -4,7 +4,7 @@ import { PoolTvlHistoryEntry } from '../../domain/pool-tvl';
4
4
  import { SdkConfig } from '../../sdk-config';
5
5
  import { NftBoostDirectus, PlatformOverviewDirectus } from './directus-types';
6
6
  import { LendingPoolConfigurationSubgraph, LendingPoolSubgraph } from './subgraph-types';
7
- import { PoolTvlHistoryOptions } from './tvl-history';
7
+ import { PoolTvlHistoryOptions, PoolTvlHistoryResult } from './tvl-history';
8
8
  import { BadAndDoubtfulDebts, FinancialReportingDocuments, LendingTotals, PoolCreditMetrics, PoolDelegateProfileAndHistory, PoolOverview, PoolRepayment, PoolTranche, RiskManagement } from './types';
9
9
  /** Thrown by `getPoolTvlHistory` when no provider that serves past state is configured. */
10
10
  export declare const NO_HISTORY_PROVIDER_MESSAGE = "getPoolTvlHistory: no history provider; pass historyProvider or set historyRpcUrls to RPCs that serve past state";
@@ -100,6 +100,34 @@ export declare class DataService {
100
100
  * `PastStateUnavailableError` from a pruned history provider.
101
101
  */
102
102
  getPoolTvlHistory(poolId: string, options?: PoolTvlHistoryOptions): Promise<PoolTvlHistoryEntry[]>;
103
+ /**
104
+ * `getPoolTvlHistory` — the same options, errors and `entries` — plus
105
+ * `opening`: the pool's value just before the window, so a strategy
106
+ * summed across deployments (`combineTvlHistories`) knows what each leg
107
+ * held before its first point instead of counting it 0.
108
+ *
109
+ * `opening` is the newest finished clearing STRICTLY before the window's
110
+ * first block (by `pickOpeningClearing`), read at its own block exactly
111
+ * like every other point and through the same past-block cache; `null`
112
+ * when the pool has no clearing before the window. Extra cost over
113
+ * `getPoolTvlHistory`:
114
+ *
115
+ * - `count` only: one more clearing row in the same request (`count + 1`,
116
+ * which always reaches past the window when older history exists);
117
+ * - `fromEpoch` above 0: one more one-row subgraph request, in parallel
118
+ * with the clearings;
119
+ * - only when every left-out clearing finished in the window's first
120
+ * block (a catch-up block that closed several epochs at once): one
121
+ * more one-row request by block (`fetchClearingBeforeBlock`), after
122
+ * the clearings — the common case never makes it;
123
+ * - either way, the opening's block in the same batched time-travel read
124
+ * and one more `externalTVLOfPool` read (cached once final).
125
+ *
126
+ * `{ entries: [], opening: null }` wherever `getPoolTvlHistory` returns
127
+ * `[]`.
128
+ */
129
+ getPoolTvlHistoryWindow(poolId: string, options?: PoolTvlHistoryOptions): Promise<PoolTvlHistoryResult>;
130
+ private _poolTvlHistory;
103
131
  private _readPoolTvlHistory;
104
132
  /** The pool's balance at each block: cached final blocks, then one batch. */
105
133
  private _balancesAtBlocks;
@@ -31,6 +31,21 @@ export interface PoolTvlHistoryOptions {
31
31
  */
32
32
  signal?: AbortSignal;
33
33
  }
34
+ /**
35
+ * `getPoolTvlHistoryWindow`'s answer: the same entries `getPoolTvlHistory`
36
+ * returns, and the pool's value just before them. Pass it to
37
+ * `combineTvlHistories` as a leg (`{ ...result, usdRate }`).
38
+ */
39
+ export interface PoolTvlHistoryResult {
40
+ entries: PoolTvlHistoryEntry[];
41
+ /**
42
+ * The newest finished clearing BEFORE the window, in a block strictly
43
+ * before the first entry's, read at its own block like every other point
44
+ * (`kind: 'clearing'`). `null` when the pool has no clearing before the
45
+ * window — its whole history is in `entries`. See `pickOpeningClearing`.
46
+ */
47
+ opening: PoolTvlHistoryEntry | null;
48
+ }
34
49
  /** The resolved, inclusive epoch range; `null` when it is empty. */
35
50
  export interface PoolTvlHistoryWindow {
36
51
  fromEpoch: number;
@@ -171,6 +186,40 @@ export declare function fetchPoolClearings(request: GraphRequest, poolId: string
171
186
  snapshot: PoolTvlSnapshot;
172
187
  requests: number;
173
188
  }>;
189
+ /**
190
+ * Pure: the opening clearing — the newest of `before` (finished clearings the
191
+ * window left out, older by epoch) that finished STRICTLY before the first
192
+ * in-window clearing's block. Newest by block, then epoch, so a clearing
193
+ * numbered out of order (XDC AUDD's epoch 1, a week before epoch 88) is
194
+ * placed by when it happened. A clearing in the first in-window block itself
195
+ * (a catch-up block that finished several epochs at once) is not an opening:
196
+ * it holds the first entry's own value, not the one before it. `null` when
197
+ * there is none — see `needsClearingBeforeBlock`.
198
+ */
199
+ export declare function pickOpeningClearing(before: readonly Clearing[], inWindow: readonly Clearing[]): Clearing | null;
200
+ /**
201
+ * Pure: whether the opening needs `fetchClearingBefore`'s by-block read.
202
+ * Only when the window left clearings out but every one of them finished in
203
+ * or after the first in-window block — the extra rows sat in a catch-up
204
+ * block — so an older one, if any, was not fetched. Otherwise the opening
205
+ * (or its absence) is already known and nothing more is read.
206
+ */
207
+ export declare function needsClearingBeforeBlock(before: readonly Clearing[], opening: Clearing | null): boolean;
208
+ /**
209
+ * The newest finished clearing in a block below `blockLt`, by block: the
210
+ * opening when every clearing the window left out shares its first block.
211
+ * ONE extra request for one row, no snapshot. Clearings that share that
212
+ * older block share its time and balance, so which one comes back does not
213
+ * change the value.
214
+ */
215
+ export declare const poolTvlClearingBeforeBlockQuery: string;
216
+ export declare function fetchClearingBeforeBlock(request: GraphRequest, poolId: string, blockLt: number, cancellation: Cancellation): Promise<Clearing | null>;
217
+ /**
218
+ * The newest finished clearing numbered below `beforeEpoch`: the opening
219
+ * candidate of a `fromEpoch` window, whose own fetch never reads that far
220
+ * back. ONE extra request for one row, no snapshot.
221
+ */
222
+ export declare function fetchClearingBefore(request: GraphRequest, poolId: string, beforeEpoch: number, cancellation: Cancellation): Promise<Clearing | null>;
174
223
  /**
175
224
  * The pool's balance (display units, the subgraph's decimal string) at the end
176
225
  * of each block, `TVL_HISTORY_BLOCKS_PER_REQUEST` blocks per request. A block
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kasufinance/kasu-sdk",
3
- "version": "2.13.1",
3
+ "version": "2.14.0",
4
4
  "description": "TypeScript SDK for the Kasu Finance protocol — pool data, portfolio analytics, and KYC-gated deposits and withdrawals on Base and XDC",
5
5
  "keywords": [
6
6
  "kasu",
@@ -188,8 +188,13 @@ export {
188
188
  } from './wallet-errors';
189
189
  export type { WalletFailure } from './wallet-errors';
190
190
 
191
- export { poolTvl } from './pool-tvl';
192
- export type { PoolTvlHistoryEntry } from './pool-tvl';
191
+ export { combineTvlHistories, poolTvl, TvlHistoryInputError } from './pool-tvl';
192
+ export type {
193
+ PoolTvlHistoryEntry,
194
+ StrategyTvlHistoryEntry,
195
+ TvlHistoryInputErrorCode,
196
+ TvlHistoryLeg,
197
+ } from './pool-tvl';
193
198
 
194
199
  export { aggregateYieldHistory, epochTrancheYield } from './yield-history';
195
200
  export type {
@@ -64,3 +64,284 @@ export interface PoolTvlHistoryEntry {
64
64
  /** `'clearing'` for a cycle boundary; `'current'` for the closing point. */
65
65
  kind: 'clearing' | 'current';
66
66
  }
67
+
68
+ /**
69
+ * One deployment's share of a strategy's history, for `combineTvlHistories`:
70
+ * that pool's `getPoolTvlHistoryWindow` result (`{ entries, opening }`) as it
71
+ * came back, and what one unit of the deployment's stable token is worth in
72
+ * USD (`1` for USDC; today's AUD→USD for AUDD). The SDK fetches no exchange
73
+ * rate: the caller passes it.
74
+ */
75
+ export interface TvlHistoryLeg {
76
+ /** At least one point: a real pool always returns its `current` point. */
77
+ entries: readonly PoolTvlHistoryEntry[];
78
+ /** USD per unit of the leg's stable token. Finite and above 0. */
79
+ usdRate: number;
80
+ /**
81
+ * The leg's step BEFORE its first entry: the newest clearing before the
82
+ * window, as `getPoolTvlHistoryWindow` read it at its own block. It
83
+ * counts from its own `timestamp` on, and the leg is 0 before that — no
84
+ * value is carried back to a time before it existed. A `'clearing'`
85
+ * point no later than the first entry; it is never drawn. `null` or
86
+ * absent: the pool has no clearing before the window (it started lending
87
+ * later, say) and counts 0 before its first entry.
88
+ */
89
+ opening?: PoolTvlHistoryEntry | null;
90
+ }
91
+
92
+ /**
93
+ * One point of a strategy's TVL summed across its deployments.
94
+ *
95
+ * There is no `epochId`: each chain clears at its own blocks and times, so a
96
+ * merged point belongs to no single epoch. Plot by `timestamp`.
97
+ */
98
+ export interface StrategyTvlHistoryEntry {
99
+ /** Unix SECONDS. Strictly ascending across the series. */
100
+ timestamp: number;
101
+ /** The sum over legs of each leg's TVL then, times its `usdRate`. */
102
+ tvlUsd: number;
103
+ /** `'clearing'` for a cycle boundary on any leg; `'current'` for the closing point. */
104
+ kind: 'clearing' | 'current';
105
+ }
106
+
107
+ /**
108
+ * What `combineTvlHistories` refuses, as a code:
109
+ *
110
+ * - `legs` — not a non-empty array (or one with holes);
111
+ * - `leg` — a leg that is not an object;
112
+ * - `usd-rate` — a rate that is not a finite number above 0;
113
+ * - `opening` — an opening that is not a well-formed `'clearing'` point at
114
+ * or before the leg's first entry (or `null`, or absent);
115
+ * - `entries` — a leg's `entries` is not an array;
116
+ * - `empty-leg` — a leg with no entries: pass only the legs you have;
117
+ * - `entry` — an entry that is not an object (or a hole);
118
+ * - `timestamp` / `tvl` — not a finite number at or above 0;
119
+ * - `kind` — neither `'clearing'` nor `'current'`;
120
+ * - `order` — timestamps going backwards within a leg;
121
+ * - `current` — a `current` point that is not the leg's last, or some legs
122
+ * ending in one and others not;
123
+ * - `overflow` — a sum too large to be a finite number.
124
+ */
125
+ export type TvlHistoryInputErrorCode =
126
+ | 'legs'
127
+ | 'leg'
128
+ | 'usd-rate'
129
+ | 'opening'
130
+ | 'entries'
131
+ | 'empty-leg'
132
+ | 'entry'
133
+ | 'timestamp'
134
+ | 'tvl'
135
+ | 'kind'
136
+ | 'order'
137
+ | 'current'
138
+ | 'overflow';
139
+
140
+ /**
141
+ * What `combineTvlHistories` throws instead of returning a number it cannot
142
+ * stand behind. `leg` and `entry` are the zero-based position of the
143
+ * offending input, when there is one.
144
+ */
145
+ export class TvlHistoryInputError extends Error {
146
+ readonly code: TvlHistoryInputErrorCode;
147
+ readonly leg: number | undefined;
148
+ readonly entry: number | undefined;
149
+
150
+ constructor(code: TvlHistoryInputErrorCode, leg?: number, entry?: number) {
151
+ const at = [
152
+ leg === undefined ? '' : ` at leg ${String(leg)}`,
153
+ entry === undefined ? '' : `, entry ${String(entry)}`,
154
+ ].join('');
155
+ super(`combineTvlHistories: input refused (${code})${at}`);
156
+ this.name = 'TvlHistoryInputError';
157
+ this.code = code;
158
+ this.leg = leg;
159
+ this.entry = entry;
160
+ Object.setPrototypeOf(this, TvlHistoryInputError.prototype);
161
+ }
162
+ }
163
+
164
+ function isNonNegativeFinite(value: unknown): value is number {
165
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0;
166
+ }
167
+
168
+ /**
169
+ * Throws unless the leg is well formed. Index loops, not `forEach`: a hole in
170
+ * a sparse array is skipped by the array methods and would surface later as
171
+ * a raw `TypeError` instead of a refusal.
172
+ */
173
+ function validateLeg(leg: unknown, legIndex: number): TvlHistoryLeg {
174
+ if (typeof leg !== 'object' || leg === null) {
175
+ throw new TvlHistoryInputError('leg', legIndex);
176
+ }
177
+ const { entries, usdRate, opening } = leg as Partial<TvlHistoryLeg>;
178
+ if (
179
+ typeof usdRate !== 'number' ||
180
+ !Number.isFinite(usdRate) ||
181
+ usdRate <= 0
182
+ ) {
183
+ throw new TvlHistoryInputError('usd-rate', legIndex);
184
+ }
185
+ if (!Array.isArray(entries as unknown)) {
186
+ throw new TvlHistoryInputError('entries', legIndex);
187
+ }
188
+ const list = entries as readonly unknown[];
189
+ if (list.length === 0) {
190
+ throw new TvlHistoryInputError('empty-leg', legIndex);
191
+ }
192
+ let previous = -Infinity;
193
+ for (let index = 0; index < list.length; index += 1) {
194
+ const entry = list[index];
195
+ if (typeof entry !== 'object' || entry === null) {
196
+ throw new TvlHistoryInputError('entry', legIndex, index);
197
+ }
198
+ const { timestamp, tvl, kind } = entry as Partial<PoolTvlHistoryEntry>;
199
+ if (!isNonNegativeFinite(timestamp)) {
200
+ throw new TvlHistoryInputError('timestamp', legIndex, index);
201
+ }
202
+ if (!isNonNegativeFinite(tvl)) {
203
+ throw new TvlHistoryInputError('tvl', legIndex, index);
204
+ }
205
+ if (kind !== 'clearing' && kind !== 'current') {
206
+ throw new TvlHistoryInputError('kind', legIndex, index);
207
+ }
208
+ if (kind === 'current' && index !== list.length - 1) {
209
+ throw new TvlHistoryInputError('current', legIndex, index);
210
+ }
211
+ if (timestamp < previous) {
212
+ throw new TvlHistoryInputError('order', legIndex, index);
213
+ }
214
+ previous = timestamp;
215
+ }
216
+ if (opening !== undefined && opening !== null) {
217
+ const first = list[0] as PoolTvlHistoryEntry;
218
+ const { timestamp, tvl, kind } = (
219
+ typeof opening === 'object' ? opening : {}
220
+ ) as Partial<PoolTvlHistoryEntry>;
221
+ if (
222
+ !isNonNegativeFinite(timestamp) ||
223
+ !isNonNegativeFinite(tvl) ||
224
+ kind !== 'clearing' ||
225
+ timestamp > first.timestamp
226
+ ) {
227
+ throw new TvlHistoryInputError('opening', legIndex);
228
+ }
229
+ }
230
+ return leg as TvlHistoryLeg;
231
+ }
232
+
233
+ /**
234
+ * A strategy's TVL in USD over time, from its deployments' histories — Tax
235
+ * Pay runs on Base (USDC) and on XDC (AUDD), and its total lent is both.
236
+ * Pure: the caller fetches each leg (`strategyDeployments` names them) and
237
+ * passes the exchange rates.
238
+ *
239
+ * A step merge by time. At every distinct timestamp where any leg has a
240
+ * clearing, the value is the sum over legs of that leg's latest point at or
241
+ * before then, times its `usdRate`. A leg's `opening` — what it held just
242
+ * before the window — is one more step: it counts from its own timestamp
243
+ * until the leg's first entry, and the leg is 0 before it (or throughout,
244
+ * before its first entry, without one).
245
+ * Points that share a timestamp — clearings run in one block, or two chains
246
+ * clearing in the same second — are one output point. The series ends with
247
+ * one `current` point at the latest of the legs' `current` timestamps, equal
248
+ * to the sum of their `current` values. Every leg must end in a `current`
249
+ * point, or none may.
250
+ *
251
+ * The window is the union of the legs' windows: the series starts at the
252
+ * earliest first entry of any leg. An `opening` is a value, never a point.
253
+ * Without it, two windows cut at offset clearing times would count the
254
+ * later-starting leg 0 at the left edge and draw a false step up; with it,
255
+ * only a genuine late start (`opening: null`) counts 0.
256
+ *
257
+ * Every leg and entry is validated first: a bad input — an empty leg
258
+ * included — throws `TvlHistoryInputError` (its `code` says why), so the
259
+ * result never holds `NaN` or `Infinity`. The inputs are not modified.
260
+ *
261
+ * ```ts
262
+ * const window = { count: 52 };
263
+ * const points = combineTvlHistories([
264
+ * { ...(await base.strategies.getPoolTvlHistoryWindow(basePool, window)), usdRate: 1 },
265
+ * { ...(await xdc.strategies.getPoolTvlHistoryWindow(xdcPool, window)), usdRate: audToUsd },
266
+ * ]);
267
+ * ```
268
+ */
269
+ export function combineTvlHistories(
270
+ legs: readonly TvlHistoryLeg[],
271
+ ): StrategyTvlHistoryEntry[] {
272
+ if (!Array.isArray(legs as unknown) || legs.length === 0) {
273
+ throw new TvlHistoryInputError('legs');
274
+ }
275
+ const valid: TvlHistoryLeg[] = [];
276
+ for (let index = 0; index < legs.length; index += 1) {
277
+ valid.push(validateLeg(legs[index], index));
278
+ }
279
+ const endsInCurrent = valid.map(
280
+ (leg) => leg.entries[leg.entries.length - 1].kind === 'current',
281
+ );
282
+ const odd = endsInCurrent.findIndex((ends) => ends !== endsInCurrent[0]);
283
+ if (odd !== -1) throw new TvlHistoryInputError('current', odd);
284
+
285
+ const finalTimestamp = endsInCurrent[0]
286
+ ? Math.max(
287
+ ...valid.map(
288
+ (leg) => leg.entries[leg.entries.length - 1].timestamp,
289
+ ),
290
+ )
291
+ : undefined;
292
+ const clearingTimes = [
293
+ ...new Set(
294
+ valid.flatMap((leg) =>
295
+ leg.entries
296
+ .filter((entry) => entry.kind === 'clearing')
297
+ .map((entry) => entry.timestamp),
298
+ ),
299
+ ),
300
+ ]
301
+ .filter((t) => finalTimestamp === undefined || t < finalTimestamp)
302
+ .sort((a, b) => a - b);
303
+
304
+ // One cursor per leg: the times ascend, so each leg is walked once. A
305
+ // leg's `current` point is a step like any other, which keeps a chain
306
+ // whose subgraph lags behind the other's last clearing at its own latest.
307
+ const cursors = valid.map(() => -1);
308
+ const sumAt = (t: number): number => {
309
+ let sum = 0;
310
+ valid.forEach((leg, index) => {
311
+ let cursor = cursors[index];
312
+ while (
313
+ cursor + 1 < leg.entries.length &&
314
+ leg.entries[cursor + 1].timestamp <= t
315
+ ) {
316
+ cursor += 1;
317
+ }
318
+ cursors[index] = cursor;
319
+ // Before the first entry, the opening is the step — from its
320
+ // own time on, never earlier.
321
+ const opening = leg.opening;
322
+ const value =
323
+ cursor >= 0
324
+ ? leg.entries[cursor].tvl
325
+ : opening && opening.timestamp <= t
326
+ ? opening.tvl
327
+ : 0;
328
+ sum += value * leg.usdRate;
329
+ });
330
+ if (!Number.isFinite(sum)) throw new TvlHistoryInputError('overflow');
331
+ return sum;
332
+ };
333
+
334
+ const combined: StrategyTvlHistoryEntry[] = clearingTimes.map((t) => ({
335
+ timestamp: t,
336
+ tvlUsd: sumAt(t),
337
+ kind: 'clearing' as const,
338
+ }));
339
+ if (finalTimestamp !== undefined) {
340
+ combined.push({
341
+ timestamp: finalTimestamp,
342
+ tvlUsd: sumAt(finalTimestamp),
343
+ kind: 'current',
344
+ });
345
+ }
346
+ return combined;
347
+ }
@@ -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