import { BigNumber } from 'ethers'; import { PoolTvlHistoryEntry } from '../../domain/pool-tvl'; /** * Which part of a pool's TVL history to return, and how long to wait for it. * Epochs are counted in the chain's numbering * (`SystemVariables.currentEpochNumber`), and the newest epoch is the * CURRENT one, which the closing `current` point carries. * * - neither field: every clearing, then the `current` point; * - `count` only: the newest `count` epochs, up to and including the current * one (a pool that did not clear in some of them has fewer points); * - `fromEpoch` only: `fromEpoch` up to the current epoch; * - both: `count` epochs starting at `fromEpoch`, capped at the current * epoch. The `current` point is included only when the window reaches the * current epoch. */ export interface PoolTvlHistoryOptions { /** First epoch included. A non-negative integer. */ fromEpoch?: number; /** How many epochs. A positive integer. */ count?: number; /** * The whole call's time limit, in MILLISECONDS. On expiry it rejects with * `PoolTvlHistoryTimeoutError` and starts no further request. * @default 30_000 */ timeoutMs?: number; /** * Abandons the call: it rejects with `PoolTvlHistoryAbortedError` and * starts no further request. Already aborted = rejected before any read. */ signal?: AbortSignal; } /** * `getPoolTvlHistoryWindow`'s answer: the same entries `getPoolTvlHistory` * returns, and the pool's value just before them. Pass it to * `combineTvlHistories` as a leg (`{ ...result, usdRate }`). */ export interface PoolTvlHistoryResult { entries: PoolTvlHistoryEntry[]; /** * The newest finished clearing BEFORE the window, in a block strictly * before the first entry's, read at its own block like every other point * (`kind: 'clearing'`). `null` when the pool has no clearing before the * window — its whole history is in `entries`. See `pickOpeningClearing`. */ opening: PoolTvlHistoryEntry | null; } /** The resolved, inclusive epoch range; `null` when it is empty. */ export interface PoolTvlHistoryWindow { fromEpoch: number; toEpoch: number; } /** Clearings per subgraph page (the subgraph's own row cap). */ export declare const TVL_HISTORY_PAGE_SIZE = 1000; /** * A runaway guard on the clearings pagination, not a working limit: a pool * clears once per epoch, so 20 pages would be twenty thousand cycles. */ export declare const TVL_HISTORY_MAX_PAGES = 20; /** * How many past blocks one time-travel request reads, as GraphQL aliases. A * pool with ~120 clearings costs two such requests. */ export declare const TVL_HISTORY_BLOCKS_PER_REQUEST = 100; /** At most this many past-state RPC reads are in flight at once. */ export declare const TVL_HISTORY_RPC_CONCURRENCY = 8; /** Attempts per past-state RPC read (each over every history RPC in turn). */ export declare const TVL_HISTORY_RPC_ATTEMPTS = 3; /** Back-off before the second attempt; doubled for each one after. */ export declare const TVL_HISTORY_RPC_RETRY_DELAY_MS = 500; /** Per-call timeout of the history providers the SDK builds itself. */ export declare const TVL_HISTORY_RPC_TIMEOUT_MS = 10000; /** Default `timeoutMs` of a whole `getPoolTvlHistory` call. */ export declare const TVL_HISTORY_DEFAULT_TIMEOUT_MS = 30000; /** * Blocks at least this far below the subgraph's head are treated as final * and their reads are cached; nearer ones are read again every time. */ export declare const TVL_HISTORY_CACHE_DEPTH = 64; /** Entries per SDK instance before the cache starts again from empty. */ export declare const TVL_HISTORY_CACHE_LIMIT = 20000; /** `getPoolTvlHistory` took longer than its `timeoutMs`. */ export declare class PoolTvlHistoryTimeoutError extends Error { readonly timeoutMs: number; constructor(timeoutMs: number); } /** `getPoolTvlHistory` was abandoned through its `signal`. */ export declare class PoolTvlHistoryAbortedError extends Error { constructor(); } /** * A history provider answered a past block as if nothing were deployed — no * code even for the pool, which cleared in that very block. A pruned node * does that; trusting it would draw the off-chain TVL as 0. */ export declare class PastStateUnavailableError extends Error { readonly block: number; constructor(block: number); } /** * Throws `RangeError` / `TypeError` on a malformed option. * `getPoolTvlHistory` calls it ONCE, BEFORE any network read; * `resolvePoolTvlHistoryWindow` assumes it has run. */ export declare function validatePoolTvlHistoryOptions(options: PoolTvlHistoryOptions): void; /** The epoch window. Options must already have passed validation. */ export declare function resolvePoolTvlHistoryWindow(options: Pick, currentEpoch: number): PoolTvlHistoryWindow | null; /** What every stage checks before it starts more work. */ export interface Cancellation { /** Aborted with the call; hand it to `fetch`-based clients. */ readonly signal: AbortSignal; /** Throws the typed reason once the call is timed out or aborted. */ throwIfCancelled(): void; } /** * Runs `work` under a deadline and an optional caller signal. Whichever comes * first rejects the returned promise with its typed error at once, aborts * `cancellation.signal` (cancelling in-flight subgraph requests) and makes * every later `throwIfCancelled()` throw, so no new read starts. An RPC call * already sent cannot be recalled; its answer is dropped. */ export declare function runCancellable(timeoutMs: number, external: AbortSignal | undefined, work: (cancellation: Cancellation) => Promise): Promise; /** * The pool's FINISHED clearings, plus — on the first page only — its balance * now and the subgraph's latest block. * * Two modes over one document: ascending from `$epochGte` (a `fromEpoch` * window, or everything), or descending below `$epochLt` (the newest N, for * a `count`-only window, so it never pages through the whole history). */ export declare const poolTvlClearingsQuery: string; export interface ClearingRow { epochId: string; endBlockNumber: string; endTimestamp: string; } export interface PoolTvlSnapshot { pool?: { balance: string; } | null; meta?: { block: { number: number; timestamp: number | null; }; } | null; } export interface PoolTvlClearingsResult extends PoolTvlSnapshot { clearings: ClearingRow[]; } /** The time-travel alias for one block: `b`. */ export declare function blockAlias(block: number): string; /** * One time-travel request: the pool's balance at the END of each block, one * alias per block. Block numbers are written into the document, so each must * be a positive safe integer — anything else throws rather than reaching the * query text. The pool id travels as a variable. */ export declare function poolBalancesAtBlocksQuery(blocks: readonly number[]): string; export type PoolBalancesAtBlocksResult = Record; /** One subgraph request; `signal` cancels it. */ export type GraphRequest = (document: string, variables: Record, signal?: AbortSignal) => Promise; /** A clearing row parsed and checked. */ export interface Clearing { epochId: number; block: number; timestamp: number; } /** Which clearings to read: ascending from an epoch, or the newest N. */ export type ClearingsScope = { kind: 'from'; fromEpoch: number; } | { kind: 'newest'; count: number; }; /** * The scope's finished clearings, ascending by epoch, and the snapshot from * the first page. Normally ONE request. */ export declare function fetchPoolClearings(request: GraphRequest, poolId: string, scope: ClearingsScope, cancellation: Cancellation): Promise<{ clearings: Clearing[]; snapshot: PoolTvlSnapshot; requests: number; }>; /** * Pure: the opening clearing — the newest of `before` (finished clearings the * window left out, older by epoch) that finished STRICTLY before the first * in-window clearing's block. Newest by block, then epoch, so a clearing * numbered out of order (XDC AUDD's epoch 1, a week before epoch 88) is * placed by when it happened. A clearing in the first in-window block itself * (a catch-up block that finished several epochs at once) is not an opening: * it holds the first entry's own value, not the one before it. `null` when * there is none — see `needsClearingBeforeBlock`. */ export declare function pickOpeningClearing(before: readonly Clearing[], inWindow: readonly Clearing[]): Clearing | null; /** * Pure: whether the opening needs `fetchClearingBefore`'s by-block read. * Only when the window left clearings out but every one of them finished in * or after the first in-window block — the extra rows sat in a catch-up * block — so an older one, if any, was not fetched. Otherwise the opening * (or its absence) is already known and nothing more is read. */ export declare function needsClearingBeforeBlock(before: readonly Clearing[], opening: Clearing | null): boolean; /** * The newest finished clearing in a block below `blockLt`, by block: the * opening when every clearing the window left out shares its first block. * ONE extra request for one row, no snapshot. Clearings that share that * older block share its time and balance, so which one comes back does not * change the value. */ export declare const poolTvlClearingBeforeBlockQuery: string; export declare function fetchClearingBeforeBlock(request: GraphRequest, poolId: string, blockLt: number, cancellation: Cancellation): Promise; /** * The newest finished clearing numbered below `beforeEpoch`: the opening * candidate of a `fromEpoch` window, whose own fetch never reads that far * back. ONE extra request for one row, no snapshot. */ export declare function fetchClearingBefore(request: GraphRequest, poolId: string, beforeEpoch: number, cancellation: Cancellation): Promise; /** * The pool's balance (display units, the subgraph's decimal string) at the end * of each block, `TVL_HISTORY_BLOCKS_PER_REQUEST` blocks per request. A block * at which the subgraph has no such pool THROWS: a finished clearing of the * pool happened in it, so a missing pool means a broken read, not a zero. */ export declare function fetchPoolBalancesAtBlocks(request: GraphRequest, poolId: string, blocks: readonly number[], cancellation: Cancellation): Promise<{ balances: Map; requests: number; }>; /** * What a history provider must answer: an `eth_call` and an `eth_getCode` * at a block. Any ethers v5 `Provider` is one. */ export interface HistoryRpc { call(transaction: { to: string; data: string; }, blockTag: number | 'latest'): Promise; getCode(address: string, blockTag: number): Promise; } /** * The past-state reads behind the off-chain TVL. Every method rejects on any * failure; none may turn an error into a value. */ export interface OffChainTvlReader { /** `externalTVLOfPool(pool)` at `block`, in the stable token's BASE units. */ readAt(block: number | 'latest'): Promise; /** Whether the `ExternalTVL` contract has code at `block`. */ hasCodeAt(block: number): Promise; /** Whether the POOL contract has code at `block` (the pruned-node check). */ poolHasCodeAt(block: number): Promise; } /** * The real reader: each read goes to the history RPCs IN ORDER until one * answers, and the whole chain is retried `attempts` times with back-off. * After the last attempt the last error propagates — never a value. Each * attempt first checks the cancellation, so a timed-out call stops here. */ export declare function createOffChainTvlReader({ externalTvl, pool, rpcs, cancellation, attempts, delayMs, sleep, }: { externalTvl: string; pool: string; rpcs: readonly HistoryRpc[]; cancellation: Cancellation; attempts?: number; delayMs?: number; sleep?: (ms: number) => Promise; }): OffChainTvlReader; /** * Index of the first block (of `blocks`, ascending) at which the contract has * code; `blocks.length` when it has code at none. A deployed contract keeps * its code (it is a proxy, never self-destructed), so the answer is a single * boundary and a binary search finds it: ONE `getCode` when the contract * already existed at the oldest clearing, about log2(n) otherwise. */ export declare function firstBlockWithCode(blocks: readonly number[], hasCodeAt: (block: number) => Promise): Promise; /** * `fn` over `items`, at most `limit` in flight; rejects on the first failure * and starts nothing after it (or after `beforeEach` throws). */ export declare function mapWithConcurrency(items: readonly T[], limit: number, fn: (item: T) => Promise, beforeEach?: () => void): Promise; /** * Immutable past-block reads, per SDK instance. Keys carry the contract (or * subgraph), the pool and the block, so two deployments never collide. */ export declare class PastBlockCache { private readonly _entries; get(key: string): T | undefined; set(key: string, value: unknown): void; get size(): number; } /** * The off-chain TVL (BASE units) at each block, and — with `withLatest` — at * the latest block, all inside ONE bounded pool of reads. * * Before the contract existed there was nothing to record, so those blocks * are 0 — decided by `getCode`, never by catching a revert: an RPC that * refuses past state can surface that refusal as a "call exception". And a * "no code" answer is believed only if the same provider DOES show code for * the pool at the oldest and newest such block (it cleared there); otherwise * `PastStateUnavailableError`. Every other failed read throws. * * `cached` blocks (final, below the head) are answered from `cache` and * stored there after a successful read. */ export declare function fetchOffChainTvlAtBlocks(reader: OffChainTvlReader, blocks: readonly number[], { withLatest, cancellation, cache, cacheKey, cacheable, }: { withLatest?: boolean; cancellation: Cancellation; cache?: PastBlockCache; cacheKey?: (kind: 'tvl' | 'code' | 'pool', block: number) => string; cacheable?: (block: number) => boolean; }): Promise<{ offChain: Map; latest: BigNumber | null; rpcReads: number; }>; export interface PoolTvlHistoryRead { /** Finished clearings inside the window. */ clearings: Clearing[]; /** On-chain balance (display units) at each distinct clearing block. */ balances: ReadonlyMap; /** Off-chain TVL (BASE units) at each distinct clearing block. */ offChain: ReadonlyMap; /** The closing point's inputs; `null` when the window stops short of now. */ current: { epochId: number; timestamp: number; balance: string; offChain: BigNumber; } | null; /** The stable token's decimals, for the off-chain BASE units. */ decimals: number; } /** * Pure: the reads → the history. One `clearing` point per clearing, ordered by * the block it finished in (then by epoch, for clearings that shared a block), * so the series is ascending in TIME even where epoch numbers jump; then the * `current` point. Each point is `poolTvl(onChain, offChain)` — the same * function `getPoolOverview` uses for `totalValueLocked.total`. */ export declare function buildPoolTvlHistory(read: PoolTvlHistoryRead): PoolTvlHistoryEntry[]; /** Ascending, de-duplicated clearing blocks: each past block is read ONCE. */ export declare function distinctBlocks(clearings: readonly Clearing[]): number[];