import { BigNumberish, BytesLike } from 'ethers'; import { CmsTwoLineValue, StrategyFacility } from '../domain/strategy-details'; import { ContractAddresses, SdkConfigOptions } from '../sdk-config'; import { LendingTotals, PoolOverview, TrancheData } from '../services/DataService/types'; import { PortfolioLendingPool, PortfolioSummary } from '../services/Portfolio/types'; export type SupportedChain = 'base' | 'xdc' | 'xdc-usdc' | 'plume'; /** * The single stable token a deployment lends in. There is exactly ONE per * deployment and it never changes: a different stable token is a separate full * deployment (the XDC AUDD / XDC USDC pattern), never a companion vault on an * existing one. That is why this is a plain object on the chain config rather * than a list. */ export interface StableAsset { /** ERC-20 address of the stable token on this chain. */ address: string; /** Ticker as the token contract reports it (`USDC`, `AUDD`, `pUSD`). */ symbol: string; /** Token name as the contract reports it (`USD Coin`). */ name: string; /** * Token decimals. Feeds `SdkConfig.stableAssetDecimals`, so every * `parseUnits`/`formatUnits` in the SDK follows the chain rather than the * hard-coded default of 6. */ decimals: number; /** * ISO-4217 code of the fiat currency the token tracks (`USD`, `AUD`). * A CODE, not copy: consumers pick their own symbol and locale from it. * Nothing in this SDK formats it. */ currencyCode: string; } export interface ChainConfigEntry { chainId: number; name: string; isLiteDeployment: boolean; contracts: ContractAddresses; subgraphUrl: string; directusUrl: string; /** * Pools to hide. An EMPTY array is normalised to `['']` by `SdkConfig` — * the subgraph reads `id_not_in: []` as "match nothing" and returns zero * pools. See `SdkConfigOptions.UNUSED_LENDING_POOL_IDS`. */ unusedPoolIds: string[]; poolMetadataMapping?: Record; /** The one stable token this deployment lends in. */ stableAsset: StableAsset; /** * Public RPC endpoints for read-only use, in STARTING preference order * only. Apps are expected to override with their own paid/keyed endpoints * and their own failover; `Kasu.create` uses `rpcUrls[0]` and nothing else * when no `signerOrProvider` is passed. * * Empty on a retired deployment, which has no read-only default. */ rpcUrls: string[]; /** * RPCs that SERVE PAST STATE (archive nodes), tried IN ORDER on failure, * used only by `getPoolTvlHistory` to read the off-chain TVL at old * blocks. Pruned nodes refuse those reads — some answer as if the call * reverted — so these are never `rpcUrls[0]` by assumption. Public and * RATE-LIMITED: an integrator should pass its own archive * `KasuOptions.historyProvider`, which wins over them. Absent on a * retired deployment. */ historyRpcUrls?: string[]; /** * Origin of the chain's block explorer, `https://…` with NO trailing * slash (`https://basescan.org`). Never append a path to it by hand: build * links with `explorerTxUrl` / `explorerAddressUrl`, which validate the * hash or address first, so no app turns an unchecked string into a URL. */ blockExplorerUrl: string; /** * True for a wound-down deployment kept only as frozen history. It has no * default RPC, so a read-only `Kasu.create` on it throws. */ retired?: boolean; /** * Multicall3 on this chain, for `kasu.loyalty.getStatus`. Defaults to the * canonical `MULTICALL3_ADDRESS`; set it only on a custom chain where * Multicall3 lives elsewhere. */ multicall3Address?: string; } /** Options passed to `Kasu.create()`. */ export interface KasuOptions { /** A supported chain name or a custom `ChainConfigEntry`. */ chain: SupportedChain | ChainConfigEntry; /** * ethers Signer (for transactions) or Provider (read-only). * * OPTIONAL. When omitted, `Kasu.create` builds a read-only * `StaticJsonRpcProvider` on `chainConfig.rpcUrls[0]`, so browsing * strategies and platform stats needs no wallet at all. Get a writable * instance later with `kasu.connect(signer)`. */ signerOrProvider?: import('ethers').Signer | import('@ethersproject/providers').Provider; /** Override any default config value. */ configOverrides?: Partial; /** * A provider that SERVES PAST STATE (an archive RPC), for * `kasu.strategies.getPoolTvlHistory`. OPTIONAL: without one, the SDK * builds one `StaticJsonRpcProvider` per * `configOverrides.historyRpcUrls ?? chainConfig.historyRpcUrls` entry * (tried in order, 10 s per call). The built-in URLs are public and * rate-limited, so pass your own archive provider in production. Kept * across `connect(signer)`. */ historyProvider?: import('@ethersproject/providers').Provider; } export interface Strategy { id: string; name: string; /** * The CMS subheading (the borrower type shown under the name). Absent when * the record has none, or an empty one. */ subheading?: string; description: string; /** * The CMS short description (`liteDescription`) for compact surfaces. * Absent when the record has none, or an empty one. */ liteDescription?: string; /** * The strategy's short blurb as ONE line of plain text, for cards and * compact surfaces: `liteDescription` when it is usable, else the first * paragraph of `description`, with inline markdown markers stripped and * every run of whitespace collapsed to one space. The `"Not Available"` * placeholder, an empty or blank value, and a missing one all count as * absent. `undefined` when neither field yields a blurb; the SDK never * substitutes a sentence of its own. See `pickShortDescription`. * * Not sanitised: HTML tags and link syntax pass through unchanged. Render * it as text, never as HTML or markdown. */ summary?: string; isActive: boolean; /** Weighted-average APY across tranches (decimal, e.g. 0.08 = 8 %). */ apy: number; tvl: { /** On-chain + off-chain total. */ total: string; offchain: string; }; /** Remaining capacity across all tranches. */ availableCapacity: string; /** 0-1 utilisation ratio. */ capacityUtilisation: string; tranches: StrategyTranche[]; /** Asset class label (e.g. "Tax Receivables"). */ assetClass: string; /** Fixed or Variable. */ apyStructure: 'Variable' | 'Fixed'; /** Thumbnail image URL (empty string when Directus unavailable). */ thumbnailUrl: string; /** Banner image URL (empty string when Directus unavailable). */ bannerUrl: string; /** * The strategy's own lending history, as kasu-ui's Details tab states it * beside Total Active Lending (`tvl.total`). Each figure is absent when * unauthored or unreadable — omit its row, never print a stub. * * Always set by `getAll` / `getVisible` / `getById` (both figures inside * may still be absent). Optional in the type only so that a `Strategy` * built by hand against an earlier version still compiles. */ strategyHistory?: StrategyHistory; /** * Who the credit originator lends to, and on what facility. Absent when * the CMS authors neither. */ endBorrowers?: StrategyEndBorrowers; /** * The CMS security tags (`security`), trimmed, blanks dropped. Absent when * none are authored. * * kasu-ui shows these, under "Security Structure over End Borrowers", ONLY * when `getRiskManagementGroups` resolves `null` — they are the fallback * for a pool with no risk-management items, not a section of their own. * Treat a REJECTED `getRiskManagementGroups` (a CMS outage) the same way * for display: show these, and report the failure as you see fit. */ securityStructure?: string[]; /** Raw `PoolOverview` for power-users who need all fields. */ _raw: PoolOverview; } /** `Strategy.strategyHistory`. */ export interface StrategyHistory { /** * The date this strategy started lending (CMS `operatingSince`), as * `YYYY-MM-DD`. Absent when unauthored, not an ISO date, before 2000 or * in the future (see `readCmsStartDate`). Render it as elapsed time * ("Strategy Lending History"). */ since?: string; /** * Interest earned by this pool's lenders since inception (the subgraph's * `totalUserInterestAmount`, `PoolOverview.yieldEarned`), in display * units of the deployment's OWN stable token — like `tvl.total`. For the * strategy-wide figure across deployments in USD, see * `strategyTotalsUsd`. Absent when the value is not a finite number. */ lenderInterestEarned?: number; } /** `Strategy.endBorrowers`: at least one of the two is present. */ export interface StrategyEndBorrowers { /** * Business Types (CMS `industryExposure`): the value and its supporting * clause. Absent when unauthored. See `splitBusinessTypes`. */ businessTypes?: CmsTwoLineValue; /** * Facility Type (CMS `loanStructure`): the label, its clause, and whether * it revolves. Absent when unauthored. See `parseFacility`. */ facility?: StrategyFacility; } /** * The credit originator's ENTIRE lending history — every loan it has made, * not only this strategy's — from its CMS profile * (`kasu.strategies.getOriginatorHistory`). Each figure is absent when * unauthored or not a valid value; omit its tile, never print a stub. * * The money figures are editorial and already in USD, on every deployment: * never convert them by the deployment's FX rate, and never sum them across * a strategy's deployments. */ export interface OriginatorHistory { /** * The date the originator started lending (CMS * `delegateLendingHistory`), as `YYYY-MM-DD`. Render it as elapsed time * ("Entire Lending History"). */ since?: string; /** Total loan funds originated, USD (CMS `totalLoanFundsOriginated`). */ totalOriginated?: number; /** Loans outstanding, USD (CMS `loansUnderManagement` on the profile). */ loansOutstanding?: number; /** Historic loss rate, a 0..1 fraction (CMS `historicLossRate`). */ lossRate?: number; } export interface StrategyTranche { id: string; name: string; /** Current base APY (decimal). */ apy: number; minApy: number; maxApy: number; /** Minimum deposit in stable asset units (ether-formatted string). */ minimumDeposit: string; /** Maximum deposit in stable asset units (ether-formatted string). */ maximumDeposit: string; /** Remaining tranche capacity (ether-formatted string). */ availableCapacity: string; /** Fixed-term deposit options on this tranche. */ fixedTermOptions: FixedTermOption[]; /** Raw `TrancheData` for power-users. */ _raw: TrancheData; } export interface FixedTermOption { configId: string; /** Annual APY (decimal). */ apy: number; /** Lock duration in epochs (1 epoch ≈ 1 week). */ epochLockDuration: string; } export interface DepositParams { poolId: string; trancheId: string; /** Amount in stable asset base units (BigNumberish). */ amount: BigNumberish; /** KYC signature obtained from the Nexera flow. */ kycSignature: { blockExpiration: BigNumberish; signature: BytesLike; }; /** ABI-encoded deposit data (contract acceptance). Pass `'0x'` when not needed. */ depositData?: BytesLike; /** Fixed-term config ID. Pass `0` for variable deposits. */ fixedTermConfigId?: BigNumberish; /** Swap calldata. Pass `'0x'` when depositing the stable asset directly. */ swapData?: BytesLike; /** Native token value to send (e.g. for gas on some chains). Defaults to `'0'`. */ ethValue?: string; } export interface WithdrawParams { poolId: string; trancheId: string; /** Stable asset amount to withdraw, or `'max'` to withdraw entire balance. */ amount: BigNumberish; /** Required when `amount` is `'max'`. */ userAddress?: string; } export interface DepositLimits { /** Minimum deposit (ether-formatted stable asset amount). */ min: string; /** Maximum deposit (ether-formatted stable asset amount). */ max: string; /** Remaining tranche capacity (ether-formatted stable asset amount). */ availableCapacity: string; } export interface KycParams { contractAbi: any; contractAddress: string; functionName: string; args: BytesLike[]; userAddress: string; chainId: string; } export interface UserPositions { /** Per-pool breakdown. */ pools: PortfolioLendingPool[]; /** Aggregate summary (invested, yields, APY). */ summary: PortfolioSummary; } export type PlatformStats = LendingTotals; /** * A strategy's risk figures, from its CMS risk-management record * (`kasu.strategies.getRiskPerformance`). Each is `null` when unauthored or * not a finite number — render "—", never `0`. */ export interface StrategyRiskPerformance { /** Realised loss rate, a 0..1 fraction. */ poolLossRate: number | null; /** First-loss capital, exactly as the CMS record authors it. */ firstLossCapital: number | null; }