@liquidium/client 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/types.ts","../src/core/config.ts","../src/core/errors.ts","../src/core/transports/api-client.ts","../src/core/transports/canister-context.ts","../src/generated/canisters/lending/lending.did.js","../src/core/canisters/lending/actor.ts","../src/core/canisters/lending/error-mappers.ts","../src/core/evm.ts","../src/core/utils/time.ts","../src/core/utils/variant.ts","../src/core/wallet-actions.ts","../src/execute.ts","../src/core/utils/signature.ts","../src/modules/accounts/mappers.ts","../src/modules/accounts/accounts.ts","../src/core/canisters/instant-loans/actor.ts","../src/core/sdk-api-paths.ts","../src/core/utils/bigint.ts","../src/modules/instant-loans/ref-code.ts","../src/modules/activities/types.ts","../src/modules/activities/activities.ts","../src/core/rates.ts","../src/modules/history/types.ts","../src/modules/history/history.ts","../src/generated/canisters/ck-btc-minter/declaration.js","../src/core/canisters/ckbtc/minter.ts","../src/generated/canisters/deposit-accounts/deposit_accounts.did.js","../src/core/canisters/deposit-accounts/actor.ts","../src/core/utils/inflow-subaccount.ts","../src/modules/lending/types.ts","../src/modules/lending/_internal/supply-targets.ts","../src/modules/quote/types.ts","../src/modules/quote/quote.ts","../src/modules/instant-loans/instant-loans.ts","../src/modules/instant-loans/types.ts","../src/modules/lending/evm-transactions.ts","../src/core/canisters/lending/messages.ts","../src/core/utils/retry.ts","../src/modules/lending/mappers.ts","../src/modules/lending/lending.ts","../src/core/utils/asset-decimals.ts","../src/modules/market/mappers.ts","../src/modules/market/market.ts","../src/modules/positions/mappers.ts","../src/modules/positions/positions.ts","../src/client.ts"],"names":["OutflowType","idlFactory","Actor","subaccount","Principal","QuoteValidationErrorCode","QuoteWarningCode","RATE_SCALE","formatBpsAsPercent","encodeIcrcAccount","isAddress","getAddress"],"mappings":";;;;;;;;;AAwDO,IAAM,WAAA,GAAc;AAAA,EACzB,OAAA,EAAS;AACX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AAW;AAAA,MAChC,cAAc,MAAA,CAAO,aAAA,GACjB,EAAE,OAAA,EAAS,MAAA,CAAO,eAAc,GAChC;AAAA,KACL;AAAA,GACF,CAAA;AACH","file":"index.js","sourcesContent":["import type { Identity } from \"@dfinity/agent\";\nimport type { PublicClient } from \"viem\";\n\n/** Minimal viem-compatible client shape required for SDK EVM read calls. */\nexport type EvmReadClient = Pick<PublicClient, \"readContract\">;\n\n/**\n * Runtime options for `new LiquidiumClient(config)`.\n *\n * Canister-backed reads and SDK HTTP features work with `{}` defaults. Set\n * `apiBaseUrl` only when overriding the Liquidium production API root.\n */\nexport interface LiquidiumClientConfig {\n /** Preset canister IDs. Only `mainnet` is bundled. */\n environment?: Environment;\n /** ICP replica host override (defaults follow `@dfinity/agent`). */\n icHost?: string;\n /** Agent identity for signed canister calls. */\n identity?: Identity;\n /**\n * Base URL for the Liquidium SDK HTTP API root (e.g. `https://app.example.com/api/sdk`).\n * Defaults to the Liquidium production API root. Endpoint versions are owned\n * by this SDK package version.\n */\n apiBaseUrl?: string;\n /** Extra headers sent with every SDK API request. */\n headers?: Record<string, string>;\n /** Override individual canister principals for custom deployments. */\n canisterIds?: Partial<CanisterIds>;\n /** Custom `fetch` implementation for SDK API requests. */\n fetch?: typeof fetch;\n /** Per-request timeout for SDK API calls in milliseconds. */\n timeoutMs?: number;\n /** Ethereum RPC URL used for public ERC-20 reads in EVM supply flows. */\n evmRpcUrl?: string;\n /** Optional headers for RPC providers that authenticate via HTTP headers. */\n evmRpcHeaders?: Record<string, string>;\n /** Existing viem public client or compatible read client for EVM reads. */\n evmPublicClient?: EvmReadClient;\n}\n\n/** Principal text values for canisters used by the client. */\nexport interface CanisterIds {\n /** Liquidium lending canister principal. */\n lending: string;\n /** BTC pool canister principal. */\n btcPool: string;\n /** ERC-20 pool canister principal. */\n ercPool: string;\n /** ckETH minter deposit helper canister principal. */\n ethDeposit: string;\n /** Accountless instant-loans canister principal. */\n instantLoans: string;\n}\n\n/** Supported deployment environments with bundled canister ids. */\nexport const Environment = {\n mainnet: \"mainnet\",\n} as const;\n/** Supported deployment environment name. */\nexport type Environment = (typeof Environment)[keyof typeof Environment];\n\n/** Canonical asset symbols supported by state-mutating protocol flows. */\nexport const Asset = {\n BTC: \"BTC\",\n SOL: \"SOL\",\n USDC: \"USDC\",\n USDT: \"USDT\",\n} as const;\n/** Canonical asset symbol supported by state-mutating protocol flows. */\nexport type Asset = (typeof Asset)[keyof typeof Asset];\n\n/** Canonical chain identifiers used by wallet and protocol actions. */\nexport const Chain = {\n BTC: \"BTC\",\n ETH: \"ETH\",\n} as const;\n/** Canonical chain identifier used by wallet and protocol actions. */\nexport type Chain = (typeof Chain)[keyof typeof Chain];\n\n/** Asset symbol as returned by market-data APIs, including future assets. */\nexport type MarketAsset = string;\n/** Chain name as returned by market-data APIs, including future chains. */\nexport type MarketChain = string;\n\n/** Inflow operation performed by a supply target. */\nexport const SupplyAction = {\n deposit: \"deposit\",\n repayment: \"repayment\",\n} as const;\n/** Inflow operation performed by a supply target. */\nexport type SupplyAction = (typeof SupplyAction)[keyof typeof SupplyAction];\n\n/** Outflow operation reported by the lending canister. */\nexport const OutflowType = {\n borrow: \"borrow\",\n feeClaim: \"feeClaim\",\n withdraw: \"withdraw\",\n} as const;\n/** Outflow operation reported by the lending canister. */\nexport type OutflowType = (typeof OutflowType)[keyof typeof OutflowType];\n\n/** Inflow submit type expected by the SDK API. */\nexport const InflowSubmitType = {\n DEPOSIT: \"DEPOSIT\",\n REPAY: \"REPAY\",\n} as const;\n/** Inflow submit type expected by the SDK API. */\nexport type InflowSubmitType =\n (typeof InflowSubmitType)[keyof typeof InflowSubmitType];\n\n/** Wallet address and chain pair linked to a Liquidium profile. */\nexport interface Wallet {\n /** Chain where the wallet address is valid. */\n chain: Chain;\n /** Wallet address as stored by the protocol. */\n address: string;\n}\n","import { type CanisterIds, Environment } from \"./types\";\n\nconst MAINNET_HOST = \"https://icp-api.io\";\nexport const DEFAULT_API_BASE_URL = \"https://app.liquidium.fi/api/sdk\";\nexport const DEFAULT_ENVIRONMENT: Environment = Environment.mainnet;\n\nconst MAINNET_CANISTER_IDS: CanisterIds = {\n lending: \"hyk4r-jqaaa-aaaar-qb4ca-cai\",\n btcPool: \"hkmli-faaaa-aaaar-qb4ba-cai\",\n ercPool: \"hnnn4-iyaaa-aaaar-qb4bq-cai\",\n ethDeposit: \"z5jz7-nyaaa-aaaar-qb6pq-cai\",\n instantLoans: \"u5rm3-niaaa-aaaar-qb7eq-cai\",\n};\n\nconst CANISTER_IDS_BY_ENVIRONMENT: Record<Environment, CanisterIds> = {\n mainnet: MAINNET_CANISTER_IDS,\n};\n\nexport function resolveHost(override?: string): string {\n return override ?? MAINNET_HOST;\n}\n\n/** Resolves environment canister ids with optional per-canister overrides. */\nexport function resolveCanisterIds(\n environment: Environment = DEFAULT_ENVIRONMENT,\n overrides?: Partial<CanisterIds>\n): CanisterIds {\n return { ...CANISTER_IDS_BY_ENVIRONMENT[environment], ...overrides };\n}\n\nexport const DEFAULT_TIMEOUT_MS = 30_000;\n\n/** Mainnet chain-key Bitcoin and Ethereum helper canister principals. */\nexport const CK_CANISTER_IDS = {\n btcMinter: \"mqygn-kiaaa-aaaar-qaadq-cai\",\n btcLedger: \"mxzaz-hqaaa-aaaar-qaada-cai\",\n btcIndex: \"n5wcd-faaaa-aaaar-qaaea-cai\",\n btcArchive: \"nbsys-saaaa-aaaar-qaaga-cai\",\n ethMinter: \"sv3dd-oaaaa-aaaar-qacoa-cai\",\n ethLedger: \"ss2fx-dyaaa-aaaar-qacoq-cai\",\n ethArchive: \"yhujl-liaaa-aaaar-qaiha-cai\",\n ethUsdtLedger: \"cngnf-vqaaa-aaaar-qag4q-cai\",\n ethUsdtIndex: \"cefgz-dyaaa-aaaar-qag5a-cai\",\n} as const;\n","/**\n * Stable string codes for {@link LiquidiumError}. Use for branching in application code.\n */\nexport const LiquidiumErrorCode = {\n // Protocol errors\n INVALID_TARGET_PRINCIPAL: \"INVALID_TARGET_PRINCIPAL\",\n INSUFFICIENT_COLLATERAL: \"INSUFFICIENT_COLLATERAL\",\n SIGNATURE_EXPIRY_TOO_FAR_IN_FUTURE: \"SIGNATURE_EXPIRY_TOO_FAR_IN_FUTURE\",\n MAX_LTV_EXCEEDED: \"MAX_LTV_EXCEEDED\",\n SIGNATURE_EXPIRED: \"SIGNATURE_EXPIRED\",\n ACCOUNT_ALREADY_LINKED: \"ACCOUNT_ALREADY_LINKED\",\n ACCOUNT_NOT_FOUND: \"ACCOUNT_NOT_FOUND\",\n CANNOT_REMOVE_SOLE_ACCOUNT: \"CANNOT_REMOVE_SOLE_ACCOUNT\",\n PROFILE_NOT_FOUND: \"PROFILE_NOT_FOUND\",\n PROFILE_ALREADY_EXISTS: \"PROFILE_ALREADY_EXISTS\",\n SIGNATURE_ERROR: \"SIGNATURE_ERROR\",\n POOL_NOT_FOUND: \"POOL_NOT_FOUND\",\n POOL_FROZEN: \"POOL_FROZEN\",\n POSITION_NOT_FOUND: \"POSITION_NOT_FOUND\",\n BORROW_CAP_EXCEEDED: \"BORROW_CAP_EXCEEDED\",\n SUPPLY_CAP_EXCEEDED: \"SUPPLY_CAP_EXCEEDED\",\n INSUFFICIENT_FUNDS: \"INSUFFICIENT_FUNDS\",\n HEALTH_FACTOR_TOO_LOW: \"HEALTH_FACTOR_TOO_LOW\",\n TRANSFER_FAILED: \"TRANSFER_FAILED\",\n LIQUIDATION_NOT_FOUND: \"LIQUIDATION_NOT_FOUND\",\n BORROWING_DISABLED: \"BORROWING_DISABLED\",\n NO_LIQUIDITY: \"NO_LIQUIDITY\",\n NOT_ALLOWED: \"NOT_ALLOWED\",\n\n // Signature verification\n INVALID_ETH_SIGNATURE: \"INVALID_ETH_SIGNATURE\",\n INVALID_BTC_SIGNATURE: \"INVALID_BTC_SIGNATURE\",\n INVALID_ETH_ADDRESS: \"INVALID_ETH_ADDRESS\",\n UNSUPPORTED_CHAIN: \"UNSUPPORTED_CHAIN\",\n\n // Client-side\n WITHDRAW_TOO_LOW: \"WITHDRAW_TOO_LOW\",\n REPAYMENT_EXCEEDS_DEBT: \"REPAYMENT_EXCEEDS_DEBT\",\n INVALID_ADDRESS: \"INVALID_ADDRESS\",\n DEPOSIT_ADDRESS_ERROR: \"DEPOSIT_ADDRESS_ERROR\",\n\n // Transport\n NETWORK_ERROR: \"NETWORK_ERROR\",\n SERVICE_UNAVAILABLE: \"SERVICE_UNAVAILABLE\",\n REQUEST_TIMEOUT: \"REQUEST_TIMEOUT\",\n CANISTER_REJECTED: \"CANISTER_REJECTED\",\n\n // Catch-all\n INTERNAL: \"INTERNAL\",\n VALIDATION_ERROR: \"VALIDATION_ERROR\",\n} as const;\n\nexport type LiquidiumErrorCode =\n (typeof LiquidiumErrorCode)[keyof typeof LiquidiumErrorCode];\n\n/** Optional debug identifiers attached to mapped SDK errors. */\nexport interface LiquidiumErrorContext {\n /** Backend trace id for support/debugging when available. */\n traceId?: string;\n /** SDK API request id for support/debugging when available. */\n requestId?: string;\n}\n\n/**\n * Typed error from the SDK or mapped protocol failures.\n *\n * Prefer checking `code` over parsing `message`.\n */\nexport class LiquidiumError extends Error {\n /** Machine-readable reason; compare to {@link LiquidiumErrorCode} values. */\n readonly code: LiquidiumErrorCode;\n /** Original error when the SDK wraps an underlying failure. */\n override readonly cause?: unknown;\n /** Backend trace id for support/debugging when available. */\n readonly traceId?: string;\n /** SDK API request id for support/debugging when available. */\n readonly requestId?: string;\n\n /**\n * @param code - Error code from {@link LiquidiumErrorCode}.\n * @param message - Human-readable detail (defaults to `code` when omitted).\n * @param cause - Optional underlying error.\n * @param context - Optional backend debug identifiers.\n */\n constructor(\n code: LiquidiumErrorCode,\n message?: string,\n cause?: unknown,\n context?: LiquidiumErrorContext\n ) {\n super(message ?? code);\n this.name = \"LiquidiumError\";\n this.code = code;\n this.cause = cause;\n this.traceId = context?.traceId;\n this.requestId = context?.requestId;\n }\n}\n","import { LiquidiumError, LiquidiumErrorCode } from \"../errors\";\n\nconst DOM_EXCEPTION_ABORT_ERROR_NAME = \"AbortError\";\nconst HTTP_HEADER_CONTENT_TYPE = \"content-type\";\nconst HTTP_HEADER_REQUEST_ID = \"x-request-id\";\nconst HTTP_HEADER_TRACE_ID = \"x-trace-id\";\nconst HTTP_METHOD_GET = \"GET\";\nconst HTTP_METHOD_POST = \"POST\";\nconst MIME_TYPE_APPLICATION_JSON = \"application/json\";\n\nexport interface ApiClient {\n get<T>(path: string): Promise<T>;\n post<TResponse, TBody>(path: string, body: TBody): Promise<TResponse>;\n}\n\nexport function createApiClient(opts: {\n baseUrl: string;\n headers?: Record<string, string>;\n timeoutMs: number;\n fetchFn?: typeof fetch;\n}): ApiClient {\n const normalizedOpts = {\n ...opts,\n baseUrl: normalizeBaseUrl(opts.baseUrl),\n };\n\n return {\n async get<T>(path: string): Promise<T> {\n return await sendRequest<T>(normalizedOpts, {\n path,\n method: HTTP_METHOD_GET,\n });\n },\n async post<TResponse, TBody>(\n path: string,\n body: TBody\n ): Promise<TResponse> {\n return await sendRequest<TResponse>(normalizedOpts, {\n path,\n method: HTTP_METHOD_POST,\n body,\n });\n },\n };\n}\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n return baseUrl.replace(/\\/+$/, \"\");\n}\n\nasync function sendRequest<TResponse>(\n opts: {\n baseUrl: string;\n fetchFn?: typeof fetch;\n headers?: Record<string, string>;\n timeoutMs: number;\n },\n request: {\n path: string;\n method: typeof HTTP_METHOD_GET | typeof HTTP_METHOD_POST;\n body?: unknown;\n }\n): Promise<TResponse> {\n const url = `${opts.baseUrl}${request.path}`;\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), opts.timeoutMs);\n const fetchFn = opts.fetchFn ?? fetch;\n const requestHeaders = {\n ...opts.headers,\n ...(request.method === HTTP_METHOD_POST\n ? {\n [HTTP_HEADER_CONTENT_TYPE]: MIME_TYPE_APPLICATION_JSON,\n }\n : {}),\n };\n\n try {\n const response = await fetchFn(url, {\n method: request.method,\n headers:\n Object.keys(requestHeaders).length > 0 ? requestHeaders : undefined,\n body:\n request.method === HTTP_METHOD_POST\n ? JSON.stringify(request.body)\n : undefined,\n signal: controller.signal,\n });\n\n if (!response.ok) {\n const payload = await tryParseJson(response);\n const errorContext = getResponseErrorContext(response);\n const message =\n getErrorMessage(payload) ??\n `API request failed: ${response.status} ${response.statusText}`;\n\n throw new LiquidiumError(\n LiquidiumErrorCode.SERVICE_UNAVAILABLE,\n appendErrorContext(message, errorContext),\n undefined,\n errorContext\n );\n }\n\n return (await response.json()) as TResponse;\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n if (\n error instanceof DOMException &&\n error.name === DOM_EXCEPTION_ABORT_ERROR_NAME\n ) {\n throw new LiquidiumError(\n LiquidiumErrorCode.REQUEST_TIMEOUT,\n `Request to ${request.path} timed out after ${opts.timeoutMs}ms`\n );\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.NETWORK_ERROR,\n `Failed to reach API: ${String(error)}`,\n error\n );\n } finally {\n clearTimeout(timeout);\n }\n}\n\nasync function tryParseJson(response: Response): Promise<unknown> {\n try {\n return await response.json();\n } catch {\n return null;\n }\n}\n\nfunction getErrorMessage(payload: unknown): string | null {\n if (!payload || typeof payload !== \"object\") {\n return null;\n }\n\n const message = (payload as { message?: unknown }).message;\n return typeof message === \"string\" && message.length > 0 ? message : null;\n}\n\nfunction getResponseErrorContext(response: Response): {\n traceId?: string;\n requestId?: string;\n} {\n return {\n traceId: response.headers.get(HTTP_HEADER_TRACE_ID) ?? undefined,\n requestId: response.headers.get(HTTP_HEADER_REQUEST_ID) ?? undefined,\n };\n}\n\nfunction appendErrorContext(\n message: string,\n context: { traceId?: string; requestId?: string }\n): string {\n if (!context.traceId && !context.requestId) {\n return message;\n }\n\n const details = [\n context.traceId ? `traceId=${context.traceId}` : undefined,\n context.requestId ? `requestId=${context.requestId}` : undefined,\n ].filter((value): value is string => Boolean(value));\n\n return `${message} (${details.join(\", \")})`;\n}\n","import type { Identity } from \"@dfinity/agent\";\nimport { HttpAgent } from \"@dfinity/agent\";\nimport { resolveHost } from \"../config\";\nimport type { CanisterIds } from \"../types\";\n\nexport interface CanisterContext {\n agent: HttpAgent;\n canisterIds: CanisterIds;\n}\n\nexport function createCanisterContext(opts: {\n icHost?: string;\n identity?: Identity;\n canisterIds: CanisterIds;\n}): CanisterContext {\n const host = resolveHost(opts.icHost);\n\n const agent = HttpAgent.createSync({\n host,\n identity: opts.identity,\n });\n\n return {\n agent,\n canisterIds: opts.canisterIds,\n };\n}\n","export const idlFactory = ({ IDL }) => {\n const Chains = IDL.Variant({\n 'BTC' : IDL.Null,\n 'ETH' : IDL.Null,\n 'SOL' : IDL.Null,\n });\n const WalletType = IDL.Variant({ 'Wallet' : Chains });\n const SignatureInfo = IDL.Record({\n 'signature' : IDL.Text,\n 'chain' : Chains,\n 'account' : IDL.Text,\n });\n const SignatureScheme = IDL.Variant({ 'Wallet' : SignatureInfo });\n const AddAccountRequest = IDL.Record({\n 'target_principal' : IDL.Principal,\n 'chain' : WalletType,\n 'wallet_signature' : SignatureScheme,\n 'expiry_timestamp' : IDL.Nat64,\n });\n const SignedRequest = IDL.Record({\n 'data' : AddAccountRequest,\n 'signature_info' : SignatureScheme,\n });\n const SignatureVerificationError = IDL.Variant({\n 'InvalidEthSignature' : IDL.Null,\n 'UnsupportedChain' : IDL.Null,\n 'InvalidSolSignature' : IDL.Null,\n 'InvalidEthAddress' : IDL.Null,\n 'CouldNotDecode' : IDL.Text,\n 'ProfileNotFound' : IDL.Null,\n 'InvalidBtcSignature' : IDL.Null,\n });\n const ProtocolError = IDL.Variant({\n 'PositionNotFound' : IDL.Null,\n 'Internal' : IDL.Text,\n 'InvalidAddress' : IDL.Text,\n 'InvalidTargetPrincipal' : IDL.Null,\n 'SignatureError' : SignatureVerificationError,\n 'SupplyCapExceeded' : IDL.Null,\n 'AccountNotFound' : IDL.Null,\n 'NotAllowed' : IDL.Text,\n 'PoolNotFound' : IDL.Text,\n 'FeeClaimReceiverNotConfigured' : IDL.Null,\n 'InsufficientCollateral' : IDL.Null,\n 'ProfileNotFound' : IDL.Null,\n 'SignatureExpiryTooFarInFuture' : IDL.Null,\n 'MaxLtvExceeded' : IDL.Null,\n 'ProfileAlreadyExists' : IDL.Null,\n 'LiquidationNotFound' : IDL.Text,\n 'HealthFactorTooLow' : IDL.Null,\n 'NoLiquidity' : IDL.Null,\n 'SignatureExpired' : IDL.Null,\n 'BorrowingDisabled' : IDL.Null,\n 'BorrowCapExceeded' : IDL.Null,\n 'PoolFrozen' : IDL.Null,\n 'TransferFailed' : IDL.Text,\n 'AccountAlreadyLinked' : IDL.Null,\n 'CannotRemoveSoleAccount' : IDL.Null,\n 'InsufficientFunds' : IDL.Null,\n });\n const Result = IDL.Variant({ 'Ok' : IDL.Null, 'Err' : ProtocolError });\n const AccountType = IDL.Variant({\n 'Native' : IDL.Principal,\n 'External' : IDL.Text,\n });\n const BorrowAssetRequest = IDL.Record({\n 'expiry_timestamp' : IDL.Nat64,\n 'account' : AccountType,\n 'pool_id' : IDL.Principal,\n 'amount' : IDL.Nat,\n });\n const SignedRequest_1 = IDL.Record({\n 'data' : BorrowAssetRequest,\n 'signature_info' : SignatureScheme,\n });\n const OutflowType = IDL.Variant({\n 'Withdraw' : IDL.Null,\n 'FeeClaim' : IDL.Null,\n 'Borrow' : IDL.Null,\n });\n const OutflowDetails = IDL.Record({\n 'id' : IDL.Text,\n 'txid' : IDL.Opt(IDL.Text),\n 'outflow_type' : OutflowType,\n 'outflow_ref' : IDL.Opt(IDL.Text),\n 'amount' : IDL.Nat,\n 'receiver' : AccountType,\n });\n const Result_1 = IDL.Variant({\n 'Ok' : OutflowDetails,\n 'Err' : ProtocolError,\n });\n const ClaimFeeRequest = IDL.Record({ 'pool_id' : IDL.Principal });\n const AssetType = IDL.Variant({\n 'CkAsset' : IDL.Principal,\n 'Unknown' : IDL.Null,\n });\n const Assets = IDL.Variant({\n 'BTC' : IDL.Null,\n 'SOL' : IDL.Null,\n 'USDC' : IDL.Null,\n 'USDT' : IDL.Null,\n });\n const LiquidatablePosition = IDL.Record({\n 'collateral_amount' : IDL.Nat,\n 'asset_type' : AssetType,\n 'debt_amount' : IDL.Nat,\n 'asset' : Assets,\n 'account' : IDL.Principal,\n 'pool_id' : IDL.Principal,\n 'protocol_fee' : IDL.Nat64,\n 'liquidation_bonus' : IDL.Nat64,\n 'liquidation_threshold' : IDL.Nat64,\n });\n const LiquidatableUser = IDL.Record({\n 'health_factor' : IDL.Nat,\n 'total_debt' : IDL.Nat,\n 'account' : IDL.Principal,\n 'positions' : IDL.Vec(LiquidatablePosition),\n 'weighted_liquidation_threshold' : IDL.Nat,\n });\n const RepaymentDetails = IDL.Record({\n 'id' : IDL.Text,\n 'txid' : IDL.Text,\n 'account' : IDL.Principal,\n 'timestamp' : IDL.Nat64,\n 'amount' : IDL.Nat,\n });\n const Wallet = IDL.Record({ 'chain' : WalletType, 'address' : IDL.Text });\n const ProfileCreatedEvent = IDL.Record({\n 'wallet' : Wallet,\n 'profile' : IDL.Principal,\n });\n const InflowType = IDL.Variant({\n 'Repayment' : IDL.Null,\n 'Deposit' : IDL.Null,\n });\n const InflowDetails = IDL.Record({\n 'id' : IDL.Text,\n 'inflow_type' : InflowType,\n 'txid' : IDL.Text,\n 'timestamp' : IDL.Nat64,\n 'amount' : IDL.Nat,\n 'receiver' : IDL.Principal,\n });\n const LiqTxTarget = IDL.Variant({\n 'Collateral' : IDL.Null,\n 'Change' : IDL.Null,\n });\n const Pool = IDL.Record({\n 'optimal_utilization_rate' : IDL.Nat,\n 'principal' : IDL.Principal,\n 'total_generated_interest_snapshot' : IDL.Nat,\n 'asset_type' : AssetType,\n 'supply_cap' : IDL.Opt(IDL.Nat),\n 'same_asset_borrowing' : IDL.Opt(IDL.Bool),\n 'asset' : Assets,\n 'rate_slope_before' : IDL.Nat,\n 'borrow_cap' : IDL.Opt(IDL.Nat),\n 'total_debt_at_last_sync' : IDL.Nat,\n 'supply_at_last_sync' : IDL.Nat,\n 'chain' : Chains,\n 'rate_slope_after' : IDL.Nat,\n 'reserve_factor' : IDL.Nat64,\n 'last_updated' : IDL.Opt(IDL.Nat64),\n 'lending_index' : IDL.Nat,\n 'protocol_liquidation_fee' : IDL.Nat64,\n 'treasury_supply_scaled' : IDL.Nat,\n 'same_asset_borrowing_dust_threshold' : IDL.Nat,\n 'borrow_index' : IDL.Nat,\n 'base_rate' : IDL.Nat,\n 'frozen' : IDL.Bool,\n 'liquidation_bonus' : IDL.Nat64,\n 'liquidation_threshold' : IDL.Nat64,\n 'max_ltv' : IDL.Nat64,\n 'repay_grace_period' : IDL.Opt(IDL.Nat64),\n 'pending_service_fees' : IDL.Nat,\n 'total_supply_at_last_sync' : IDL.Nat,\n });\n const LiquidationStatus = IDL.Variant({\n 'CollateralTransferFailed' : IDL.Text,\n 'FailedLiquidation' : IDL.Text,\n 'InflowProcessed' : IDL.Null,\n 'Success' : IDL.Null,\n 'CoreExecuted' : IDL.Null,\n 'ChangeTransferFailed' : IDL.Text,\n 'Pending' : IDL.Null,\n });\n const TransferStatus = IDL.Variant({\n 'Failed' : IDL.Text,\n 'Success' : IDL.Null,\n 'Pending' : IDL.Null,\n });\n const TxStatus = IDL.Record({\n 'status' : TransferStatus,\n 'tx_id' : IDL.Opt(IDL.Text),\n });\n const LiquidationAmounts = IDL.Record({\n 'debt_repaid' : IDL.Nat,\n 'collateral_received' : IDL.Nat,\n });\n const LiquidationResult = IDL.Record({\n 'id' : IDL.Nat,\n 'status' : LiquidationStatus,\n 'change_tx' : TxStatus,\n 'debt_asset' : AssetType,\n 'amounts' : LiquidationAmounts,\n 'collateral_asset' : AssetType,\n 'timestamp' : IDL.Nat64,\n 'collateral_tx' : TxStatus,\n });\n const LiquidationRequest = IDL.Record({\n 'debt_amount' : IDL.Nat,\n 'receiver_address' : IDL.Principal,\n 'collateral_pool_id' : IDL.Principal,\n 'borrower' : IDL.Principal,\n 'debt_pool_id' : IDL.Principal,\n 'buy_bad_debt' : IDL.Bool,\n });\n const ProtocolEventType = IDL.Variant({\n 'RepaymentRejected' : IDL.Record({\n 'pool' : IDL.Principal,\n 'error' : ProtocolError,\n 'details' : RepaymentDetails,\n }),\n 'AccountCreated' : ProfileCreatedEvent,\n 'DepositConfirmed' : IDL.Record({\n 'pool' : IDL.Principal,\n 'details' : InflowDetails,\n }),\n 'DepositRejected' : IDL.Record({\n 'pool' : IDL.Principal,\n 'error' : ProtocolError,\n 'details' : InflowDetails,\n }),\n 'AccountAdded' : Wallet,\n 'BorrowStateUpdated' : IDL.Bool,\n 'LiquidationUnderlyingWithdrawal' : IDL.Record({\n 'txid' : IDL.Text,\n 'target' : LiqTxTarget,\n 'liquidation_id' : IDL.Nat,\n 'account' : IDL.Text,\n 'pool_id' : IDL.Text,\n 'amount' : IDL.Nat,\n }),\n 'PoolUpdated' : Pool,\n 'RepaymentConfirmed' : IDL.Record({\n 'pool' : IDL.Principal,\n 'details' : RepaymentDetails,\n }),\n 'LiquidationExecuted' : IDL.Record({\n 'result' : LiquidationResult,\n 'request' : LiquidationRequest,\n }),\n 'WithdrawalConfirmed' : IDL.Record({\n 'pool' : IDL.Principal,\n 'details' : OutflowDetails,\n }),\n 'BorrowConfirmed' : IDL.Record({\n 'pool' : IDL.Principal,\n 'details' : OutflowDetails,\n }),\n 'PoolRegistered' : Pool,\n 'AccountRemoved' : Wallet,\n 'PoolRemoved' : IDL.Principal,\n });\n const ProtocolEvent = IDL.Record({\n 'id' : IDL.Nat,\n 'user' : IDL.Principal,\n 'timestamp' : IDL.Nat64,\n 'event_type' : ProtocolEventType,\n });\n const BorrowingPower = IDL.Record({\n 'max_borrowable_usd' : IDL.Nat,\n 'weighted_max_ltv' : IDL.Nat,\n });\n const Position = IDL.Record({\n 'asset' : Assets,\n 'total_debt_interest' : IDL.Nat,\n 'borrow_index_snapshot' : IDL.Nat,\n 'lending_index_snapshot' : IDL.Nat,\n 'debt_scaled' : IDL.Nat,\n 'total_earned_interest' : IDL.Nat,\n 'deposit_scaled' : IDL.Nat,\n 'pool_id' : IDL.Principal,\n 'unpaid_debt_interest' : IDL.Nat,\n 'last_update' : IDL.Nat64,\n 'user_profile' : IDL.Principal,\n });\n const UserStats = IDL.Record({\n 'debt' : IDL.Nat,\n 'collateral' : IDL.Nat,\n 'acumulated_interest' : IDL.Nat,\n 'borrowing_power' : BorrowingPower,\n 'positions' : IDL.Vec(Position),\n 'weighted_liquidation_threshold' : IDL.Nat,\n });\n const Result_2 = IDL.Variant({\n 'Ok' : LiquidationResult,\n 'Err' : ProtocolError,\n });\n const PositionView = IDL.Record({\n 'lending_index_now' : IDL.Nat,\n 'interest_since_snapshot' : IDL.Nat,\n 'asset' : Assets,\n 'total_debt_interest' : IDL.Nat,\n 'borrow_index_snapshot' : IDL.Nat,\n 'debt_native_now' : IDL.Nat,\n 'borrow_index_now' : IDL.Nat,\n 'lending_index_snapshot' : IDL.Nat,\n 'debt_scaled' : IDL.Nat,\n 'total_earned_interest' : IDL.Nat,\n 'deposit_scaled' : IDL.Nat,\n 'earned_since_snapshot' : IDL.Nat,\n 'deposited_native_now' : IDL.Nat,\n 'pool_id' : IDL.Principal,\n 'last_update' : IDL.Nat64,\n 'user_profile' : IDL.Principal,\n });\n const Result_3 = IDL.Variant({\n 'Ok' : IDL.Tuple(IDL.Nat, IDL.Nat32),\n 'Err' : IDL.Text,\n });\n const ListPositionsResponse = IDL.Record({\n 'total' : IDL.Nat64,\n 'next_cursor' : IDL.Opt(IDL.Tuple(IDL.Principal, IDL.Principal)),\n 'positions' : IDL.Vec(PositionView),\n });\n const ListProfilesResponse = IDL.Record({\n 'total' : IDL.Nat64,\n 'next_cursor' : IDL.Opt(IDL.Principal),\n 'profiles' : IDL.Vec(\n IDL.Tuple(IDL.Principal, IDL.Tuple(IDL.Nat, UserStats))\n ),\n });\n const PoolEvents = IDL.Variant({\n 'DepositConfirmed' : InflowDetails,\n 'RepaymentConfirmed' : RepaymentDetails,\n });\n const Result_4 = IDL.Variant({\n 'Ok' : IDL.Opt(IDL.Nat),\n 'Err' : ProtocolError,\n });\n const InitializeAccountRequest = IDL.Record({\n 'expiry_timestamp' : IDL.Nat64,\n });\n const SignedRequest_2 = IDL.Record({\n 'data' : InitializeAccountRequest,\n 'signature_info' : SignatureScheme,\n });\n const Result_5 = IDL.Variant({ 'Ok' : IDL.Principal, 'Err' : ProtocolError });\n const Result_6 = IDL.Variant({ 'Ok' : IDL.Null, 'Err' : IDL.Text });\n const RemoveAccountRequest = IDL.Record({\n 'wallet_address' : IDL.Text,\n 'expiry_timestamp' : IDL.Nat64,\n });\n const SignedRequest_3 = IDL.Record({\n 'data' : RemoveAccountRequest,\n 'signature_info' : SignatureScheme,\n });\n const ScanResult = IDL.Record({\n 'scanned' : IDL.Nat64,\n 'users' : IDL.Vec(LiquidatableUser),\n 'next_cursor' : IDL.Opt(IDL.Principal),\n });\n const Result_7 = IDL.Variant({ 'Ok' : IDL.Null, 'Err' : IDL.Text });\n const WithdrawRequest = IDL.Record({\n 'expiry_timestamp' : IDL.Nat64,\n 'account' : AccountType,\n 'pool_id' : IDL.Principal,\n 'amount' : IDL.Nat,\n });\n const SignedRequest_4 = IDL.Record({\n 'data' : WithdrawRequest,\n 'signature_info' : SignatureScheme,\n });\n const Result_8 = IDL.Variant({ 'Ok' : IDL.Nat, 'Err' : ProtocolError });\n return IDL.Service({\n 'add_admin' : IDL.Func([IDL.Principal], [], []),\n 'add_liquidator' : IDL.Func([IDL.Principal], [], []),\n 'add_wallet' : IDL.Func([IDL.Principal, SignedRequest], [Result], []),\n 'borrow_assets' : IDL.Func(\n [IDL.Principal, SignedRequest_1],\n [Result_1],\n [],\n ),\n 'claim_fee' : IDL.Func([ClaimFeeRequest], [Result_1], []),\n 'disable_borrowing' : IDL.Func([], [], []),\n 'disable_same_asset_borrowing' : IDL.Func([IDL.Principal], [], []),\n 'enable_borrowing' : IDL.Func([], [], []),\n 'enable_same_asset_borrowing' : IDL.Func([IDL.Principal], [], []),\n 'freeze_pool' : IDL.Func([IDL.Principal], [], []),\n 'get_admins' : IDL.Func([], [IDL.Vec(IDL.Principal)], ['query']),\n 'get_at_risk_positions' : IDL.Func(\n [IDL.Nat64, IDL.Nat64],\n [IDL.Vec(LiquidatableUser)],\n ['query'],\n ),\n 'get_borrowing_disabled' : IDL.Func([], [IDL.Bool], ['query']),\n 'get_event' : IDL.Func([IDL.Nat], [IDL.Opt(ProtocolEvent)], ['query']),\n 'get_health_factor' : IDL.Func(\n [IDL.Principal],\n [IDL.Nat, UserStats],\n ['query'],\n ),\n 'get_liquidation' : IDL.Func([IDL.Nat], [Result_2], ['query']),\n 'get_liquidators' : IDL.Func([], [IDL.Vec(IDL.Principal)], ['query']),\n 'get_nonce' : IDL.Func([IDL.Text], [IDL.Nat], ['query']),\n 'get_pool' : IDL.Func([IDL.Principal], [IDL.Opt(Pool)], ['query']),\n 'get_pool_rate' : IDL.Func(\n [IDL.Principal],\n [IDL.Opt(IDL.Tuple(IDL.Nat, IDL.Nat, IDL.Nat))],\n ['query'],\n ),\n 'get_position' : IDL.Func(\n [IDL.Principal, IDL.Principal],\n [IDL.Opt(PositionView)],\n ['query'],\n ),\n 'get_price' : IDL.Func([IDL.Text, IDL.Text], [Result_3], ['query']),\n 'get_prices' : IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Nat, IDL.Nat32))],\n ['query'],\n ),\n 'get_profile_stats' : IDL.Func([IDL.Principal], [UserStats], ['query']),\n 'get_profile_wallets' : IDL.Func(\n [IDL.Principal],\n [IDL.Vec(Wallet)],\n ['query'],\n ),\n 'get_protocol_fee_claim_receiver' : IDL.Func(\n [],\n [IDL.Opt(IDL.Principal)],\n ['query'],\n ),\n 'get_wallet_profile' : IDL.Func(\n [IDL.Text],\n [IDL.Opt(IDL.Principal)],\n ['query'],\n ),\n 'liquidate' : IDL.Func([LiquidationRequest], [Result_2], []),\n 'list_events' : IDL.Func(\n [IDL.Nat, IDL.Nat64],\n [IDL.Vec(IDL.Tuple(IDL.Nat, ProtocolEvent))],\n ['query'],\n ),\n 'list_pools' : IDL.Func([], [IDL.Vec(Pool)], ['query']),\n 'list_positions' : IDL.Func(\n [IDL.Opt(IDL.Tuple(IDL.Principal, IDL.Principal)), IDL.Nat64],\n [ListPositionsResponse],\n ['query'],\n ),\n 'list_profiles' : IDL.Func(\n [IDL.Opt(IDL.Principal), IDL.Nat64],\n [ListProfilesResponse],\n ['query'],\n ),\n 'notify_fee_claim_rollback' : IDL.Func([IDL.Nat], [], []),\n 'notify_pool_events' : IDL.Func(\n [IDL.Vec(PoolEvents)],\n [IDL.Vec(Result)],\n [],\n ),\n 'refresh_pool_transfer_fee' : IDL.Func([IDL.Principal], [Result_4], []),\n 'refund_stuck_liquidation' : IDL.Func([IDL.Nat], [Result_2], []),\n 'register_pool' : IDL.Func([Pool], [], []),\n 'register_profile' : IDL.Func([SignedRequest_2], [Result_5], []),\n 'remove_admin' : IDL.Func([IDL.Principal], [], []),\n 'remove_liquidator' : IDL.Func([IDL.Principal], [], []),\n 'remove_pool' : IDL.Func([IDL.Principal], [Result_6], []),\n 'remove_wallet' : IDL.Func([IDL.Principal, SignedRequest_3], [Result], []),\n 'scan_at_risk_positions' : IDL.Func(\n [IDL.Opt(IDL.Principal), IDL.Nat64, IDL.Nat64],\n [ScanResult],\n ['query'],\n ),\n 'set_base_rate' : IDL.Func([IDL.Principal, IDL.Nat], [], []),\n 'set_optimal_utilization_rate' : IDL.Func([IDL.Principal, IDL.Nat], [], []),\n 'set_pool_borrow_cap' : IDL.Func([IDL.Principal, IDL.Opt(IDL.Nat)], [], []),\n 'set_pool_liquidation_bonus' : IDL.Func([IDL.Principal, IDL.Nat64], [], []),\n 'set_pool_liquidation_threshold' : IDL.Func(\n [IDL.Principal, IDL.Nat64],\n [],\n [],\n ),\n 'set_pool_max_ltv' : IDL.Func([IDL.Principal, IDL.Nat64], [], []),\n 'set_pool_protocol_liquidation_fee' : IDL.Func(\n [IDL.Principal, IDL.Nat64],\n [],\n [],\n ),\n 'set_pool_reserve_factor' : IDL.Func([IDL.Principal, IDL.Nat64], [], []),\n 'set_pool_supply_cap' : IDL.Func([IDL.Principal, IDL.Opt(IDL.Nat)], [], []),\n 'set_protocol_fee_claim_receiver' : IDL.Func(\n [IDL.Principal],\n [Result_7],\n [],\n ),\n 'set_rate_slope_after' : IDL.Func([IDL.Principal, IDL.Nat], [], []),\n 'set_rate_slope_before' : IDL.Func([IDL.Principal, IDL.Nat], [], []),\n 'set_same_asset_borrow_dust_threshold' : IDL.Func(\n [IDL.Principal, IDL.Nat],\n [],\n [],\n ),\n 'unfreeze_pool' : IDL.Func([IDL.Principal], [], []),\n 'withdraw' : IDL.Func([IDL.Principal, SignedRequest_4], [Result_1], []),\n 'withdraw_stuck_pool_funds' : IDL.Func(\n [IDL.Principal, SignedRequest_4],\n [Result_8],\n [],\n ),\n });\n};\nexport const init = ({ IDL }) => { return [IDL.Opt(IDL.Text)]; };\n","import { Actor } from \"@dfinity/agent\";\nimport type {\n _SERVICE,\n AccountType,\n Assets,\n BorrowAssetRequest,\n BorrowingPower,\n Chains,\n ProtocolError as GeneratedProtocolError,\n SignatureVerificationError as GeneratedSignatureVerificationError,\n OutflowDetails,\n OutflowType,\n Pool,\n Result_1,\n Result_5,\n SignatureInfo,\n SignedRequest_1,\n SignedRequest_2,\n SignedRequest_4,\n UserStats,\n Wallet,\n WalletType,\n WithdrawRequest,\n} from \"../../../generated/canisters/lending/lending.did\";\nimport { idlFactory } from \"../../../generated/canisters/lending/lending.did.js\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { CanisterContext } from \"../../transports/canister-context\";\n\nexport type AssetVariant = Assets;\nexport type ChainVariant = Chains;\nexport type WalletChainVariant = WalletType;\nexport type WalletRecord = Wallet;\nexport type SignatureInfoVariant = SignatureInfo;\nexport type AccountTypeVariant = AccountType;\nexport type OutflowTypeVariant = OutflowType;\nexport type BorrowAssetsRequest = BorrowAssetRequest;\nexport type WithdrawAssetsRequest = WithdrawRequest;\nexport type SignedBorrowAssetsRequest = SignedRequest_1;\nexport type SignedWithdrawAssetsRequest = SignedRequest_4;\nexport type OutflowDetailsRecord = OutflowDetails;\nexport type BorrowAssetsResult = Result_1;\nexport type WithdrawAssetsResult = Result_1;\nexport type BorrowingPowerRecord = BorrowingPower;\nexport type UserStatsRecord = UserStats;\nexport type RegisterProfileRequest = SignedRequest_2;\nexport type RegisterProfileResult = Result_5;\nexport type LendingPoolRecord = Pool;\nexport type PoolRateTuple = [bigint, bigint, bigint];\nexport type PriceRecord = [string, bigint, number];\nexport type ProtocolError = GeneratedProtocolError;\nexport type SignatureVerificationError = GeneratedSignatureVerificationError;\nexport type LendingActor = _SERVICE;\n\nexport function createLendingActor(\n canisterContext: CanisterContext\n): LendingActor {\n const canisterId = canisterContext.canisterIds.lending;\n\n if (!canisterId) {\n throw new LiquidiumError(\n LiquidiumErrorCode.SERVICE_UNAVAILABLE,\n \"Lending canister ID is not configured\"\n );\n }\n\n return Actor.createActor<LendingActor>(idlFactory, {\n agent: canisterContext.agent,\n canisterId,\n });\n}\n","import { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { ProtocolError, SignatureVerificationError } from \"./actor\";\n\ntype VariantKey<T> = keyof UnionToIntersection<T> & string;\n\ntype UnionToIntersection<T> = (\n T extends unknown\n ? (value: T) => void\n : never\n) extends (value: infer Intersection) => void\n ? Intersection\n : never;\n\ntype ErrorMapping = {\n code: LiquidiumErrorCode;\n fallbackMessage?: string;\n};\n\nconst LENDING_CANISTER_PROTOCOL_RESULT_ERROR_MAP = {\n InvalidTargetPrincipal: { code: LiquidiumErrorCode.INVALID_TARGET_PRINCIPAL },\n InsufficientCollateral: { code: LiquidiumErrorCode.INSUFFICIENT_COLLATERAL },\n SignatureExpiryTooFarInFuture: {\n code: LiquidiumErrorCode.SIGNATURE_EXPIRY_TOO_FAR_IN_FUTURE,\n },\n MaxLtvExceeded: { code: LiquidiumErrorCode.MAX_LTV_EXCEEDED },\n SignatureExpired: { code: LiquidiumErrorCode.SIGNATURE_EXPIRED },\n AccountAlreadyLinked: { code: LiquidiumErrorCode.ACCOUNT_ALREADY_LINKED },\n AccountNotFound: { code: LiquidiumErrorCode.ACCOUNT_NOT_FOUND },\n CannotRemoveSoleAccount: {\n code: LiquidiumErrorCode.CANNOT_REMOVE_SOLE_ACCOUNT,\n },\n ProfileNotFound: { code: LiquidiumErrorCode.PROFILE_NOT_FOUND },\n ProfileAlreadyExists: { code: LiquidiumErrorCode.PROFILE_ALREADY_EXISTS },\n SignatureError: { code: LiquidiumErrorCode.SIGNATURE_ERROR },\n PoolNotFound: {\n code: LiquidiumErrorCode.POOL_NOT_FOUND,\n fallbackMessage: \"Pool not found\",\n },\n PoolFrozen: { code: LiquidiumErrorCode.POOL_FROZEN },\n PositionNotFound: { code: LiquidiumErrorCode.POSITION_NOT_FOUND },\n BorrowCapExceeded: { code: LiquidiumErrorCode.BORROW_CAP_EXCEEDED },\n SupplyCapExceeded: { code: LiquidiumErrorCode.SUPPLY_CAP_EXCEEDED },\n InsufficientFunds: { code: LiquidiumErrorCode.INSUFFICIENT_FUNDS },\n HealthFactorTooLow: { code: LiquidiumErrorCode.HEALTH_FACTOR_TOO_LOW },\n TransferFailed: {\n code: LiquidiumErrorCode.TRANSFER_FAILED,\n fallbackMessage: \"Transfer failed\",\n },\n LiquidationNotFound: {\n code: LiquidiumErrorCode.LIQUIDATION_NOT_FOUND,\n fallbackMessage: \"Liquidation not found\",\n },\n BorrowingDisabled: { code: LiquidiumErrorCode.BORROWING_DISABLED },\n NoLiquidity: { code: LiquidiumErrorCode.NO_LIQUIDITY },\n NotAllowed: {\n code: LiquidiumErrorCode.NOT_ALLOWED,\n fallbackMessage: \"Operation not allowed\",\n },\n InvalidAddress: {\n code: LiquidiumErrorCode.INVALID_ADDRESS,\n fallbackMessage: \"Invalid address\",\n },\n Internal: {\n code: LiquidiumErrorCode.INTERNAL,\n fallbackMessage: \"Internal protocol error\",\n },\n FeeClaimReceiverNotConfigured: {\n code: LiquidiumErrorCode.INTERNAL,\n fallbackMessage: \"Fee claim receiver is not configured\",\n },\n} as const satisfies Record<VariantKey<ProtocolError>, ErrorMapping>;\n\nconst LENDING_CANISTER_SIGNATURE_VERIFICATION_ERROR_MAP = {\n InvalidEthSignature: { code: LiquidiumErrorCode.INVALID_ETH_SIGNATURE },\n InvalidBtcSignature: { code: LiquidiumErrorCode.INVALID_BTC_SIGNATURE },\n InvalidEthAddress: { code: LiquidiumErrorCode.INVALID_ETH_ADDRESS },\n UnsupportedChain: { code: LiquidiumErrorCode.UNSUPPORTED_CHAIN },\n ProfileNotFound: { code: LiquidiumErrorCode.PROFILE_NOT_FOUND },\n CouldNotDecode: {\n code: LiquidiumErrorCode.SIGNATURE_ERROR,\n fallbackMessage: \"Could not decode signature\",\n },\n InvalidSolSignature: {\n code: LiquidiumErrorCode.SIGNATURE_ERROR,\n fallbackMessage: \"Invalid SOL signature\",\n },\n} as const satisfies Record<\n VariantKey<SignatureVerificationError>,\n ErrorMapping\n>;\n\n/** Maps lending canister `Result.Err(ProtocolError)` responses. */\nexport function mapLendingProtocolErrorToLiquidiumError(\n error: ProtocolError\n): LiquidiumError {\n const [key, payload] = getVariantEntry(error);\n\n if (key === \"SignatureError\") {\n return mapLendingSignatureVerificationErrorToLiquidiumError(\n payload as SignatureVerificationError\n );\n }\n\n return mapVariantToLiquidiumError(\n LENDING_CANISTER_PROTOCOL_RESULT_ERROR_MAP[key],\n payload\n );\n}\n\n/** Maps nested `ProtocolError.SignatureError` verification failures. */\nexport function mapLendingSignatureVerificationErrorToLiquidiumError(\n error: SignatureVerificationError\n): LiquidiumError {\n const [key, payload] = getVariantEntry(error);\n\n return mapVariantToLiquidiumError(\n LENDING_CANISTER_SIGNATURE_VERIFICATION_ERROR_MAP[key],\n payload\n );\n}\n\n/** Maps thrown/rejected canister calls, not typed protocol `Err` responses. */\nexport function mapCanisterCallErrorToLiquidiumError(\n methodName: string,\n cause: unknown\n): LiquidiumError {\n return new LiquidiumError(\n LiquidiumErrorCode.CANISTER_REJECTED,\n `Canister call failed: ${methodName}`,\n cause\n );\n}\n\nfunction getVariantEntry<T extends Record<string, unknown>>(\n variant: T\n): [VariantKey<T>, unknown] {\n const [entry] = Object.entries(variant) as [\n [VariantKey<T>, unknown],\n ...Array<[VariantKey<T>, unknown]>,\n ];\n\n return entry;\n}\n\nfunction mapVariantToLiquidiumError(\n mapping: ErrorMapping,\n payload: unknown\n): LiquidiumError {\n const message =\n typeof payload === \"string\"\n ? payload\n : (mapping.fallbackMessage ?? humanizeErrorCode(mapping.code));\n\n return new LiquidiumError(mapping.code, message);\n}\n\nfunction humanizeErrorCode(code: LiquidiumErrorCode): string {\n return code\n .toLowerCase()\n .replaceAll(\"_\", \" \")\n .replace(/^\\w/, (firstLetter) => firstLetter.toUpperCase());\n}\n","import { getAddress, isAddress } from \"viem\";\n\n/** Ethereum mainnet USDC contract address. */\nexport const USDC_CONTRACT_ADDRESS =\n \"0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48\";\n/** Ethereum mainnet USDT contract address. */\nexport const USDT_CONTRACT_ADDRESS =\n \"0xdac17f958d2ee523a2206206994597c13d831ec7\";\n/** Ethereum mainnet ckETH minter ERC-20 deposit helper contract address. */\nexport const CK_ETH_DEPOSIT_CONTRACT_ADDRESS =\n \"0x18901044688D3756C35Ed2b36D93e6a5B8e00E68\";\n\n/** Largest uint256 value, used for max-allowance ERC-20 approvals. */\nexport const MAX_UINT256 =\n 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffn;\n\n/** Minimal ERC-20 ABI used by the SDK for balance, allowance, approval, and transfers. */\nexport const ERC20_ABI = [\n {\n name: \"allowance\",\n type: \"function\",\n inputs: [\n { name: \"owner\", type: \"address\" },\n { name: \"spender\", type: \"address\" },\n ],\n outputs: [{ name: \"remaining\", type: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n name: \"balanceOf\",\n type: \"function\",\n inputs: [{ name: \"owner\", type: \"address\" }],\n outputs: [{ name: \"balance\", type: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n name: \"approve\",\n type: \"function\",\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n name: \"transfer\",\n type: \"function\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n] as const;\n\n/** ckETH minter deposit helper ABI used for ERC-20 deposits into ICRC accounts. */\nexport const CK_DEPOSIT_ABI = [\n {\n inputs: [\n { internalType: \"address\", name: \"erc20Address\", type: \"address\" },\n { internalType: \"uint256\", name: \"amount\", type: \"uint256\" },\n { internalType: \"bytes32\", name: \"principal\", type: \"bytes32\" },\n { internalType: \"bytes32\", name: \"subaccount\", type: \"bytes32\" },\n ],\n name: \"depositErc20\",\n outputs: [],\n stateMutability: \"nonpayable\",\n type: \"function\",\n },\n] as const;\n\n/** Returns an EIP-55 checksum address when `address` is valid EVM input. */\nexport function normalizeEvmAddress(address: string): string {\n if (!isAddress(address)) {\n return address;\n }\n\n return getAddress(address);\n}\n","const MILLISECONDS_PER_SECOND = 1_000;\nconst SIGNATURE_VALIDITY_5_MINUTES_IN_SECONDS = 5n * 60n;\n\nexport function computeExpiryTimestampFromNow(\n signatureValidityInSeconds: bigint = SIGNATURE_VALIDITY_5_MINUTES_IN_SECONDS\n): bigint {\n return (\n BigInt(Math.floor(Date.now() / MILLISECONDS_PER_SECOND)) +\n signatureValidityInSeconds\n );\n}\n","import { LiquidiumError, LiquidiumErrorCode } from \"../errors\";\n\nexport function getVariantKey(variant: Record<string, unknown>): string {\n const [variantKey] = Object.keys(variant);\n\n if (!variantKey) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n \"Unexpected empty canister variant\"\n );\n }\n\n return variantKey;\n}\n","import type { Chain } from \"./types\";\n\n/** Asset transfer path used for wallet-executed actions. */\nexport const TransferMode = {\n ck: \"ck\",\n native: \"native\",\n} as const;\n/** Asset transfer path used for wallet-executed actions. */\nexport type TransferMode = (typeof TransferMode)[keyof typeof TransferMode];\n\n/** Wallet capability required to execute a prepared SDK action. */\nexport const WalletExecutionKind = {\n sendEthTransaction: \"send-eth-transaction\",\n signMessage: \"sign-message\",\n signPsbt: \"sign-psbt\",\n} as const;\n/** Wallet capability required to execute a prepared SDK action. */\nexport type WalletExecutionKind =\n (typeof WalletExecutionKind)[keyof typeof WalletExecutionKind];\n\n/** Protocol action represented by a prepared wallet action. */\nexport const WalletActionKind = {\n createAccount: \"create-account\",\n createBorrow: \"create-borrow\",\n createWithdraw: \"create-withdraw\",\n} as const;\n/** Protocol action represented by a prepared wallet action. */\nexport type WalletActionKind =\n (typeof WalletActionKind)[keyof typeof WalletActionKind];\n\n/** EVM transaction request passed to wallet adapters. */\nexport interface EthTransactionRequest {\n /** Destination address or contract address. */\n to: string;\n /** Hex-encoded calldata for contract interactions. */\n data?: string;\n /** Native ETH value in wei, serialized as a decimal string. */\n value?: string;\n /** Optional EVM chain id for wallet implementations that require it. */\n chainId?: number;\n}\n\n/** Message-signing request passed to wallet adapters. */\nexport interface SignMessageRequest {\n /** Chain for the signing wallet. */\n chain: Chain;\n /** Plaintext message to sign. */\n message: string;\n /** Optional account override for the signing wallet. */\n account?: string;\n /** SDK action type that produced this request. */\n actionType: string;\n /** Transfer path associated with the action. */\n transferMode: TransferMode;\n}\n\n/** PSBT-signing request passed to BTC wallet adapters. */\nexport interface SignPsbtRequest {\n /** BTC chain discriminator. */\n chain: Extract<Chain, \"BTC\">;\n /** Base64-encoded unsigned PSBT. */\n psbtBase64: string;\n /** Optional BTC account override. */\n account?: string;\n /** SDK action type that produced this request. */\n actionType: string;\n /** Transfer path associated with the action. */\n transferMode: TransferMode;\n}\n\n/** ETH transaction-sending request passed to wallet adapters. */\nexport interface SendEthTransactionRequest {\n /** ETH chain discriminator. */\n chain: Extract<Chain, \"ETH\">;\n /** Transaction payload to send. */\n transaction: EthTransactionRequest;\n /** Optional account override for the sending wallet. */\n account?: string;\n /** SDK action type that produced this request. */\n actionType: string;\n /** Transfer path associated with the action. */\n transferMode: TransferMode;\n}\n\n/** BTC transaction-sending request passed to wallet adapters. */\nexport interface SendBtcTransactionRequest {\n /** BTC chain discriminator. */\n chain: Extract<Chain, \"BTC\">;\n /** Recipient BTC address. */\n toAddress: string;\n /** Amount in satoshis when the SDK knows the transfer amount. */\n amountSats?: bigint;\n /** Optional account override for the sending wallet. */\n account?: string;\n /** SDK action type that produced this request. */\n actionType: string;\n /** Transfer path associated with the action. */\n transferMode: TransferMode;\n}\n\n/**\n * Optional wallet capabilities. Implement only what your flow uses:\n *\n * - `signMessage` - account creation, borrow, withdraw\n * - `sendBtcTransaction` / `sendEthTransaction` - automated transfer-path supply\n * - `sendEthTransaction` - contract-interaction supply and ETH native sends\n * - `signPsbt` - reserved for PSBT-based actions when exposed\n */\nexport interface WalletAdapter {\n /** Signs an SDK plaintext message and returns the wallet signature. */\n signMessage?: (request: SignMessageRequest) => Promise<string>;\n /** Signs an SDK-provided BTC PSBT and returns the signed PSBT as base64. */\n signPsbt?: (request: SignPsbtRequest) => Promise<string>;\n /** Sends an EVM transaction and returns its transaction hash. */\n sendEthTransaction?: (request: SendEthTransactionRequest) => Promise<string>;\n /** Sends a BTC transaction and returns its transaction id. */\n sendBtcTransaction?: (request: SendBtcTransactionRequest) => Promise<string>;\n}\n\n/** Signature payload submitted to a sign-message action. */\nexport interface SignatureInfo {\n /** Wallet signature over the action message. */\n signature: string;\n /** Chain used to produce the signature. */\n chain: Chain;\n /** Account that produced the signature, when different from the action default. */\n account?: string;\n}\n\n/** Prepared action that requires message signing before submit. */\nexport interface SignMessageWalletAction<TData, TResult> {\n /** Protocol action kind. */\n kind: string;\n /** Wallet capability required to execute the action. */\n executionKind: typeof WalletExecutionKind.signMessage;\n /** Adapter-facing action type. */\n actionType: string;\n /** Transfer path associated with the action. */\n transferMode: TransferMode;\n /** Default account to pass to the wallet adapter. */\n account: string;\n /** Plaintext message that must be signed. */\n message: string;\n /** Original request data needed to submit the signed action. */\n data: TData;\n /** Submits the signature and resolves the protocol result. */\n submit(signatureInfo: SignatureInfo): Promise<TResult>;\n}\n\n/** Prepared action that requires BTC PSBT signing before submit. */\nexport interface SignPsbtWalletAction<TResult> {\n /** Protocol action kind. */\n kind: string;\n /** Wallet capability required to execute the action. */\n executionKind: typeof WalletExecutionKind.signPsbt;\n /** Adapter-facing action type. */\n actionType: string;\n /** Transfer path associated with the action. */\n transferMode: TransferMode;\n /** Optional default account to pass to the wallet adapter. */\n account?: string;\n /** Base64-encoded unsigned PSBT. */\n psbtBase64: string;\n /** Submits the signed PSBT and resolves the protocol result. */\n submit(request: { signedPsbtBase64: string }): Promise<TResult>;\n}\n\n/** Prepared action that requires sending an ETH transaction before submit. */\nexport interface SendEthTransactionWalletAction<TResult> {\n /** Protocol action kind. */\n kind: string;\n /** Wallet capability required to execute the action. */\n executionKind: typeof WalletExecutionKind.sendEthTransaction;\n /** Adapter-facing action type. */\n actionType: string;\n /** Transfer path associated with the action. */\n transferMode: TransferMode;\n /** Optional default account to pass to the wallet adapter. */\n account?: string;\n /** EVM transaction request to send. */\n transaction: EthTransactionRequest;\n /** Submits the transaction hash and resolves the protocol result. */\n submit(request: { txHash: string }): Promise<TResult>;\n}\n\n/** Any prepared action returned by SDK methods and executable by {@link executeWith}. */\nexport type WalletAction<TResult> =\n | SignMessageWalletAction<unknown, TResult>\n | SignPsbtWalletAction<TResult>\n | SendEthTransactionWalletAction<TResult>;\n\n// Future extension point:\n// native ICP and native Solana wallet capabilities will be added in a later\n// version once those chains are supported by the SDK.\n// Wallet actions currently default to native asset flows. ck-asset execution\n// paths will be added in a later version for borrow, withdraw, and supply.\n","import { LiquidiumError, LiquidiumErrorCode } from \"./core/errors\";\nimport { Chain } from \"./core/types\";\nimport {\n type WalletAction,\n type WalletAdapter,\n WalletExecutionKind,\n} from \"./core/wallet-actions\";\n\n/**\n * Wallet wiring for {@link executeWith}.\n *\n * `chain` and `account` override values embedded on the action when present;\n * message signing uses `options.account ?? action.account`.\n */\nexport interface ExecuteWithOptions {\n /** Must expose the methods required by the action's `executionKind`. */\n walletAdapter: WalletAdapter;\n /** Required for `sign-message` actions; forwarded to the adapter and submit payload. */\n chain?: Chain;\n /** Optional signing/sending account override. */\n account?: string;\n}\n\n/**\n * Returns an async function that runs a {@link WalletAction} end-to-end.\n *\n * - `sign-message`: needs `walletAdapter.signMessage` and `options.chain`.\n * - `sign-psbt`: needs `walletAdapter.signPsbt`.\n * - `send-eth-transaction`: needs `walletAdapter.sendEthTransaction`.\n *\n * @param options - Adapter and optional chain/account overrides.\n * @returns A function that accepts a `WalletAction` and resolves with its submit result.\n */\nexport function executeWith(options: ExecuteWithOptions) {\n return async function execute<TResult>(\n action: WalletAction<TResult>\n ): Promise<TResult> {\n switch (action.executionKind) {\n case WalletExecutionKind.signMessage: {\n if (!options.walletAdapter.signMessage) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Wallet adapter does not support message signing\"\n );\n }\n\n if (!options.chain) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Message-signing actions require a chain\"\n );\n }\n\n const signature = await options.walletAdapter.signMessage({\n chain: options.chain,\n message: action.message,\n account: options.account ?? action.account,\n actionType: action.actionType,\n transferMode: action.transferMode,\n });\n\n return action.submit({\n signature,\n chain: options.chain,\n account: options.account ?? action.account,\n });\n }\n case WalletExecutionKind.signPsbt: {\n if (!options.walletAdapter.signPsbt) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Wallet adapter does not support PSBT signing\"\n );\n }\n\n const signedPsbtBase64 = await options.walletAdapter.signPsbt({\n chain: Chain.BTC,\n psbtBase64: action.psbtBase64,\n account: options.account ?? action.account,\n actionType: action.actionType,\n transferMode: action.transferMode,\n });\n\n return action.submit({ signedPsbtBase64 });\n }\n case WalletExecutionKind.sendEthTransaction: {\n if (!options.walletAdapter.sendEthTransaction) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Wallet adapter does not support ETH transaction sending\"\n );\n }\n\n const txHash = await options.walletAdapter.sendEthTransaction({\n chain: Chain.ETH,\n transaction: action.transaction,\n account: options.account ?? action.account,\n actionType: action.actionType,\n transferMode: action.transferMode,\n });\n\n return action.submit({ txHash });\n }\n default:\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Unsupported wallet execution kind: ${String(\n (action as { executionKind?: unknown }).executionKind\n )}`\n );\n }\n };\n}\n","export function normalizeHexSignature(signature: string): string {\n if (!signature.startsWith(\"0x\")) {\n return signature;\n }\n\n const signatureWithoutPrefix = signature.slice(2);\n\n if (!/^[0-9a-fA-F]+$/.test(signatureWithoutPrefix)) {\n return signature;\n }\n\n return signatureWithoutPrefix;\n}\n","import type { RegisterProfileRequest } from \"../../core/canisters/lending/actor\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport { Chain } from \"../../core/types\";\nimport { normalizeHexSignature } from \"../../core/utils/signature\";\nimport type { CreateAccountRequest } from \"./types\";\n\ntype AccountChainVariant = { BTC: null } | { ETH: null };\n\nexport function mapCreateAccountRequestToRegisterProfileRequest(\n request: CreateAccountRequest\n): RegisterProfileRequest {\n const signingAccount = request.signatureInfo.account;\n if (!signingAccount) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Account creation requires the signing account\"\n );\n }\n\n return {\n data: {\n expiry_timestamp: request.data.expiryTimestamp,\n },\n signature_info: {\n Wallet: {\n signature: normalizeHexSignature(request.signatureInfo.signature),\n chain: mapAccountChainToLendingChainVariant(\n request.signatureInfo.chain\n ),\n account: signingAccount,\n },\n },\n };\n}\n\nfunction mapAccountChainToLendingChainVariant(\n chain: Chain\n): AccountChainVariant {\n switch (chain) {\n case Chain.BTC:\n return { BTC: null };\n case Chain.ETH:\n return { ETH: null };\n }\n}\n","import { Principal } from \"@dfinity/principal\";\nimport {\n createLendingActor,\n type WalletRecord,\n} from \"../../core/canisters/lending/actor\";\nimport {\n mapCanisterCallErrorToLiquidiumError,\n mapLendingProtocolErrorToLiquidiumError,\n} from \"../../core/canisters/lending/error-mappers\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport { normalizeEvmAddress } from \"../../core/evm\";\nimport type { CanisterContext } from \"../../core/transports/canister-context\";\nimport { Chain, type Wallet } from \"../../core/types\";\nimport { computeExpiryTimestampFromNow } from \"../../core/utils/time\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport {\n TransferMode,\n WalletActionKind,\n type WalletAdapter,\n WalletExecutionKind,\n} from \"../../core/wallet-actions\";\nimport { executeWith } from \"../../execute\";\nimport { mapCreateAccountRequestToRegisterProfileRequest } from \"./mappers\";\nimport type { CreateAccountAction, CreateAccountRequest } from \"./types\";\n\ntype PrepareCreateProfileOptions = {\n account: string;\n};\n\ntype CreateProfileParams = {\n account: string;\n chain: Chain;\n walletAdapter: WalletAdapter;\n};\n\n/** Profile lifecycle and linked-wallet helpers. */\nexport class AccountsModule {\n constructor(readonly canisterContext: CanisterContext) {}\n\n /**\n * Prepares a profile-creation action that can be signed and submitted later.\n *\n * Use this when you need direct control over the signing flow.\n *\n * @param options - `account` is the wallet address that will own the new profile.\n * @returns A signable {@link CreateAccountAction} with `submit` wired to the canister.\n */\n async prepareCreateProfile(\n options: PrepareCreateProfileOptions\n ): Promise<CreateAccountAction> {\n return await this.buildCreateProfileAction(options.account);\n }\n\n /**\n * Creates a Liquidium profile using the provided wallet adapter.\n *\n * This is the convenience form of `prepareCreateProfile(...)` plus execution.\n *\n * @param params - Wallet `account`, signing `chain`, and `walletAdapter` with `signMessage`.\n * @returns The new profile principal as text.\n */\n async createProfile(params: CreateProfileParams): Promise<string> {\n const account = normalizeProfileAccount(params.account);\n const action = await this.prepareCreateProfile({\n account,\n });\n\n return await executeWith({\n walletAdapter: params.walletAdapter,\n chain: params.chain,\n account,\n })(action);\n }\n\n /**\n * Resolves the Liquidium profile id linked to a wallet address.\n *\n * @param walletAddress - Wallet address string as registered with the protocol.\n * @returns Profile principal text, or `null` if none exists.\n */\n async getProfileId(walletAddress: string): Promise<string | null> {\n try {\n const account = normalizeProfileAccount(walletAddress);\n const profile = await createLendingActor(\n this.canisterContext\n ).get_wallet_profile(account);\n\n return profile[0]?.toText() ?? null;\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_wallet_profile\", error);\n }\n }\n\n /**\n * Returns the current nonce for a wallet address.\n *\n * This is mainly useful for custom signing flows built on prepared actions.\n *\n * @param walletAddress - Wallet address used in `get_nonce` on the lending canister.\n * @returns The next signing nonce as a bigint.\n */\n async getWalletNonce(walletAddress: string): Promise<bigint> {\n try {\n const account = normalizeProfileAccount(walletAddress);\n return await createLendingActor(this.canisterContext).get_nonce(account);\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_nonce\", error);\n }\n }\n\n /**\n * Lists the wallets currently linked to a profile.\n *\n * @param profileId - The Liquidium profile principal text.\n * @returns The wallets currently linked to the requested profile.\n */\n async listLinkedWallets(profileId: string): Promise<Wallet[]> {\n try {\n const wallets = await createLendingActor(\n this.canisterContext\n ).get_profile_wallets(Principal.fromText(profileId));\n\n return wallets.map(mapCanisterWalletToWallet);\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_profile_wallets\", error);\n }\n }\n\n private async buildCreateProfileAction(\n account: string\n ): Promise<CreateAccountAction> {\n try {\n const normalizedAccount = normalizeProfileAccount(account);\n\n const nonce = await createLendingActor(this.canisterContext).get_nonce(\n normalizedAccount\n );\n const expiryTimestamp = computeExpiryTimestampFromNow();\n\n return {\n kind: WalletActionKind.createAccount,\n executionKind: WalletExecutionKind.signMessage,\n actionType: WalletActionKind.createAccount,\n transferMode: TransferMode.native,\n account: normalizedAccount,\n message: createInitializeAccountMessage(expiryTimestamp, nonce),\n data: {\n expiryTimestamp,\n },\n submit: async (signatureInfo) => {\n return await this.submitCreateProfile({\n data: {\n expiryTimestamp,\n },\n signatureInfo: {\n ...signatureInfo,\n account: normalizeProfileAccount(\n signatureInfo.account ?? normalizedAccount\n ),\n },\n });\n },\n };\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_nonce\", error);\n }\n }\n\n private async submitCreateProfile(\n request: CreateAccountRequest\n ): Promise<string> {\n try {\n const signingAccount = request.signatureInfo.account;\n if (!signingAccount) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Account creation requires the signing account\"\n );\n }\n\n await assertWalletHasNoProfile(this.canisterContext, signingAccount);\n\n const result = await createLendingActor(\n this.canisterContext\n ).register_profile(\n mapCreateAccountRequestToRegisterProfileRequest(request)\n );\n\n if (\"Err\" in result) {\n throw mapLendingProtocolErrorToLiquidiumError(result.Err);\n }\n\n return result.Ok.toText();\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"register_profile\", error);\n }\n }\n}\n\nfunction normalizeProfileAccount(account: string): string {\n return normalizeEvmAddress(account);\n}\n\nfunction createInitializeAccountMessage(\n expiryTimestamp: bigint,\n nonce: bigint\n): string {\n return `Liquidium: Initialize Account\n\nAction: Create new account\nExpires: ${expiryTimestamp}\nNonce: ${nonce}`;\n}\n\nasync function assertWalletHasNoProfile(\n canisterContext: CanisterContext,\n walletAddress: string\n): Promise<void> {\n const existingProfile =\n await createLendingActor(canisterContext).get_wallet_profile(walletAddress);\n const profileId = existingProfile[0]?.toText();\n\n if (!profileId) {\n return;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.PROFILE_ALREADY_EXISTS,\n `Wallet address is already linked to profile ${profileId}`\n );\n}\n\nfunction mapCanisterWalletToWallet(canisterWallet: WalletRecord): Wallet {\n const walletChain = getVariantKey(canisterWallet.chain.Wallet);\n\n switch (walletChain) {\n case Chain.BTC:\n case Chain.ETH:\n return {\n address: canisterWallet.address,\n chain: walletChain,\n };\n default:\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Unsupported wallet chain returned for profile wallet: ${walletChain}`\n );\n }\n}\n","import type { ActorMethod } from \"@dfinity/agent\";\nimport { Actor } from \"@dfinity/agent\";\nimport type { IDL } from \"@dfinity/candid\";\nimport type { Principal } from \"@dfinity/principal\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { CanisterContext } from \"../../transports/canister-context\";\n\nexport type InstantLoanAccountType =\n | { Native: Principal }\n | { External: string };\nexport type InstantLoanAsset =\n | { BTC: null }\n | { SOL: null }\n | { USDC: null }\n | { USDT: null };\nexport type InstantLoanLeg = { Lend: null } | { Borrow: null };\nexport type InstantLoanAuthorisation = {\n EthSignature: {\n derivation_index: Uint8Array;\n pubkey: Uint8Array;\n address: string;\n };\n};\n\nexport interface CreateInstantLoanCanisterRequest {\n borrow_destination: InstantLoanAccountType;\n lend_asset: InstantLoanAsset;\n borrow_amount: bigint;\n lend_pool_id: Principal;\n refund_destination: InstantLoanAccountType;\n ltv_max_bps: bigint;\n borrow_pool_id: Principal;\n borrow_asset: InstantLoanAsset;\n ltv_timer_s: bigint;\n}\n\nexport interface CreateInstantLoanCanisterResponse {\n loan_id: bigint;\n lending_profile: Principal;\n}\n\nexport interface HeadlessLoansConfig {\n lending_canister: Principal;\n}\n\nexport type HeadlessLoanEventType =\n | {\n LoanCreated: {\n loan_id: bigint;\n borrow_destination: InstantLoanAccountType;\n lend_asset: InstantLoanAsset;\n borrow_amount: bigint;\n lend_pool_id: Principal;\n refund_destination: InstantLoanAccountType;\n ltv_max_bps: bigint;\n ltv_timer_s: bigint;\n lending_profile: Principal;\n borrow_pool_id: Principal;\n borrow_asset: InstantLoanAsset;\n };\n }\n | {\n FullLendWithdrawalRequested: {\n loan_id: bigint;\n account: InstantLoanAccountType;\n pool_id: Principal;\n };\n }\n | {\n BorrowRequested: {\n loan_id: bigint;\n account: InstantLoanAccountType;\n pool_id: Principal;\n amount: bigint;\n };\n }\n | { DepositTimerExceeded: { loan_id: bigint } }\n | {\n StuckFundsWithdrawalRequested: {\n leg: InstantLoanLeg;\n loan_id: bigint;\n account: InstantLoanAccountType;\n pool_id: Principal;\n amount: bigint;\n };\n }\n | {\n ProfileWarmed: {\n derivation_index: Uint8Array;\n warmed_profile_id: bigint;\n eth_address: string;\n lending_profile: Principal;\n };\n }\n | { RepayComplete: CreateInstantLoanCanisterResponse }\n | { DepositTimerStarted: { loan_id: bigint; timestamp: bigint } };\n\nexport interface HeadlessLoanEvent {\n id: bigint;\n schema_version: number;\n timestamp: bigint;\n event_type: HeadlessLoanEventType;\n}\n\nexport interface InstantLoanCanisterRecord {\n id: bigint;\n authorisation: InstantLoanAuthorisation;\n borrow_destination: InstantLoanAccountType;\n started: boolean;\n lend_asset: InstantLoanAsset;\n created_at: bigint;\n schema_version: number;\n borrow_amount: bigint;\n lend_pool_id: Principal;\n refund_destination: InstantLoanAccountType;\n ltv_max_bps: bigint;\n ltv_timer_s: bigint;\n lending_profile: Principal;\n borrow_pool_id: Principal;\n borrow_asset: InstantLoanAsset;\n expires_at: [] | [bigint];\n deposit_detected_ts: [] | [bigint];\n}\n\nexport interface WarmedProfile {\n id: bigint;\n authorisation: InstantLoanAuthorisation;\n created_at: bigint;\n lending_profile: Principal;\n}\n\ntype LendingClientError =\n | { CallFailed: { method: string; reason: string } }\n | { CallRejected: { method: string; reason: string } }\n | { DecodeFailed: { method: string; reason: string } };\n\nexport type InstantLoansCanisterError =\n | { BorrowAmountRequired: null }\n | { NoCollateralPosition: { loan_id: bigint } }\n | { LtvTimerOutOfRange: { max: bigint } }\n | { LtvMaxExceeded: { actual_bps: bigint; max_bps: bigint } }\n | { MemoryLockFailed: { reason: string } }\n | { UnauthorizedAccessListCaller: { caller: Principal } }\n | { LendingClient: LendingClientError }\n | { LtvMaxOutOfRange: { max: bigint } }\n | { AccountRequired: { label: string } }\n | { DepositTimerExceeded: { loan_id: bigint } }\n | { LoanNotFound: { loan_id: bigint } }\n | { LendingProtocolError: { error: unknown; operation: string } }\n | { AuthorizationFailed: { reason: string } }\n | { DepositAlreadyProcessed: { loan_id: bigint } }\n | { MissingPrice: { symbol: string } }\n | { InvalidLtvTimerS: null }\n | { DebtNotFullyRepaid: { loan_id: bigint } }\n | { EmptyCollateralPosition: null }\n | { SigningFailed: { reason: string } };\n\ntype Result<T> = { Ok: T } | { Err: InstantLoansCanisterError };\n\nexport interface InstantLoansActor {\n create_loan: ActorMethod<\n [CreateInstantLoanCanisterRequest],\n Result<CreateInstantLoanCanisterResponse>\n >;\n count_warmed_profiles: ActorMethod<[], bigint>;\n get_config: ActorMethod<[], HeadlessLoansConfig>;\n get_event: ActorMethod<[bigint], [] | [HeadlessLoanEvent]>;\n get_loan: ActorMethod<[bigint], Result<InstantLoanCanisterRecord>>;\n list_access_list: ActorMethod<[], Principal[]>;\n list_events: ActorMethod<\n [bigint, bigint],\n Array<[bigint, HeadlessLoanEvent]>\n >;\n list_warmed_profiles: ActorMethod<[], WarmedProfile[]>;\n}\n\nconst idlFactory: IDL.InterfaceFactory = ({ IDL }) => {\n const AccountType = IDL.Variant({\n Native: IDL.Principal,\n External: IDL.Text,\n });\n const Assets = IDL.Variant({\n BTC: IDL.Null,\n SOL: IDL.Null,\n USDC: IDL.Null,\n USDT: IDL.Null,\n });\n const SignatureVerificationError = IDL.Variant({\n InvalidEthSignature: IDL.Null,\n UnsupportedChain: IDL.Null,\n InvalidSolSignature: IDL.Null,\n InvalidEthAddress: IDL.Null,\n CouldNotDecode: IDL.Text,\n ProfileNotFound: IDL.Null,\n InvalidBtcSignature: IDL.Null,\n });\n const ProtocolError = IDL.Variant({\n PositionNotFound: IDL.Null,\n Internal: IDL.Text,\n InvalidAddress: IDL.Text,\n InvalidTargetPrincipal: IDL.Null,\n SignatureError: SignatureVerificationError,\n SupplyCapExceeded: IDL.Null,\n AccountNotFound: IDL.Null,\n NotAllowed: IDL.Text,\n PoolNotFound: IDL.Text,\n FeeClaimReceiverNotConfigured: IDL.Null,\n InsufficientCollateral: IDL.Null,\n ProfileNotFound: IDL.Null,\n SignatureExpiryTooFarInFuture: IDL.Null,\n MaxLtvExceeded: IDL.Null,\n ProfileAlreadyExists: IDL.Null,\n LiquidationNotFound: IDL.Text,\n HealthFactorTooLow: IDL.Null,\n NoLiquidity: IDL.Null,\n SignatureExpired: IDL.Null,\n BorrowingDisabled: IDL.Null,\n BorrowCapExceeded: IDL.Null,\n PoolFrozen: IDL.Null,\n TransferFailed: IDL.Text,\n AccountAlreadyLinked: IDL.Null,\n CannotRemoveSoleAccount: IDL.Null,\n InsufficientFunds: IDL.Null,\n });\n const InstantLoansError = IDL.Variant({\n BorrowAmountRequired: IDL.Null,\n NoCollateralPosition: IDL.Record({ loan_id: IDL.Nat }),\n LtvTimerOutOfRange: IDL.Record({ max: IDL.Nat64 }),\n LtvMaxExceeded: IDL.Record({\n actual_bps: IDL.Nat64,\n max_bps: IDL.Nat64,\n }),\n MemoryLockFailed: IDL.Record({ reason: IDL.Text }),\n UnauthorizedAccessListCaller: IDL.Record({ caller: IDL.Principal }),\n LendingClient: IDL.Variant({\n CallFailed: IDL.Record({ method: IDL.Text, reason: IDL.Text }),\n CallRejected: IDL.Record({ method: IDL.Text, reason: IDL.Text }),\n DecodeFailed: IDL.Record({ method: IDL.Text, reason: IDL.Text }),\n }),\n LtvMaxOutOfRange: IDL.Record({ max: IDL.Nat64 }),\n AccountRequired: IDL.Record({ label: IDL.Text }),\n DepositTimerExceeded: IDL.Record({ loan_id: IDL.Nat }),\n LoanNotFound: IDL.Record({ loan_id: IDL.Nat }),\n LendingProtocolError: IDL.Record({\n error: ProtocolError,\n operation: IDL.Text,\n }),\n AuthorizationFailed: IDL.Record({ reason: IDL.Text }),\n DepositAlreadyProcessed: IDL.Record({ loan_id: IDL.Nat }),\n MissingPrice: IDL.Record({ symbol: IDL.Text }),\n InvalidLtvTimerS: IDL.Null,\n DebtNotFullyRepaid: IDL.Record({ loan_id: IDL.Nat }),\n EmptyCollateralPosition: IDL.Null,\n SigningFailed: IDL.Record({ reason: IDL.Text }),\n });\n const CreateLoanRequest = IDL.Record({\n borrow_destination: AccountType,\n lend_asset: Assets,\n borrow_amount: IDL.Nat,\n lend_pool_id: IDL.Principal,\n refund_destination: AccountType,\n ltv_max_bps: IDL.Nat64,\n borrow_pool_id: IDL.Principal,\n borrow_asset: Assets,\n ltv_timer_s: IDL.Nat64,\n });\n const CreateLoanResponse = IDL.Record({\n loan_id: IDL.Nat,\n lending_profile: IDL.Principal,\n });\n const CreateLoanResult = IDL.Variant({\n Ok: CreateLoanResponse,\n Err: InstantLoansError,\n });\n const LoanLeg = IDL.Variant({ Lend: IDL.Null, Borrow: IDL.Null });\n const HeadlessLoanEventType = IDL.Variant({\n LoanCreated: IDL.Record({\n loan_id: IDL.Nat,\n borrow_destination: AccountType,\n lend_asset: Assets,\n borrow_amount: IDL.Nat,\n lend_pool_id: IDL.Principal,\n refund_destination: AccountType,\n ltv_max_bps: IDL.Nat64,\n ltv_timer_s: IDL.Nat64,\n lending_profile: IDL.Principal,\n borrow_pool_id: IDL.Principal,\n borrow_asset: Assets,\n }),\n FullLendWithdrawalRequested: IDL.Record({\n loan_id: IDL.Nat,\n account: AccountType,\n pool_id: IDL.Principal,\n }),\n BorrowRequested: IDL.Record({\n loan_id: IDL.Nat,\n account: AccountType,\n pool_id: IDL.Principal,\n amount: IDL.Nat,\n }),\n DepositTimerExceeded: IDL.Record({ loan_id: IDL.Nat }),\n StuckFundsWithdrawalRequested: IDL.Record({\n leg: LoanLeg,\n loan_id: IDL.Nat,\n account: AccountType,\n pool_id: IDL.Principal,\n amount: IDL.Nat,\n }),\n ProfileWarmed: IDL.Record({\n derivation_index: IDL.Vec(IDL.Nat8),\n warmed_profile_id: IDL.Nat,\n eth_address: IDL.Text,\n lending_profile: IDL.Principal,\n }),\n RepayComplete: CreateLoanResponse,\n DepositTimerStarted: IDL.Record({\n loan_id: IDL.Nat,\n timestamp: IDL.Nat64,\n }),\n });\n const HeadlessLoanEvent = IDL.Record({\n id: IDL.Nat,\n schema_version: IDL.Nat16,\n timestamp: IDL.Nat64,\n event_type: HeadlessLoanEventType,\n });\n const AuthorisationType = IDL.Variant({\n EthSignature: IDL.Record({\n derivation_index: IDL.Vec(IDL.Nat8),\n pubkey: IDL.Vec(IDL.Nat8),\n address: IDL.Text,\n }),\n });\n const Loan = IDL.Record({\n id: IDL.Nat,\n authorisation: AuthorisationType,\n borrow_destination: AccountType,\n started: IDL.Bool,\n lend_asset: Assets,\n created_at: IDL.Nat64,\n schema_version: IDL.Nat16,\n borrow_amount: IDL.Nat,\n lend_pool_id: IDL.Principal,\n refund_destination: AccountType,\n ltv_max_bps: IDL.Nat64,\n ltv_timer_s: IDL.Nat64,\n lending_profile: IDL.Principal,\n expires_at: IDL.Opt(IDL.Nat64),\n borrow_pool_id: IDL.Principal,\n borrow_asset: Assets,\n deposit_detected_ts: IDL.Opt(IDL.Nat64),\n });\n const LoanResult = IDL.Variant({ Ok: Loan, Err: InstantLoansError });\n const HeadlessLoansConfig = IDL.Record({\n lending_canister: IDL.Principal,\n });\n const WarmedProfile = IDL.Record({\n id: IDL.Nat,\n authorisation: AuthorisationType,\n created_at: IDL.Nat64,\n lending_profile: IDL.Principal,\n });\n\n return IDL.Service({\n count_warmed_profiles: IDL.Func([], [IDL.Nat64], [\"query\"]),\n create_loan: IDL.Func([CreateLoanRequest], [CreateLoanResult], []),\n get_config: IDL.Func([], [HeadlessLoansConfig], [\"query\"]),\n get_event: IDL.Func([IDL.Nat], [IDL.Opt(HeadlessLoanEvent)], [\"query\"]),\n get_loan: IDL.Func([IDL.Nat], [LoanResult], [\"query\"]),\n list_access_list: IDL.Func([], [IDL.Vec(IDL.Principal)], [\"query\"]),\n list_events: IDL.Func(\n [IDL.Nat, IDL.Nat64],\n [IDL.Vec(IDL.Tuple(IDL.Nat, HeadlessLoanEvent))],\n [\"query\"]\n ),\n list_warmed_profiles: IDL.Func([], [IDL.Vec(WarmedProfile)], [\"query\"]),\n });\n};\n\nexport function createInstantLoansActor(\n canisterContext: CanisterContext\n): InstantLoansActor {\n const canisterId = canisterContext.canisterIds.instantLoans;\n\n if (!canisterId) {\n throw new LiquidiumError(\n LiquidiumErrorCode.SERVICE_UNAVAILABLE,\n \"Instant loans canister ID is not configured\"\n );\n }\n\n return Actor.createActor<InstantLoansActor>(idlFactory, {\n agent: canisterContext.agent,\n canisterId,\n });\n}\n","/**\n * Path and query key constants for the Liquidium SDK HTTP API.\n */\n\nconst SDK_API_VERSION = {\n activities: \"v1\",\n history: \"v1\",\n inflow: \"v1\",\n instantLoans: \"v1\",\n} as const;\n\nexport const SdkApiQueryParam = {\n cursor: \"cursor\",\n from: \"from\",\n limit: \"limit\",\n market: \"market\",\n poolId: \"poolId\",\n profileId: \"profileId\",\n state: \"state\",\n statuses: \"statuses\",\n to: \"to\",\n types: \"types\",\n} as const;\n\ntype BuildActivitiesPathRequest = {\n profileId: string;\n state?: string;\n};\n\ntype BuildActivityStatusPathRequest = {\n profileId: string;\n id: string;\n};\n\ntype BuildInstantLoanAddressLookupPathRequest = {\n address: string;\n};\n\nconst ACTIVITIES = `/${SDK_API_VERSION.activities}/activities`;\nconst HISTORY_POOL = `/${SDK_API_VERSION.history}/history/pool`;\nconst HISTORY_POOL_CONFIG = `/${SDK_API_VERSION.history}/history/pool-config`;\nconst HISTORY_RATES = `/${SDK_API_VERSION.history}/history/rates`;\nconst HISTORY_USERS = `/${SDK_API_VERSION.history}/history/users`;\nconst INFLOW = `/${SDK_API_VERSION.inflow}/inflow`;\nconst INSTANT_LOANS = `/${SDK_API_VERSION.instantLoans}/instant-loans`;\n\nexport function buildHistoryPoolPath(\n poolId: string,\n query: URLSearchParams\n): string {\n const base = `${HISTORY_POOL}/${encodeURIComponent(poolId)}`;\n const qs = query.toString();\n return qs ? `${base}?${qs}` : base;\n}\n\nexport function buildHistoryPoolConfigPath(\n poolId: string,\n cursor?: string\n): string {\n const base = `${HISTORY_POOL_CONFIG}/${encodeURIComponent(poolId)}`;\n if (!cursor) {\n return base;\n }\n\n const query = new URLSearchParams({ [SdkApiQueryParam.cursor]: cursor });\n return `${base}?${query.toString()}`;\n}\n\nexport function buildHistoryRatesPath(\n poolId: string,\n query: URLSearchParams\n): string {\n const base = `${HISTORY_RATES}/${encodeURIComponent(poolId)}`;\n const qs = query.toString();\n return qs ? `${base}?${qs}` : base;\n}\n\nexport function buildHistoryUserTransactionsPath(\n user: string,\n query: URLSearchParams\n): string {\n const base = `${HISTORY_USERS}/${encodeURIComponent(user)}/transactions`;\n const qs = query.toString();\n return qs ? `${base}?${qs}` : base;\n}\n\nexport function buildHistoryUserLiquidationsPath(\n user: string,\n query: URLSearchParams\n): string {\n const base = `${HISTORY_USERS}/${encodeURIComponent(user)}/liquidations`;\n const qs = query.toString();\n return qs ? `${base}?${qs}` : base;\n}\n\nexport function buildActivitiesPath(\n request: BuildActivitiesPathRequest\n): string {\n const query = new URLSearchParams({\n [SdkApiQueryParam.profileId]: request.profileId,\n });\n if (request.state) {\n query.set(SdkApiQueryParam.state, request.state);\n }\n\n return `${ACTIVITIES}?${query.toString()}`;\n}\n\nexport function buildActivityStatusPath(\n request: BuildActivityStatusPathRequest\n): string {\n const query = new URLSearchParams({\n [SdkApiQueryParam.profileId]: request.profileId,\n });\n\n return `${ACTIVITIES}/${encodeURIComponent(\n request.id\n )}/status?${query.toString()}`;\n}\n\nexport function buildInstantLoanAddressLookupPath(\n request: BuildInstantLoanAddressLookupPathRequest\n): string {\n const query = new URLSearchParams({ address: request.address });\n return `${INSTANT_LOANS}/address?${query.toString()}`;\n}\n\nexport const SdkApiPath = {\n inflow: INFLOW,\n instantLoans: INSTANT_LOANS,\n} as const;\n","import { LiquidiumError, LiquidiumErrorCode } from \"../errors\";\n\nexport function ceilDivBigint(numerator: bigint, denominator: bigint): bigint {\n if (denominator === 0n) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n \"ceilDivBigint called with zero denominator\"\n );\n }\n\n if (numerator === 0n) {\n return 0n;\n }\n\n const numeratorIsNegative = numerator < 0n;\n const denominatorIsNegative = denominator < 0n;\n const resultIsNegative = numeratorIsNegative !== denominatorIsNegative;\n\n const absNumerator = numeratorIsNegative ? -numerator : numerator;\n const absDenominator = denominatorIsNegative ? -denominator : denominator;\n\n if (resultIsNegative) {\n return -(absNumerator / absDenominator);\n }\n\n return (absNumerator + absDenominator - 1n) / absDenominator;\n}\n\nexport function parseBigInt(value: string, label: string): bigint {\n try {\n return BigInt(value);\n } catch (error) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Invalid bigint returned for ${label}`,\n error\n );\n }\n}\n\nexport function parseOptionalBigInt(\n value: string | undefined,\n label: string\n): bigint | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n return parseBigInt(value, label);\n}\n","/** Number of characters in a public instant-loan reference. */\nexport const REF_LENGTH = 6;\n\n/** Crockford-style base32 alphabet used for public instant-loan references. */\nexport const REF_ALPHABET = \"0123456789ABCDEFGHJKMNPQRSTVWXYZ\";\n\nconst BASE = 32n;\nconst MOD = BASE ** BigInt(REF_LENGTH);\nconst A = 1_103_515_245n;\nconst B = 123_456_789n;\nconst A_INVERSE = modInverse(A, MOD);\nconst ALPHABET_INDEX = new Map(\n [...REF_ALPHABET].map((character, index) => [character, BigInt(index)])\n);\n\n/**\n * Converts a canister loan id into a short user-facing reference.\n *\n * @param id - Canister loan id in the supported public-reference range.\n * @returns Fixed-length public reference string.\n */\nexport function publicIdFromInt(id: bigint): string {\n if (id < 0n || id >= MOD) throw new Error(\"id out of range\");\n return toBase32Fixed((id * A + B) % MOD);\n}\n\n/**\n * Decodes a short user-facing reference back into the canister loan id.\n *\n * @param ref - Fixed-length public reference string.\n * @returns Canister loan id represented by the reference.\n */\nexport function intFromPublicId(ref: string): bigint {\n const encodedId = fromBase32Fixed(ref.toUpperCase());\n const id = ((encodedId - B) * A_INVERSE) % MOD;\n return (id + MOD) % MOD;\n}\n\nfunction modInverse(value: bigint, modulo: bigint): bigint {\n let oldRemainder = value;\n let remainder = modulo;\n let oldCoefficient = 1n;\n let coefficient = 0n;\n\n while (remainder !== 0n) {\n const quotient = oldRemainder / remainder;\n\n [oldRemainder, remainder] = [\n remainder,\n oldRemainder - quotient * remainder,\n ];\n [oldCoefficient, coefficient] = [\n coefficient,\n oldCoefficient - quotient * coefficient,\n ];\n }\n\n if (oldRemainder !== 1n) throw new Error(\"value is not invertible\");\n\n return ((oldCoefficient % modulo) + modulo) % modulo;\n}\n\nfunction toBase32Fixed(value: bigint): string {\n let encoded = \"\";\n let remaining = value;\n for (let i = 0; i < REF_LENGTH; i++) {\n encoded = REF_ALPHABET[Number(remaining % BASE)] + encoded;\n remaining /= BASE;\n }\n return encoded;\n}\n\nfunction fromBase32Fixed(ref: string): bigint {\n if (ref.length !== REF_LENGTH) {\n throw new Error(`ref must be ${REF_LENGTH} characters`);\n }\n\n let decoded = 0n;\n for (const character of ref) {\n const value = ALPHABET_INDEX.get(character);\n if (value === undefined) {\n throw new Error(\"ref contains invalid character\");\n }\n\n decoded = decoded * BASE + value;\n }\n\n return decoded;\n}\n","import type { Chain } from \"../../core/types\";\n\n/** Activity list state filter. */\nexport const ActivityFilter = {\n active: \"active\",\n completed: \"completed\",\n all: \"all\",\n} as const;\n/** Activity list state filter. */\nexport type ActivityFilter =\n (typeof ActivityFilter)[keyof typeof ActivityFilter];\n\n/** Direction of value movement for an activity. */\nexport const ActivityDirection = {\n inflow: \"inflow\",\n outflow: \"outflow\",\n} as const;\n/** Direction of value movement for an activity. */\nexport type ActivityDirection =\n (typeof ActivityDirection)[keyof typeof ActivityDirection];\n\n/** Consumer-facing activity kind. */\nexport const ActivityKind = {\n deposit: \"deposit\",\n repayment: \"repayment\",\n borrow: \"borrow\",\n withdraw: \"withdraw\",\n} as const;\n/** Consumer-facing activity kind. */\nexport type ActivityKind = (typeof ActivityKind)[keyof typeof ActivityKind];\n\n/** Consumer-facing activity lifecycle status. */\nexport const ActivityStatus = {\n requested: \"requested\",\n pending: \"pending\",\n detected: \"detected\",\n processing: \"processing\",\n sent: \"sent\",\n confirmed: \"confirmed\",\n failed: \"failed\",\n} as const;\n/** Consumer-facing activity lifecycle status. */\nexport type ActivityStatus =\n (typeof ActivityStatus)[keyof typeof ActivityStatus];\n\n/** Fee top-up state for an inflow activity. */\nexport interface ActivityTopUp {\n /** Whether another transfer is needed before processing can continue. */\n required: boolean;\n /** Total same-token deposited amount counted toward the current fee. */\n depositedAmount: bigint;\n /** Current deposit-address processing fee. */\n feeAmount: bigint;\n /** Additional amount needed before processing can start. */\n shortfallAmount: bigint;\n}\n\n/** Activity kind emitted by deposit or repayment inflows. */\nexport type InflowActivityKind =\n | typeof ActivityKind.deposit\n | typeof ActivityKind.repayment;\n/** Activity kind emitted by borrow or withdraw outflows. */\nexport type OutflowActivityKind =\n | typeof ActivityKind.borrow\n | typeof ActivityKind.withdraw;\n\n/** Lifecycle status that can appear on an inflow activity. */\nexport type InflowActivityStatus =\n | typeof ActivityStatus.requested\n | typeof ActivityStatus.pending\n | typeof ActivityStatus.detected\n | typeof ActivityStatus.processing\n | typeof ActivityStatus.confirmed\n | typeof ActivityStatus.failed;\n/** Lifecycle status that can appear on an outflow activity. */\nexport type OutflowActivityStatus =\n | typeof ActivityStatus.requested\n | typeof ActivityStatus.pending\n | typeof ActivityStatus.sent\n | typeof ActivityStatus.confirmed\n | typeof ActivityStatus.failed;\n\ninterface BaseActivity {\n id: string;\n poolId: string;\n asset: string | null;\n chain: Chain | null;\n amount: bigint;\n timestampMs: number;\n txid: string | null;\n txids?: string[];\n confirmations: number | null;\n requiredConfirmations: number | null;\n}\n\n/** Deposit or repayment activity returned by the activity API. */\nexport interface InflowActivity extends BaseActivity {\n /** Direction discriminator. */\n direction: typeof ActivityDirection.inflow;\n /** Deposit or repayment kind. */\n kind: InflowActivityKind;\n /** Single consumer-facing lifecycle status. */\n status: InflowActivityStatus;\n /** Fee top-up state when the inflow is below the current processing fee. */\n topUp?: ActivityTopUp;\n}\n\n/** Borrow or withdraw activity returned by the activity API. */\nexport interface OutflowActivity extends BaseActivity {\n /** Direction discriminator. */\n direction: typeof ActivityDirection.outflow;\n /** Borrow or withdraw kind. */\n kind: OutflowActivityKind;\n /** Single consumer-facing lifecycle status. */\n status: OutflowActivityStatus;\n /** Outflows never carry top-up state. */\n topUp?: never;\n}\n\n/** Any activity returned by `activities.list` or `activities.getStatus`. */\nexport type Activity = InflowActivity | OutflowActivity;\n\n/** Request for listing activities by profile id or instant-loan short reference. */\nexport type ListActivitiesRequest = {\n /** Optional state filter; defaults to `all`. */\n filter?: ActivityFilter;\n} & ({ profileId: string } | { shortRef: string });\n\n/** Request for fetching one activity by id and owner identifier. */\nexport type GetActivityStatusRequest = {\n /** Activity or receipt id to look up. */\n id: string;\n} & ({ profileId: string } | { shortRef: string });\n\n/** Result of an activity status lookup. */\nexport type GetActivityStatusResponse =\n | {\n found: true;\n activity: Activity;\n }\n | {\n found: false;\n id: string;\n };\n","import {\n createInstantLoansActor,\n type InstantLoansCanisterError,\n} from \"../../core/canisters/instant-loans/actor\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport {\n buildActivitiesPath,\n buildActivityStatusPath,\n} from \"../../core/sdk-api-paths\";\nimport type { ApiClient } from \"../../core/transports/api-client\";\nimport type { CanisterContext } from \"../../core/transports/canister-context\";\nimport { Chain } from \"../../core/types\";\nimport { parseBigInt } from \"../../core/utils/bigint\";\nimport { intFromPublicId } from \"../instant-loans/ref-code\";\nimport type {\n Activity,\n ActivityStatus,\n ActivityTopUp,\n GetActivityStatusRequest,\n GetActivityStatusResponse,\n InflowActivityKind,\n InflowActivityStatus,\n ListActivitiesRequest,\n OutflowActivityKind,\n OutflowActivityStatus,\n} from \"./types\";\nimport { ActivityDirection, ActivityFilter } from \"./types\";\n\nconst PRE_TERMINAL_ETH_ACTIVITY_ID_PREFIX = \"pre_terminal_eth_\";\n\ntype ActivityTopUpWire = Omit<\n ActivityTopUp,\n \"depositedAmount\" | \"feeAmount\" | \"shortfallAmount\"\n> & {\n depositedAmount: string;\n feeAmount: string;\n shortfallAmount: string;\n};\n\ntype ActivityWireStatus =\n | \"requested\"\n | \"pending\"\n | \"sent\"\n | \"confirmed\"\n | \"failed\";\n\ntype ActivityWireStage =\n | \"logged\"\n | \"deposited\"\n | \"confirmed\"\n | \"pending\"\n | \"finalising\";\n\ntype ActivityWire = {\n id: string;\n direction: Activity[\"direction\"];\n kind: Activity[\"kind\"];\n poolId: string;\n asset: string | null;\n chain: Chain | null;\n amount: string;\n timestampMs: number;\n txid: string | null;\n txids?: string[];\n confirmations: number | null;\n requiredConfirmations: number | null;\n status: ActivityWireStatus;\n stage?: ActivityWireStage;\n topUp?: ActivityTopUpWire;\n};\n\ntype ListActivitiesResponseWire = {\n success: true;\n activities: ActivityWire[];\n};\n\ntype ActivityStatusResponseWire =\n | {\n success: true;\n found: true;\n activity: ActivityWire;\n }\n | {\n success: true;\n found: false;\n id: string;\n };\n\n/** Receipt-oriented activity list and status helpers. */\nexport class ActivitiesModule {\n constructor(\n readonly apiClient: ApiClient | undefined,\n readonly canisterContext: CanisterContext\n ) {}\n\n /**\n * Lists profile activities. Defaults to all activities.\n *\n * Uses the Liquidium SDK API.\n *\n * @param request - Profile id or instant-loan short reference plus optional state filter.\n * @returns Activities owned by the resolved profile.\n */\n async list(request: ListActivitiesRequest): Promise<Activity[]> {\n const apiClient = this.requireApi();\n const profileId = await this.resolveProfileId(request);\n const response = await apiClient.get<ListActivitiesResponseWire>(\n buildActivitiesPath({\n profileId,\n state: request.filter ?? ActivityFilter.all,\n })\n );\n\n return response.activities.map(mapActivity);\n }\n\n /**\n * Fetches the latest status for a single receipt/activity id.\n *\n * Uses the Liquidium SDK API.\n *\n * @param request - Activity id plus profile id or instant-loan short reference.\n * @returns The activity when found, otherwise `{ found: false }` with the requested id.\n */\n async getStatus(\n request: GetActivityStatusRequest\n ): Promise<GetActivityStatusResponse> {\n const apiClient = this.requireApi();\n const profileId = await this.resolveProfileId(request);\n const response = await apiClient.get<ActivityStatusResponseWire>(\n buildActivityStatusPath({ id: request.id, profileId })\n );\n\n if (!response.found) {\n return { found: false, id: response.id };\n }\n\n return {\n found: true,\n activity: mapActivity(response.activity),\n };\n }\n\n private requireApi(): ApiClient {\n if (!this.apiClient) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Activities require an API client\"\n );\n }\n\n return this.apiClient;\n }\n\n private async resolveProfileId(\n request: GetActivityStatusRequest | ListActivitiesRequest\n ): Promise<string> {\n if (\"profileId\" in request) {\n return request.profileId;\n }\n\n let loanId: bigint;\n try {\n loanId = intFromPublicId(request.shortRef.trim());\n } catch (error) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Invalid instant loan reference\",\n error\n );\n }\n\n try {\n const result = await createInstantLoansActor(\n this.canisterContext\n ).get_loan(loanId);\n\n if (\"Err\" in result) {\n throw mapInstantLoanLookupError(result.Err);\n }\n\n return result.Ok.lending_profile.toText();\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.CANISTER_REJECTED,\n \"Unable to resolve instant loan reference\",\n error\n );\n }\n }\n}\n\nfunction mapInstantLoanLookupError(\n error: InstantLoansCanisterError\n): LiquidiumError {\n const [key] = Object.entries(error)[0] ?? [\"Unknown\"];\n\n if (key === \"LoanNotFound\") {\n return new LiquidiumError(\n LiquidiumErrorCode.POSITION_NOT_FOUND,\n \"Instant loan not found\"\n );\n }\n\n return new LiquidiumError(LiquidiumErrorCode.INTERNAL, key);\n}\n\nfunction mapActivity(wire: ActivityWire): Activity {\n const { amount, stage, status, topUp: topUpWire, ...activity } = wire;\n const effectiveStage = stage ?? deriveActivityStage(wire);\n const topUp =\n activity.direction === ActivityDirection.inflow && topUpWire\n ? mapActivityTopUp(topUpWire)\n : undefined;\n\n if (activity.direction === ActivityDirection.inflow) {\n return {\n ...activity,\n direction: ActivityDirection.inflow,\n kind: mapInflowActivityKind(activity.kind),\n status: mapInflowActivityStatus(\n mapActivityStatus(status, effectiveStage)\n ),\n ...(topUp ? { topUp } : {}),\n amount: parseBigInt(amount, \"activity amount\"),\n };\n }\n\n return {\n ...activity,\n direction: ActivityDirection.outflow,\n kind: mapOutflowActivityKind(activity.kind),\n status: mapOutflowActivityStatus(mapActivityStatus(status, effectiveStage)),\n amount: parseBigInt(amount, \"activity amount\"),\n };\n}\n\nfunction mapInflowActivityKind(kind: Activity[\"kind\"]): InflowActivityKind {\n if (kind === \"deposit\" || kind === \"repayment\") {\n return kind;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Invalid inflow activity kind: ${kind}`\n );\n}\n\nfunction mapOutflowActivityKind(kind: Activity[\"kind\"]): OutflowActivityKind {\n if (kind === \"borrow\" || kind === \"withdraw\") {\n return kind;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Invalid outflow activity kind: ${kind}`\n );\n}\n\nfunction mapInflowActivityStatus(status: ActivityStatus): InflowActivityStatus {\n if (status !== \"sent\") {\n return status;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Invalid inflow activity status: ${status}`\n );\n}\n\nfunction mapOutflowActivityStatus(\n status: ActivityStatus\n): OutflowActivityStatus {\n if (status !== \"detected\" && status !== \"processing\") {\n return status;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Invalid outflow activity status: ${status}`\n );\n}\n\nfunction mapActivityStatus(\n status: ActivityWireStatus,\n stage: ActivityWireStage | undefined\n): ActivityStatus {\n if (status !== \"pending\") {\n return status;\n }\n\n if (stage === \"deposited\") {\n return \"detected\";\n }\n\n if (stage === \"confirmed\" || stage === \"finalising\" || stage === \"pending\") {\n return \"processing\";\n }\n\n return \"pending\";\n}\n\nfunction mapActivityTopUp(wire: ActivityTopUpWire): ActivityTopUp {\n return {\n required: wire.required,\n depositedAmount: parseBigInt(\n wire.depositedAmount,\n \"activity top-up deposited amount\"\n ),\n feeAmount: parseBigInt(wire.feeAmount, \"activity top-up fee amount\"),\n shortfallAmount: parseBigInt(\n wire.shortfallAmount,\n \"activity top-up shortfall amount\"\n ),\n };\n}\n\nfunction deriveActivityStage(\n wire: ActivityWire\n): ActivityWireStage | undefined {\n if (\n wire.id.startsWith(PRE_TERMINAL_ETH_ACTIVITY_ID_PREFIX) &&\n wire.direction === ActivityDirection.inflow &&\n wire.chain === Chain.ETH\n ) {\n return \"deposited\";\n }\n\n return undefined;\n}\n","/** Fixed-point scale used by protocol rate values. */\nexport const RATE_SCALE = 1_000_000_000_000_000_000_000_000_000n;\n/** Number of decimal places represented by {@link RATE_SCALE}. */\nexport const RATE_DECIMALS = BigInt(RATE_SCALE.toString().length - 1);\n","/** Consumer-facing status for profile transaction history entries. */\nexport const UserHistoryStatus = {\n requested: \"requested\",\n pending: \"pending\",\n confirmed: \"confirmed\",\n failed: \"failed\",\n} as const;\n/** Consumer-facing status for profile transaction history entries. */\nexport type UserHistoryStatus =\n (typeof UserHistoryStatus)[keyof typeof UserHistoryStatus];\n/** Uppercase status value used by SDK API responses. */\nexport type UserHistoryStatusApi = Uppercase<UserHistoryStatus>;\n\n/** User transaction kinds returned by profile transaction history. */\nexport type UserTransactionHistoryType =\n | \"supply\"\n | \"borrow\"\n | \"repay\"\n | \"withdraw\";\n/** User liquidation history kind. */\nexport type UserLiquidationHistoryType = \"liquidation\";\n/** Any user history kind returned by the history API. */\nexport type UserHistoryType =\n | UserTransactionHistoryType\n | UserLiquidationHistoryType;\n\ninterface BaseUserHistoryEntry {\n id: string;\n amount: bigint;\n poolId: string;\n timestamp: string;\n txids?: string[];\n}\n\n/** Supply, borrow, repay, or withdraw entry in user history. */\nexport interface UserTransactionHistoryEntry extends BaseUserHistoryEntry {\n /** Transaction history kind. */\n type: UserTransactionHistoryType;\n /** Current lifecycle status. */\n status: UserHistoryStatus;\n}\n\n/** Liquidation entry in user history. */\nexport interface UserLiquidationHistoryEntry extends BaseUserHistoryEntry {\n /** Liquidation kind discriminator. */\n type: UserLiquidationHistoryType;\n /** Liquidations are only returned once confirmed. */\n status: typeof UserHistoryStatus.confirmed;\n}\n\n/** Any consumer-facing profile history entry. */\nexport type UserHistoryEntry =\n | UserTransactionHistoryEntry\n | UserLiquidationHistoryEntry;\n\n/** Filters for profile transaction history requests. */\nexport interface UserTransactionHistoryFilters {\n /** Pagination cursor from a previous response. */\n cursor?: string;\n /** Maximum number of entries to return. */\n limit?: number;\n /** Market filter accepted by the SDK API. */\n market?: string;\n /** Pool principal text filter. */\n poolId?: string;\n /** Transaction kind filters. */\n types?: UserTransactionHistoryType[];\n /** Status filters. */\n statuses?: UserHistoryEntry[\"status\"][];\n /** Inclusive start timestamp filter accepted by the SDK API. */\n from?: string;\n /** Inclusive end timestamp filter accepted by the SDK API. */\n to?: string;\n}\n\n/** Filters for profile liquidation history requests. */\nexport interface UserLiquidationHistoryFilters {\n /** Pagination cursor from a previous response. */\n cursor?: string;\n /** Maximum number of entries to return. */\n limit?: number;\n /** Market filter accepted by the SDK API. */\n market?: string;\n /** Pool principal text filter. */\n poolId?: string;\n /** Inclusive start timestamp filter accepted by the SDK API. */\n from?: string;\n /** Inclusive end timestamp filter accepted by the SDK API. */\n to?: string;\n}\n\n/** Backwards-compatible alias for user transaction history filters. */\nexport type ActivitiesRequest = UserTransactionHistoryFilters;\n\n/** Time-window and pagination options for borrow APY history. */\nexport interface BorrowApyHistoryRequest {\n /** Pagination cursor from a previous response. */\n cursor?: string;\n /** Maximum number of samples to return. */\n limit?: number;\n /** Inclusive start timestamp filter accepted by the SDK API. */\n from?: string;\n /** Inclusive end timestamp filter accepted by the SDK API. */\n to?: string;\n}\n\n/** Time-window and pagination options for pool rate history. */\nexport type PoolHistoryRequest = BorrowApyHistoryRequest;\n\n/** Borrow APY sample returned to SDK consumers. */\nexport interface ApySample {\n /** Sample date from the SDK API. */\n date: string;\n /** Decimal scale for `avgRate`. */\n rateDecimals: bigint;\n /** Average borrow rate for the sample, scaled by `rateDecimals`. */\n avgRate: bigint;\n}\n\n/** Wire-format borrow APY sample returned by the SDK API. */\nexport interface ApySampleApiItem {\n date: string;\n rateDecimals: number;\n avgRate: string;\n}\n\n/** Wire-format borrow rate history response returned by the SDK API. */\nexport interface BorrowRateHistoryResponse {\n success: true;\n items: ApySampleApiItem[];\n nextCursor?: string;\n}\n\n/** Wire-format user history item returned by the SDK API. */\nexport interface UserHistoryEntryApiItem {\n id: string;\n type: UserHistoryType;\n amount: string;\n poolId: string;\n timestamp: string;\n status: UserHistoryStatusApi;\n txids?: string[];\n}\n\n/** Wire-format user history page returned by the SDK API. */\nexport interface UserHistoryResponse {\n success: true;\n items: UserHistoryEntryApiItem[];\n nextCursor?: string;\n}\n\n/** Pool rate and utilization history entry returned to SDK consumers. */\nexport interface PoolHistoryEntry {\n /** Sample date from the SDK API. */\n date: string;\n /** Decimal scale for rate fields. */\n rateDecimals: bigint;\n /** Average borrow rate for the sample, scaled by `rateDecimals`. */\n avgBorrowRate: bigint;\n /** Average lend rate for the sample, scaled by `rateDecimals`. */\n avgLendRate: bigint;\n /** Average utilization rate for the sample, scaled by `rateDecimals`. */\n avgUtilizationRate: bigint;\n}\n\n/** Wire-format pool rate history item returned by the SDK API. */\nexport interface PoolHistoryEntryApiItem {\n date: string;\n rateDecimals: number;\n avgBorrowRate: string;\n avgLendRate: string;\n avgUtilizationRate: string;\n}\n\n/** Wire-format pool rate history page returned by the SDK API. */\nexport interface PoolHistoryResponse {\n success: true;\n items: PoolHistoryEntryApiItem[];\n nextCursor?: string;\n}\n\n/** Pool configuration snapshot returned to SDK consumers. */\nexport interface PoolConfigHistoryEntry {\n type: \"configuration_change\";\n poolId: string;\n asset: string;\n chain: string;\n timestamp: string;\n totalSupply: bigint;\n totalDebt: bigint;\n supplyCap?: bigint;\n borrowCap?: bigint;\n maxLtv: bigint;\n liquidationThreshold: bigint;\n liquidationBonus: bigint;\n protocolLiquidationFee: bigint;\n reserveFactor: bigint;\n baseRate: bigint;\n optimalUtilizationRate: bigint;\n rateSlopeBefore: bigint;\n rateSlopeAfter: bigint;\n lendingIndex: bigint;\n borrowIndex: bigint;\n sameAssetBorrowing: boolean;\n frozen: boolean;\n}\n\n/** Wire-format pool configuration history item returned by the SDK API. */\nexport interface PoolConfigHistoryEntryApiItem {\n type: \"configuration_change\";\n poolId: string;\n asset: string;\n chain: string;\n timestamp: string;\n totalSupply: string;\n totalDebt: string;\n supplyCap?: string;\n borrowCap?: string;\n maxLtv: string;\n liquidationThreshold: string;\n liquidationBonus: string;\n protocolLiquidationFee: string;\n reserveFactor: string;\n baseRate: string;\n optimalUtilizationRate: string;\n rateSlopeBefore: string;\n rateSlopeAfter: string;\n lendingIndex: string;\n borrowIndex: string;\n sameAssetBorrowing: boolean;\n frozen: boolean;\n}\n\n/** Wire-format pool configuration history page returned by the SDK API. */\nexport interface PoolConfigHistoryResponse {\n success: true;\n items: PoolConfigHistoryEntryApiItem[];\n nextCursor?: string;\n}\n\n/** Any history entry returned by history module methods. */\nexport type HistoryEntry =\n | UserHistoryEntry\n | PoolHistoryEntry\n | PoolConfigHistoryEntry;\n\n/** Generic SDK API paginated response. */\nexport interface PaginatedResponse<T> {\n /** Items in the current page. */\n items: T[];\n /** Cursor for the next page when more results are available. */\n nextCursor?: string;\n}\n","import { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport { RATE_DECIMALS } from \"../../core/rates\";\nimport {\n buildHistoryPoolConfigPath,\n buildHistoryPoolPath,\n buildHistoryRatesPath,\n buildHistoryUserLiquidationsPath,\n buildHistoryUserTransactionsPath,\n SdkApiQueryParam,\n} from \"../../core/sdk-api-paths\";\nimport type { ApiClient } from \"../../core/transports/api-client\";\nimport { parseBigInt, parseOptionalBigInt } from \"../../core/utils/bigint\";\nimport type {\n ApySample,\n BorrowApyHistoryRequest,\n BorrowRateHistoryResponse,\n PaginatedResponse,\n PoolConfigHistoryEntry,\n PoolConfigHistoryResponse,\n PoolHistoryEntry,\n PoolHistoryRequest,\n PoolHistoryResponse,\n UserHistoryEntry,\n UserHistoryResponse,\n UserHistoryStatusApi,\n UserLiquidationHistoryEntry,\n UserLiquidationHistoryFilters,\n UserTransactionHistoryEntry,\n UserTransactionHistoryFilters,\n UserTransactionHistoryType,\n} from \"./types\";\nimport { UserHistoryStatus } from \"./types\";\n\n/** Historical pool, rate, user transaction, and liquidation data helpers. */\nexport class HistoryModule {\n constructor(readonly apiClient: ApiClient | undefined) {}\n\n private requireApi(): ApiClient {\n if (!this.apiClient) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"History requires an API client\"\n );\n }\n\n return this.apiClient;\n }\n\n /**\n * Returns paginated rate and utilization history for a pool.\n *\n * @param poolId - The pool principal text.\n * @param window - Optional time window with from/to timestamps and limit.\n * @returns A page of pool rate history entries and the next cursor when more results are available.\n */\n async getPoolHistory(\n poolId: string,\n window: PoolHistoryRequest = {}\n ): Promise<PaginatedResponse<PoolHistoryEntry>> {\n const apiClient = this.requireApi();\n const query = createHistoryWindowQuery(window);\n const requestPath = buildHistoryPoolPath(poolId, query);\n const response = await apiClient.get<PoolHistoryResponse>(requestPath);\n\n return {\n items: response.items.map((item) => ({\n date: item.date,\n rateDecimals: RATE_DECIMALS,\n avgBorrowRate: parseBigInt(item.avgBorrowRate, \"pool borrow rate\"),\n avgLendRate: parseBigInt(item.avgLendRate, \"pool lend rate\"),\n avgUtilizationRate: parseBigInt(\n item.avgUtilizationRate,\n \"pool utilization rate\"\n ),\n })),\n nextCursor: response.nextCursor,\n };\n }\n\n /**\n * Returns paginated configuration change history for a pool.\n *\n * @param poolId - The pool principal text.\n * @param cursor - An optional pagination cursor from a previous response.\n * @returns A page of pool configuration changes and the next cursor when more results are available.\n */\n async getPoolConfigHistory(\n poolId: string,\n cursor?: string\n ): Promise<PaginatedResponse<PoolConfigHistoryEntry>> {\n const apiClient = this.requireApi();\n const requestPath = buildHistoryPoolConfigPath(poolId, cursor);\n const response =\n await apiClient.get<PoolConfigHistoryResponse>(requestPath);\n\n return {\n items: response.items.map((item) => ({\n type: item.type,\n poolId: item.poolId,\n asset: item.asset,\n chain: item.chain,\n timestamp: item.timestamp,\n totalSupply: parseBigInt(item.totalSupply, \"pool history totalSupply\"),\n totalDebt: parseBigInt(item.totalDebt, \"pool history totalDebt\"),\n supplyCap: parseOptionalBigInt(\n item.supplyCap,\n \"pool history supplyCap\"\n ),\n borrowCap: parseOptionalBigInt(\n item.borrowCap,\n \"pool history borrowCap\"\n ),\n maxLtv: parseBigInt(item.maxLtv, \"pool history maxLtv\"),\n liquidationThreshold: parseBigInt(\n item.liquidationThreshold,\n \"pool history liquidationThreshold\"\n ),\n liquidationBonus: parseBigInt(\n item.liquidationBonus,\n \"pool history liquidationBonus\"\n ),\n protocolLiquidationFee: parseBigInt(\n item.protocolLiquidationFee,\n \"pool history protocolLiquidationFee\"\n ),\n reserveFactor: parseBigInt(\n item.reserveFactor,\n \"pool history reserveFactor\"\n ),\n baseRate: parseBigInt(item.baseRate, \"pool history baseRate\"),\n optimalUtilizationRate: parseBigInt(\n item.optimalUtilizationRate,\n \"pool history optimalUtilizationRate\"\n ),\n rateSlopeBefore: parseBigInt(\n item.rateSlopeBefore,\n \"pool history rateSlopeBefore\"\n ),\n rateSlopeAfter: parseBigInt(\n item.rateSlopeAfter,\n \"pool history rateSlopeAfter\"\n ),\n lendingIndex: parseBigInt(\n item.lendingIndex,\n \"pool history lendingIndex\"\n ),\n borrowIndex: parseBigInt(item.borrowIndex, \"pool history borrowIndex\"),\n sameAssetBorrowing: item.sameAssetBorrowing,\n frozen: item.frozen,\n })),\n nextCursor: response.nextCursor,\n };\n }\n\n /**\n * Returns borrow rate history for a pool.\n *\n * @param poolId - The pool principal text.\n * @param window - Optional time window with from/to timestamps and limit.\n * @returns Paginated APY samples.\n */\n async getBorrowRateHistory(\n poolId: string,\n window: BorrowApyHistoryRequest = {}\n ): Promise<PaginatedResponse<ApySample>> {\n const apiClient = this.requireApi();\n const query = createHistoryWindowQuery(window);\n\n const requestPath = buildHistoryRatesPath(poolId, query);\n const response =\n await apiClient.get<BorrowRateHistoryResponse>(requestPath);\n\n return {\n items: response.items.map((item) => ({\n date: item.date,\n rateDecimals: RATE_DECIMALS,\n avgRate: parseBigInt(item.avgRate, \"borrow rate\"),\n })),\n nextCursor: response.nextCursor,\n };\n }\n\n /**\n * Returns transaction history for a user.\n *\n * @param user - The Liquidium profile principal text.\n * @param filters - Optional pool, type, status, time range, and pagination filters.\n * @returns Paginated user history entries.\n */\n async getUserTransactionHistory(\n user: string,\n filters?: UserTransactionHistoryFilters\n ): Promise<PaginatedResponse<UserTransactionHistoryEntry>>;\n async getUserTransactionHistory(\n user: string,\n market?: string,\n filters?: UserTransactionHistoryFilters\n ): Promise<PaginatedResponse<UserTransactionHistoryEntry>>;\n async getUserTransactionHistory(\n user: string,\n marketOrFilters?: string | UserTransactionHistoryFilters,\n filters: UserTransactionHistoryFilters = {}\n ): Promise<PaginatedResponse<UserTransactionHistoryEntry>> {\n const apiClient = this.requireApi();\n const normalizedFilters = normalizeTransactionHistoryFilters(\n marketOrFilters,\n filters\n );\n const query = new URLSearchParams();\n\n if (normalizedFilters.cursor) {\n query.set(SdkApiQueryParam.cursor, normalizedFilters.cursor);\n }\n if (normalizedFilters.market) {\n query.set(SdkApiQueryParam.market, normalizedFilters.market);\n }\n if (normalizedFilters.poolId) {\n query.set(SdkApiQueryParam.poolId, normalizedFilters.poolId);\n }\n if (normalizedFilters.types?.length) {\n query.set(SdkApiQueryParam.types, normalizedFilters.types.join(\",\"));\n }\n if (normalizedFilters.statuses?.length) {\n query.set(\n SdkApiQueryParam.statuses,\n normalizedFilters.statuses.map(mapHistoryStatusToApi).join(\",\")\n );\n }\n if (normalizedFilters.from) {\n query.set(SdkApiQueryParam.from, normalizedFilters.from);\n }\n if (normalizedFilters.to) {\n query.set(SdkApiQueryParam.to, normalizedFilters.to);\n }\n if (normalizedFilters.limit !== undefined) {\n query.set(SdkApiQueryParam.limit, String(normalizedFilters.limit));\n }\n\n const requestPath = buildHistoryUserTransactionsPath(user, query);\n const response = await apiClient.get<UserHistoryResponse>(requestPath);\n\n return {\n items: response.items.map(mapUserTransactionHistoryEntry),\n nextCursor: response.nextCursor,\n };\n }\n\n /**\n * Returns liquidation history for a user.\n *\n * @param user - The Liquidium profile principal text.\n * @param filters - Optional pool, time range, and pagination filters.\n * @returns Paginated liquidation history entries.\n */\n async getLiquidationHistory(\n user: string,\n filters?: UserLiquidationHistoryFilters\n ): Promise<PaginatedResponse<UserLiquidationHistoryEntry>>;\n async getLiquidationHistory(\n user: string,\n market?: string,\n filters?: UserLiquidationHistoryFilters\n ): Promise<PaginatedResponse<UserLiquidationHistoryEntry>>;\n async getLiquidationHistory(\n user: string,\n marketOrFilters?: string | UserLiquidationHistoryFilters,\n filters: UserLiquidationHistoryFilters = {}\n ): Promise<PaginatedResponse<UserLiquidationHistoryEntry>> {\n const apiClient = this.requireApi();\n const normalizedFilters = normalizeLiquidationHistoryFilters(\n marketOrFilters,\n filters\n );\n const query = new URLSearchParams();\n if (normalizedFilters.cursor) {\n query.set(SdkApiQueryParam.cursor, normalizedFilters.cursor);\n }\n if (normalizedFilters.market) {\n query.set(SdkApiQueryParam.market, normalizedFilters.market);\n }\n if (normalizedFilters.poolId) {\n query.set(SdkApiQueryParam.poolId, normalizedFilters.poolId);\n }\n if (normalizedFilters.from) {\n query.set(SdkApiQueryParam.from, normalizedFilters.from);\n }\n if (normalizedFilters.to) {\n query.set(SdkApiQueryParam.to, normalizedFilters.to);\n }\n if (normalizedFilters.limit !== undefined) {\n query.set(SdkApiQueryParam.limit, String(normalizedFilters.limit));\n }\n\n const requestPath = buildHistoryUserLiquidationsPath(user, query);\n const response = await apiClient.get<UserHistoryResponse>(requestPath);\n\n return {\n items: response.items.map(mapUserLiquidationHistoryEntry),\n nextCursor: response.nextCursor,\n };\n }\n}\n\nfunction mapUserTransactionHistoryEntry(\n item: UserHistoryResponse[\"items\"][number]\n): UserTransactionHistoryEntry {\n return {\n id: item.id,\n type: mapUserTransactionHistoryType(item.type),\n amount: parseBigInt(item.amount, \"history user amount\"),\n poolId: item.poolId,\n timestamp: item.timestamp,\n status: mapHistoryStatusFromApi(item.status),\n txids: item.txids,\n };\n}\n\nfunction mapUserLiquidationHistoryEntry(\n item: UserHistoryResponse[\"items\"][number]\n): UserLiquidationHistoryEntry {\n if (item.type !== \"liquidation\") {\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Invalid liquidation history type: ${item.type}`\n );\n }\n\n return {\n id: item.id,\n type: \"liquidation\",\n amount: parseBigInt(item.amount, \"history user amount\"),\n poolId: item.poolId,\n timestamp: item.timestamp,\n status: mapLiquidationHistoryStatus(item.status),\n txids: item.txids,\n };\n}\n\nfunction mapUserTransactionHistoryType(\n type: UserHistoryEntry[\"type\"]\n): UserTransactionHistoryType {\n if (type !== \"liquidation\") {\n return type;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n \"Transaction history response included a liquidation entry\"\n );\n}\n\nfunction mapLiquidationHistoryStatus(\n status: UserHistoryStatusApi\n): typeof UserHistoryStatus.confirmed {\n const mappedStatus = mapHistoryStatusFromApi(status);\n\n if (mappedStatus === UserHistoryStatus.confirmed) {\n return mappedStatus;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Invalid liquidation history status: ${status}`\n );\n}\n\nfunction createHistoryWindowQuery(\n window: BorrowApyHistoryRequest\n): URLSearchParams {\n const query = new URLSearchParams();\n if (window.cursor) query.set(SdkApiQueryParam.cursor, window.cursor);\n if (window.from) query.set(SdkApiQueryParam.from, window.from);\n if (window.to) query.set(SdkApiQueryParam.to, window.to);\n if (window.limit !== undefined) {\n query.set(SdkApiQueryParam.limit, String(window.limit));\n }\n\n return query;\n}\n\nfunction normalizeTransactionHistoryFilters(\n marketOrFilters: string | UserTransactionHistoryFilters | undefined,\n filters: UserTransactionHistoryFilters\n): UserTransactionHistoryFilters {\n if (typeof marketOrFilters === \"string\") {\n return { ...filters, market: marketOrFilters };\n }\n\n return { ...(marketOrFilters ?? {}), ...filters };\n}\n\nfunction normalizeLiquidationHistoryFilters(\n marketOrFilters: string | UserLiquidationHistoryFilters | undefined,\n filters: UserLiquidationHistoryFilters\n): UserLiquidationHistoryFilters {\n if (typeof marketOrFilters === \"string\") {\n return { ...filters, market: marketOrFilters };\n }\n\n return { ...(marketOrFilters ?? {}), ...filters };\n}\n\nfunction mapHistoryStatusFromApi(\n status: UserHistoryStatusApi\n): UserHistoryStatus {\n return status.toLowerCase() as UserHistoryStatus;\n}\n\nfunction mapHistoryStatusToApi(\n status: UserHistoryStatus\n): UserHistoryStatusApi {\n return status.toUpperCase() as UserHistoryStatusApi;\n}\n","export const idlFactory = ({ IDL }) => {\n const Mode = IDL.Variant({\n 'RestrictedTo' : IDL.Vec(IDL.Principal),\n 'DepositsRestrictedTo' : IDL.Vec(IDL.Principal),\n 'ReadOnly' : IDL.Null,\n 'GeneralAvailability' : IDL.Null,\n });\n const UpgradeArgs = IDL.Record({\n 'get_utxos_cache_expiration_seconds' : IDL.Opt(IDL.Nat64),\n 'kyt_principal' : IDL.Opt(IDL.Principal),\n 'mode' : IDL.Opt(Mode),\n 'retrieve_btc_min_amount' : IDL.Opt(IDL.Nat64),\n 'max_time_in_queue_nanos' : IDL.Opt(IDL.Nat64),\n 'check_fee' : IDL.Opt(IDL.Nat64),\n 'btc_checker_principal' : IDL.Opt(IDL.Principal),\n 'min_confirmations' : IDL.Opt(IDL.Nat32),\n 'kyt_fee' : IDL.Opt(IDL.Nat64),\n });\n const BtcNetwork = IDL.Variant({\n 'Mainnet' : IDL.Null,\n 'Regtest' : IDL.Null,\n 'Testnet' : IDL.Null,\n });\n const InitArgs = IDL.Record({\n 'get_utxos_cache_expiration_seconds' : IDL.Opt(IDL.Nat64),\n 'kyt_principal' : IDL.Opt(IDL.Principal),\n 'ecdsa_key_name' : IDL.Text,\n 'mode' : Mode,\n 'retrieve_btc_min_amount' : IDL.Nat64,\n 'ledger_id' : IDL.Principal,\n 'max_time_in_queue_nanos' : IDL.Nat64,\n 'btc_network' : BtcNetwork,\n 'check_fee' : IDL.Opt(IDL.Nat64),\n 'btc_checker_principal' : IDL.Opt(IDL.Principal),\n 'min_confirmations' : IDL.Opt(IDL.Nat32),\n 'kyt_fee' : IDL.Opt(IDL.Nat64),\n });\n const MinterArg = IDL.Variant({\n 'Upgrade' : IDL.Opt(UpgradeArgs),\n 'Init' : InitArgs,\n });\n const CanisterStatusType = IDL.Variant({\n 'stopped' : IDL.Null,\n 'stopping' : IDL.Null,\n 'running' : IDL.Null,\n });\n const LogVisibility = IDL.Variant({\n 'controllers' : IDL.Null,\n 'public' : IDL.Null,\n 'allowed_viewers' : IDL.Vec(IDL.Principal),\n });\n const DefiniteCanisterSettings = IDL.Record({\n 'freezing_threshold' : IDL.Nat,\n 'controllers' : IDL.Vec(IDL.Principal),\n 'reserved_cycles_limit' : IDL.Nat,\n 'log_visibility' : LogVisibility,\n 'wasm_memory_limit' : IDL.Nat,\n 'memory_allocation' : IDL.Nat,\n 'compute_allocation' : IDL.Nat,\n });\n const QueryStats = IDL.Record({\n 'response_payload_bytes_total' : IDL.Nat,\n 'num_instructions_total' : IDL.Nat,\n 'num_calls_total' : IDL.Nat,\n 'request_payload_bytes_total' : IDL.Nat,\n });\n const CanisterStatusResponse = IDL.Record({\n 'status' : CanisterStatusType,\n 'memory_size' : IDL.Nat,\n 'cycles' : IDL.Nat,\n 'settings' : DefiniteCanisterSettings,\n 'query_stats' : QueryStats,\n 'idle_cycles_burned_per_day' : IDL.Nat,\n 'module_hash' : IDL.Opt(IDL.Vec(IDL.Nat8)),\n 'reserved_cycles' : IDL.Nat,\n });\n const Account = IDL.Record({\n 'owner' : IDL.Principal,\n 'subaccount' : IDL.Opt(IDL.Vec(IDL.Nat8)),\n });\n const Utxo = IDL.Record({\n 'height' : IDL.Nat32,\n 'value' : IDL.Nat64,\n 'outpoint' : IDL.Record({ 'txid' : IDL.Vec(IDL.Nat8), 'vout' : IDL.Nat32 }),\n });\n const ReimbursementReason = IDL.Variant({\n 'CallFailed' : IDL.Null,\n 'TaintedDestination' : IDL.Record({\n 'kyt_fee' : IDL.Nat64,\n 'kyt_provider' : IDL.Principal,\n }),\n });\n const SuspendedReason = IDL.Variant({\n 'ValueTooSmall' : IDL.Null,\n 'Quarantined' : IDL.Null,\n });\n const BitcoinAddress = IDL.Variant({\n 'p2wsh_v0' : IDL.Vec(IDL.Nat8),\n 'p2tr_v1' : IDL.Vec(IDL.Nat8),\n 'p2sh' : IDL.Vec(IDL.Nat8),\n 'p2wpkh_v0' : IDL.Vec(IDL.Nat8),\n 'p2pkh' : IDL.Vec(IDL.Nat8),\n });\n const EventType = IDL.Variant({\n 'received_utxos' : IDL.Record({\n 'to_account' : Account,\n 'mint_txid' : IDL.Opt(IDL.Nat64),\n 'utxos' : IDL.Vec(Utxo),\n }),\n 'schedule_deposit_reimbursement' : IDL.Record({\n 'burn_block_index' : IDL.Nat64,\n 'account' : Account,\n 'amount' : IDL.Nat64,\n 'reason' : ReimbursementReason,\n }),\n 'sent_transaction' : IDL.Record({\n 'fee' : IDL.Opt(IDL.Nat64),\n 'change_output' : IDL.Opt(\n IDL.Record({ 'value' : IDL.Nat64, 'vout' : IDL.Nat32 })\n ),\n 'txid' : IDL.Vec(IDL.Nat8),\n 'utxos' : IDL.Vec(Utxo),\n 'requests' : IDL.Vec(IDL.Nat64),\n 'submitted_at' : IDL.Nat64,\n }),\n 'distributed_kyt_fee' : IDL.Record({\n 'block_index' : IDL.Nat64,\n 'amount' : IDL.Nat64,\n 'kyt_provider' : IDL.Principal,\n }),\n 'init' : InitArgs,\n 'upgrade' : UpgradeArgs,\n 'retrieve_btc_kyt_failed' : IDL.Record({\n 'block_index' : IDL.Nat64,\n 'owner' : IDL.Principal,\n 'uuid' : IDL.Text,\n 'address' : IDL.Text,\n 'amount' : IDL.Nat64,\n 'kyt_provider' : IDL.Principal,\n }),\n 'suspended_utxo' : IDL.Record({\n 'utxo' : Utxo,\n 'account' : Account,\n 'reason' : SuspendedReason,\n }),\n 'accepted_retrieve_btc_request' : IDL.Record({\n 'received_at' : IDL.Nat64,\n 'block_index' : IDL.Nat64,\n 'address' : BitcoinAddress,\n 'reimbursement_account' : IDL.Opt(Account),\n 'amount' : IDL.Nat64,\n 'kyt_provider' : IDL.Opt(IDL.Principal),\n }),\n 'checked_utxo' : IDL.Record({\n 'clean' : IDL.Bool,\n 'utxo' : Utxo,\n 'uuid' : IDL.Text,\n 'kyt_provider' : IDL.Opt(IDL.Principal),\n }),\n 'removed_retrieve_btc_request' : IDL.Record({ 'block_index' : IDL.Nat64 }),\n 'confirmed_transaction' : IDL.Record({ 'txid' : IDL.Vec(IDL.Nat8) }),\n 'replaced_transaction' : IDL.Record({\n 'fee' : IDL.Nat64,\n 'change_output' : IDL.Record({ 'value' : IDL.Nat64, 'vout' : IDL.Nat32 }),\n 'old_txid' : IDL.Vec(IDL.Nat8),\n 'new_txid' : IDL.Vec(IDL.Nat8),\n 'submitted_at' : IDL.Nat64,\n }),\n 'checked_utxo_v2' : IDL.Record({ 'utxo' : Utxo, 'account' : Account }),\n 'ignored_utxo' : IDL.Record({ 'utxo' : Utxo }),\n 'checked_utxo_mint_unknown' : IDL.Record({\n 'utxo' : Utxo,\n 'account' : Account,\n }),\n 'reimbursed_failed_deposit' : IDL.Record({\n 'burn_block_index' : IDL.Nat64,\n 'mint_block_index' : IDL.Nat64,\n }),\n });\n const Event = IDL.Record({\n 'timestamp' : IDL.Opt(IDL.Nat64),\n 'payload' : EventType,\n });\n const MinterInfo = IDL.Record({\n 'retrieve_btc_min_amount' : IDL.Nat64,\n 'min_confirmations' : IDL.Nat32,\n 'kyt_fee' : IDL.Nat64,\n });\n const RetrieveBtcArgs = IDL.Record({\n 'address' : IDL.Text,\n 'amount' : IDL.Nat64,\n });\n const RetrieveBtcOk = IDL.Record({ 'block_index' : IDL.Nat64 });\n const RetrieveBtcError = IDL.Variant({\n 'MalformedAddress' : IDL.Text,\n 'GenericError' : IDL.Record({\n 'error_message' : IDL.Text,\n 'error_code' : IDL.Nat64,\n }),\n 'TemporarilyUnavailable' : IDL.Text,\n 'AlreadyProcessing' : IDL.Null,\n 'AmountTooLow' : IDL.Nat64,\n 'InsufficientFunds' : IDL.Record({ 'balance' : IDL.Nat64 }),\n });\n const RetrieveBtcStatus = IDL.Variant({\n 'Signing' : IDL.Null,\n 'Confirmed' : IDL.Record({ 'txid' : IDL.Vec(IDL.Nat8) }),\n 'Sending' : IDL.Record({ 'txid' : IDL.Vec(IDL.Nat8) }),\n 'AmountTooLow' : IDL.Null,\n 'Unknown' : IDL.Null,\n 'Submitted' : IDL.Record({ 'txid' : IDL.Vec(IDL.Nat8) }),\n 'Pending' : IDL.Null,\n });\n const ReimbursementRequest = IDL.Record({\n 'account' : Account,\n 'amount' : IDL.Nat64,\n 'reason' : ReimbursementReason,\n });\n const ReimbursedDeposit = IDL.Record({\n 'account' : Account,\n 'mint_block_index' : IDL.Nat64,\n 'amount' : IDL.Nat64,\n 'reason' : ReimbursementReason,\n });\n const RetrieveBtcStatusV2 = IDL.Variant({\n 'Signing' : IDL.Null,\n 'Confirmed' : IDL.Record({ 'txid' : IDL.Vec(IDL.Nat8) }),\n 'Sending' : IDL.Record({ 'txid' : IDL.Vec(IDL.Nat8) }),\n 'AmountTooLow' : IDL.Null,\n 'WillReimburse' : ReimbursementRequest,\n 'Unknown' : IDL.Null,\n 'Submitted' : IDL.Record({ 'txid' : IDL.Vec(IDL.Nat8) }),\n 'Reimbursed' : ReimbursedDeposit,\n 'Pending' : IDL.Null,\n });\n const RetrieveBtcWithApprovalArgs = IDL.Record({\n 'from_subaccount' : IDL.Opt(IDL.Vec(IDL.Nat8)),\n 'address' : IDL.Text,\n 'amount' : IDL.Nat64,\n });\n const RetrieveBtcWithApprovalError = IDL.Variant({\n 'MalformedAddress' : IDL.Text,\n 'GenericError' : IDL.Record({\n 'error_message' : IDL.Text,\n 'error_code' : IDL.Nat64,\n }),\n 'TemporarilyUnavailable' : IDL.Text,\n 'InsufficientAllowance' : IDL.Record({ 'allowance' : IDL.Nat64 }),\n 'AlreadyProcessing' : IDL.Null,\n 'AmountTooLow' : IDL.Nat64,\n 'InsufficientFunds' : IDL.Record({ 'balance' : IDL.Nat64 }),\n });\n const UtxoStatus = IDL.Variant({\n 'ValueTooSmall' : Utxo,\n 'Tainted' : Utxo,\n 'Minted' : IDL.Record({\n 'minted_amount' : IDL.Nat64,\n 'block_index' : IDL.Nat64,\n 'utxo' : Utxo,\n }),\n 'Checked' : Utxo,\n });\n const Timestamp = IDL.Nat64;\n const SuspendedUtxo = IDL.Record({\n 'utxo' : Utxo,\n 'earliest_retry' : Timestamp,\n 'reason' : SuspendedReason,\n });\n const PendingUtxo = IDL.Record({\n 'confirmations' : IDL.Nat32,\n 'value' : IDL.Nat64,\n 'outpoint' : IDL.Record({ 'txid' : IDL.Vec(IDL.Nat8), 'vout' : IDL.Nat32 }),\n });\n const UpdateBalanceError = IDL.Variant({\n 'GenericError' : IDL.Record({\n 'error_message' : IDL.Text,\n 'error_code' : IDL.Nat64,\n }),\n 'TemporarilyUnavailable' : IDL.Text,\n 'AlreadyProcessing' : IDL.Null,\n 'NoNewUtxos' : IDL.Record({\n 'suspended_utxos' : IDL.Opt(IDL.Vec(SuspendedUtxo)),\n 'required_confirmations' : IDL.Nat32,\n 'pending_utxos' : IDL.Opt(IDL.Vec(PendingUtxo)),\n 'current_confirmations' : IDL.Opt(IDL.Nat32),\n }),\n });\n return IDL.Service({\n 'estimate_withdrawal_fee' : IDL.Func(\n [IDL.Record({ 'amount' : IDL.Opt(IDL.Nat64) })],\n [IDL.Record({ 'minter_fee' : IDL.Nat64, 'bitcoin_fee' : IDL.Nat64 })],\n ['query'],\n ),\n 'get_btc_address' : IDL.Func(\n [\n IDL.Record({\n 'owner' : IDL.Opt(IDL.Principal),\n 'subaccount' : IDL.Opt(IDL.Vec(IDL.Nat8)),\n }),\n ],\n [IDL.Text],\n [],\n ),\n 'get_canister_status' : IDL.Func([], [CanisterStatusResponse], []),\n 'get_deposit_fee' : IDL.Func([], [IDL.Nat64], ['query']),\n 'get_events' : IDL.Func(\n [IDL.Record({ 'start' : IDL.Nat64, 'length' : IDL.Nat64 })],\n [IDL.Vec(Event)],\n ['query'],\n ),\n 'get_known_utxos' : IDL.Func(\n [\n IDL.Record({\n 'owner' : IDL.Opt(IDL.Principal),\n 'subaccount' : IDL.Opt(IDL.Vec(IDL.Nat8)),\n }),\n ],\n [IDL.Vec(Utxo)],\n ['query'],\n ),\n 'get_minter_info' : IDL.Func([], [MinterInfo], ['query']),\n 'get_withdrawal_account' : IDL.Func([], [Account], []),\n 'retrieve_btc' : IDL.Func(\n [RetrieveBtcArgs],\n [IDL.Variant({ 'Ok' : RetrieveBtcOk, 'Err' : RetrieveBtcError })],\n [],\n ),\n 'retrieve_btc_status' : IDL.Func(\n [IDL.Record({ 'block_index' : IDL.Nat64 })],\n [RetrieveBtcStatus],\n ['query'],\n ),\n 'retrieve_btc_status_v2' : IDL.Func(\n [IDL.Record({ 'block_index' : IDL.Nat64 })],\n [RetrieveBtcStatusV2],\n ['query'],\n ),\n 'retrieve_btc_status_v2_by_account' : IDL.Func(\n [IDL.Opt(Account)],\n [\n IDL.Vec(\n IDL.Record({\n 'block_index' : IDL.Nat64,\n 'status_v2' : IDL.Opt(RetrieveBtcStatusV2),\n })\n ),\n ],\n ['query'],\n ),\n 'retrieve_btc_with_approval' : IDL.Func(\n [RetrieveBtcWithApprovalArgs],\n [\n IDL.Variant({\n 'Ok' : RetrieveBtcOk,\n 'Err' : RetrieveBtcWithApprovalError,\n }),\n ],\n [],\n ),\n 'update_balance' : IDL.Func(\n [\n IDL.Record({\n 'owner' : IDL.Opt(IDL.Principal),\n 'subaccount' : IDL.Opt(IDL.Vec(IDL.Nat8)),\n }),\n ],\n [\n IDL.Variant({\n 'Ok' : IDL.Vec(UtxoStatus),\n 'Err' : UpdateBalanceError,\n }),\n ],\n [],\n ),\n });\n};\n\nexport const init = ({ IDL }) => {\n const Mode = IDL.Variant({\n 'RestrictedTo' : IDL.Vec(IDL.Principal),\n 'DepositsRestrictedTo' : IDL.Vec(IDL.Principal),\n 'ReadOnly' : IDL.Null,\n 'GeneralAvailability' : IDL.Null,\n });\n const UpgradeArgs = IDL.Record({\n 'get_utxos_cache_expiration_seconds' : IDL.Opt(IDL.Nat64),\n 'kyt_principal' : IDL.Opt(IDL.Principal),\n 'mode' : IDL.Opt(Mode),\n 'retrieve_btc_min_amount' : IDL.Opt(IDL.Nat64),\n 'max_time_in_queue_nanos' : IDL.Opt(IDL.Nat64),\n 'check_fee' : IDL.Opt(IDL.Nat64),\n 'btc_checker_principal' : IDL.Opt(IDL.Principal),\n 'min_confirmations' : IDL.Opt(IDL.Nat32),\n 'kyt_fee' : IDL.Opt(IDL.Nat64),\n });\n const BtcNetwork = IDL.Variant({\n 'Mainnet' : IDL.Null,\n 'Regtest' : IDL.Null,\n 'Testnet' : IDL.Null,\n });\n const InitArgs = IDL.Record({\n 'get_utxos_cache_expiration_seconds' : IDL.Opt(IDL.Nat64),\n 'kyt_principal' : IDL.Opt(IDL.Principal),\n 'ecdsa_key_name' : IDL.Text,\n 'mode' : Mode,\n 'retrieve_btc_min_amount' : IDL.Nat64,\n 'ledger_id' : IDL.Principal,\n 'max_time_in_queue_nanos' : IDL.Nat64,\n 'btc_network' : BtcNetwork,\n 'check_fee' : IDL.Opt(IDL.Nat64),\n 'btc_checker_principal' : IDL.Opt(IDL.Principal),\n 'min_confirmations' : IDL.Opt(IDL.Nat32),\n 'kyt_fee' : IDL.Opt(IDL.Nat64),\n });\n const MinterArg = IDL.Variant({\n 'Upgrade' : IDL.Opt(UpgradeArgs),\n 'Init' : InitArgs,\n });\n return [MinterArg];\n};\n","import { Actor } from \"@dfinity/agent\";\nimport type { _SERVICE } from \"../../../generated/canisters/ck-btc-minter/declaration\";\nimport { idlFactory } from \"../../../generated/canisters/ck-btc-minter/declaration.js\";\nimport { CK_CANISTER_IDS } from \"../../config\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { CanisterContext } from \"../../transports/canister-context\";\n\nexport type CkBtcMinterActor = _SERVICE;\n\nexport function createCkBtcMinterActor(\n canisterContext: CanisterContext\n): CkBtcMinterActor {\n const canisterId = CK_CANISTER_IDS.btcMinter;\n\n if (!canisterId) {\n throw new LiquidiumError(\n LiquidiumErrorCode.SERVICE_UNAVAILABLE,\n \"ckBTC minter canister ID is not configured\"\n );\n }\n\n return Actor.createActor<CkBtcMinterActor>(idlFactory, {\n agent: canisterContext.agent,\n canisterId,\n });\n}\n","export const idlFactory = ({ IDL }) => {\n const DepositAccountErrors = IDL.Variant({\n 'Busy' : IDL.Null,\n 'NotFound' : IDL.Null,\n 'Other' : IDL.Text,\n 'Cooldown' : IDL.Record({ 'retry_after_secs' : IDL.Nat64 }),\n 'AddressDerivationFailed' : IDL.Null,\n 'InvalidEvmAddress' : IDL.Null,\n });\n const Result = IDL.Variant({ 'Ok' : IDL.Nat, 'Err' : DepositAccountErrors });\n const DepositStatus = IDL.Variant({\n 'Failed' : IDL.Text,\n 'Success' : IDL.Null,\n 'Pending' : IDL.Null,\n });\n const DepositAssetType = IDL.Variant({\n 'Native' : IDL.Null,\n 'ERC20' : IDL.Text,\n });\n const Account = IDL.Record({\n 'owner' : IDL.Principal,\n 'subaccount' : IDL.Opt(IDL.Vec(IDL.Nat8)),\n });\n const Deposit = IDL.Record({\n 'status' : DepositStatus,\n 'asset_type' : DepositAssetType,\n 'account' : Account,\n 'timestamp' : IDL.Nat64,\n 'amount' : IDL.Nat,\n });\n const Result_1 = IDL.Variant({\n 'Ok' : IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text, Deposit)),\n 'Err' : DepositAccountErrors,\n });\n const Result_2 = IDL.Variant({\n 'Ok' : IDL.Text,\n 'Err' : DepositAccountErrors,\n });\n const QueueJobStatus = IDL.Variant({\n 'Queued' : IDL.Null,\n 'Failed' : IDL.Null,\n 'NoOp' : IDL.Null,\n 'Ready' : IDL.Null,\n 'RetryScheduled' : IDL.Null,\n 'Succeeded' : IDL.Null,\n 'Cancelled' : IDL.Null,\n 'Processing' : IDL.Null,\n 'Broadcasted' : IDL.Null,\n });\n const QueueRecoveryContext = IDL.Variant({\n 'FundingPending' : IDL.Record({\n 'funding_tx_hash' : IDL.Text,\n 'native_amount_wei' : IDL.Opt(IDL.Nat),\n }),\n 'ReadyNativeAmount' : IDL.Record({ 'native_amount_wei' : IDL.Nat }),\n });\n const QueueJob = IDL.Record({\n 'id' : IDL.Nat64,\n 'last_error' : IDL.Opt(IDL.Text),\n 'status' : QueueJobStatus,\n 'updated_at' : IDL.Nat64,\n 'asset_type' : DepositAssetType,\n 'next_attempt_at' : IDL.Nat64,\n 'token_address' : IDL.Opt(IDL.Text),\n 'attempts' : IDL.Nat32,\n 'created_at' : IDL.Nat64,\n 'address' : IDL.Text,\n 'account' : Account,\n 'tx_hash' : IDL.Opt(IDL.Text),\n 'recovery_context' : IDL.Opt(QueueRecoveryContext),\n });\n const BroadcastSuccessEvent = IDL.Record({\n 'broadcast_key' : IDL.Text,\n 'asset_type' : DepositAssetType,\n 'address' : IDL.Text,\n 'account' : Account,\n 'timestamp' : IDL.Nat64,\n 'queue_job_id' : IDL.Nat64,\n 'tx_hash' : IDL.Text,\n 'amount' : IDL.Nat,\n });\n const BroadcastConfirmedEvent = IDL.Record({\n 'broadcast_key' : IDL.Text,\n 'timestamp' : IDL.Nat64,\n 'queue_job_id' : IDL.Opt(IDL.Nat64),\n 'tx_hash' : IDL.Text,\n });\n const DustCleanupScheduledEvent = IDL.Record({\n 'address' : IDL.Text,\n 'timestamp' : IDL.Nat64,\n 'queue_job_id' : IDL.Nat64,\n });\n const DustCleanupFailedEvent = IDL.Record({\n 'attempts' : IDL.Nat8,\n 'address' : IDL.Text,\n 'timestamp' : IDL.Nat64,\n 'reason' : IDL.Text,\n });\n const BroadcastRejectedEvent = IDL.Record({\n 'broadcast_key' : IDL.Text,\n 'timestamp' : IDL.Nat64,\n 'queue_job_id' : IDL.Opt(IDL.Nat64),\n 'tx_hash' : IDL.Text,\n 'reason' : IDL.Text,\n });\n const BalanceDetectedEvent = IDL.Record({\n 'asset_type' : DepositAssetType,\n 'address' : IDL.Text,\n 'account' : Account,\n 'timestamp' : IDL.Nat64,\n 'queue_job_id' : IDL.Nat64,\n 'amount' : IDL.Nat,\n });\n const AssetRegisteredEvent = IDL.Record({\n 'decimals' : IDL.Nat32,\n 'asset_address' : IDL.Text,\n 'updated_existing' : IDL.Bool,\n 'timestamp' : IDL.Nat64,\n 'caller' : IDL.Principal,\n 'symbol' : IDL.Text,\n });\n const QueueJobFailedEvent = IDL.Record({\n 'asset_type' : DepositAssetType,\n 'attempts' : IDL.Nat32,\n 'address' : IDL.Text,\n 'account' : Account,\n 'timestamp' : IDL.Nat64,\n 'queue_job_id' : IDL.Nat64,\n 'reason' : IDL.Text,\n });\n const DepositAccountEvent = IDL.Variant({\n 'BroadcastSuccess' : BroadcastSuccessEvent,\n 'BroadcastConfirmed' : BroadcastConfirmedEvent,\n 'DustCleanupScheduled' : DustCleanupScheduledEvent,\n 'DustCleanupFailed' : DustCleanupFailedEvent,\n 'BroadcastRejected' : BroadcastRejectedEvent,\n 'BalanceDetected' : BalanceDetectedEvent,\n 'AssetRegistered' : AssetRegisteredEvent,\n 'QueueJobFailed' : QueueJobFailedEvent,\n });\n const AddressBinding = IDL.Record({\n 'token_address' : IDL.Opt(IDL.Text),\n 'account' : Account,\n });\n const Result_3 = IDL.Variant({\n 'Ok' : AddressBinding,\n 'Err' : DepositAccountErrors,\n });\n const Result_4 = IDL.Variant({\n 'Ok' : IDL.Null,\n 'Err' : DepositAccountErrors,\n });\n const Result_5 = IDL.Variant({\n 'Ok' : IDL.Nat64,\n 'Err' : DepositAccountErrors,\n });\n const Result_6 = IDL.Variant({\n 'Ok' : IDL.Nat,\n 'Err' : DepositAccountErrors,\n });\n return IDL.Service({\n 'estimate_deposit_fee' : IDL.Func([IDL.Opt(IDL.Text)], [Result], ['query']),\n 'get_broadcasted_txs' : IDL.Func([], [Result_1], ['query']),\n 'get_deposit_address' : IDL.Func(\n [Account, IDL.Opt(IDL.Text)],\n [Result_2],\n ['query'],\n ),\n 'get_funding_wallet_address' : IDL.Func([], [Result_2], ['query']),\n 'get_or_create_deposit_address' : IDL.Func(\n [Account, IDL.Opt(IDL.Text)],\n [Result_2],\n [],\n ),\n 'get_queue_job' : IDL.Func([IDL.Nat64], [IDL.Opt(QueueJob)], ['query']),\n 'get_queued_event' : IDL.Func(\n [IDL.Nat],\n [IDL.Opt(DepositAccountEvent)],\n ['query'],\n ),\n 'get_queued_events' : IDL.Func(\n [IDL.Nat64, IDL.Nat64],\n [IDL.Vec(IDL.Tuple(IDL.Nat, DepositAccountEvent))],\n ['query'],\n ),\n 'get_supported_assets' : IDL.Func(\n [],\n [IDL.Vec(IDL.Tuple(IDL.Text, IDL.Text, IDL.Nat32))],\n ['query'],\n ),\n 'get_user_by_address' : IDL.Func([IDL.Text], [Result_3], ['query']),\n 'list_queue_jobs' : IDL.Func(\n [IDL.Nat64, IDL.Nat32],\n [IDL.Vec(QueueJob)],\n ['query'],\n ),\n 'register_asset' : IDL.Func(\n [IDL.Text, IDL.Text, IDL.Nat32],\n [Result_4],\n [],\n ),\n 'set_proxy_contract_address_override' : IDL.Func(\n [IDL.Text],\n [Result_4],\n [],\n ),\n 'sync_address_nonce' : IDL.Func([IDL.Text], [Result_5], []),\n 'update_address' : IDL.Func([IDL.Text], [Result_6], []),\n });\n};\nexport const init = ({ IDL }) => { return []; };\n","import { Actor } from \"@dfinity/agent\";\nimport type {\n _SERVICE,\n DepositAccountErrors as GeneratedDepositAccountErrors,\n} from \"../../../generated/canisters/deposit-accounts/deposit_accounts.did\";\nimport { idlFactory } from \"../../../generated/canisters/deposit-accounts/deposit_accounts.did.js\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { CanisterContext } from \"../../transports/canister-context\";\n\nexport type DepositAccountsActor = _SERVICE;\nexport type DepositAccountErrors = GeneratedDepositAccountErrors;\n\nexport function createDepositAccountsActor(\n canisterContext: CanisterContext\n): DepositAccountsActor {\n const canisterId = canisterContext.canisterIds.ethDeposit;\n\n if (!canisterId) {\n throw new LiquidiumError(\n LiquidiumErrorCode.SERVICE_UNAVAILABLE,\n \"ETH deposit canister ID is not configured\"\n );\n }\n\n return Actor.createActor<DepositAccountsActor>(idlFactory, {\n agent: canisterContext.agent,\n canisterId,\n });\n}\n","import type { Principal } from \"@dfinity/principal\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../errors\";\nimport { SupplyAction } from \"../types\";\n\nconst INFLOW_DEPOSIT_PREFIX = 0x1;\nconst INFLOW_REPAY_PREFIX = 0x2;\nconst MAX_PRINCIPAL_BYTES = 29;\nconst SUBACCOUNT_LENGTH = 32;\nconst PRINCIPAL_LENGTH_OFFSET = 2;\nconst PRINCIPAL_START_OFFSET = 3;\n\nexport function encodeInflowSubaccount(request: {\n action: SupplyAction;\n principal: Principal;\n}): Uint8Array {\n const subaccount = new Uint8Array(SUBACCOUNT_LENGTH);\n const principalBytes = request.principal.toUint8Array();\n\n if (principalBytes.length > MAX_PRINCIPAL_BYTES) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Principal length exceeds inflow subaccount capacity\"\n );\n }\n\n subaccount[0] =\n request.action === SupplyAction.deposit\n ? INFLOW_DEPOSIT_PREFIX\n : INFLOW_REPAY_PREFIX;\n subaccount[PRINCIPAL_LENGTH_OFFSET] = principalBytes.length;\n subaccount.set(principalBytes, PRINCIPAL_START_OFFSET);\n\n return subaccount;\n}\n","import type {\n Asset,\n Chain,\n InflowSubmitType,\n MarketAsset,\n MarketChain,\n OutflowType,\n SupplyAction,\n} from \"../../core/types\";\nimport type {\n SignatureInfo,\n SignMessageWalletAction,\n WalletActionKind,\n WalletAdapter,\n WalletExecutionKind,\n} from \"../../core/wallet-actions\";\n\n/** Destination account for a completed outflow. */\nexport interface OutflowReceiver {\n /** Destination account type reported by the protocol. */\n type: \"Native\" | \"External\";\n /** Destination principal or external-chain address. */\n account: string;\n}\n\n/**\n * Receipt for a borrow or withdraw submitted to the lending canister.\n *\n * `id` is the outflow reference to show users immediately. `txid` may be unset until\n * the protocol assigns a chain transaction id. `outflowRef` is an optional protocol reference.\n */\nexport interface OutflowDetails {\n /** Protocol outflow id. */\n id: string;\n /** Borrow, withdraw, or fee-claim discriminator. */\n outflowType: OutflowType;\n /** Optional protocol outflow reference. */\n outflowRef?: string;\n /** Chain transaction id when already assigned by the protocol. */\n txid?: string;\n /** Outflow amount in the pool asset's base units. */\n amount: bigint;\n /** Outflow destination account. */\n receiver: OutflowReceiver;\n}\n\n/** Borrow receipt with an external-chain receiver. */\nexport type BorrowOutflowDetails = OutflowDetails & {\n outflowType: \"borrow\";\n receiver: { type: \"External\"; account: string };\n};\n\n/** Withdraw receipt with an external-chain receiver. */\nexport type WithdrawOutflowDetails = OutflowDetails & {\n outflowType: \"withdraw\";\n receiver: { type: \"External\"; account: string };\n};\n\n/** Signature payload for submitting a prepared borrow action. */\nexport interface BorrowSubmitSignatureInfo extends SignatureInfo {}\n\n/** Signature payload for submitting a prepared withdraw action. */\nexport interface WithdrawSubmitSignatureInfo extends SignatureInfo {}\n\n/**\n * Fields to build a borrow request. `amount` is in the borrow pool asset's base units\n * (e.g. satoshis, token smallest units).\n */\nexport interface CreateBorrowRequest {\n /** Liquidium profile principal text. */\n profileId: string;\n /** Borrow pool principal text. */\n poolId: string;\n /** Amount to borrow in the borrow asset's base units. */\n amount: bigint;\n /** External-chain address that receives the borrowed asset. */\n receiverAddress: string;\n /** Wallet address that signs the borrow authorization. */\n signerWalletAddress: string;\n}\n\n/** Prepared borrow request data embedded in the signable action. */\nexport interface CreateBorrowData extends CreateBorrowRequest {\n /** Expiry timestamp, in protocol nanoseconds, included in the signed message. */\n expiryTimestamp: bigint;\n}\n\n/** Prepared action for creating a borrow outflow. */\nexport interface BorrowAction\n extends SignMessageWalletAction<CreateBorrowData, BorrowOutflowDetails> {\n /** Protocol action kind. */\n kind: typeof WalletActionKind.createBorrow;\n /** Required wallet capability. */\n executionKind: typeof WalletExecutionKind.signMessage;\n /** Adapter-facing action type. */\n actionType: typeof WalletActionKind.createBorrow;\n}\n\n/**\n * Fields to build a withdraw request. `amount` is in the pool asset's base units.\n */\nexport interface CreateWithdrawRequest {\n /** Liquidium profile principal text. */\n profileId: string;\n /** Pool principal text to withdraw from. */\n poolId: string;\n /** Amount to withdraw in the pool asset's base units. */\n amount: bigint;\n /** External-chain address that receives the withdrawn asset. */\n receiverAddress: string;\n /** Wallet address that signs the withdraw authorization. */\n signerWalletAddress: string;\n}\n\n/** Prepared withdraw request data embedded in the signable action. */\nexport interface CreateWithdrawData extends CreateWithdrawRequest {\n /** Expiry timestamp, in protocol nanoseconds, included in the signed message. */\n expiryTimestamp: bigint;\n}\n\n/** Prepared action for creating a withdraw outflow. */\nexport interface WithdrawAction\n extends SignMessageWalletAction<CreateWithdrawData, WithdrawOutflowDetails> {\n /** Protocol action kind. */\n kind: typeof WalletActionKind.createWithdraw;\n /** Required wallet capability. */\n executionKind: typeof WalletExecutionKind.signMessage;\n /** Adapter-facing action type. */\n actionType: typeof WalletActionKind.createWithdraw;\n}\n\n/** Supply execution plan selected by the SDK. */\nexport const SupplyPlanType = {\n contractInteraction: \"contractInteraction\",\n transfer: \"transfer\",\n} as const;\n/** Supply execution plan selected by the SDK. */\nexport type SupplyPlanType =\n (typeof SupplyPlanType)[keyof typeof SupplyPlanType];\n\n/** External-chain address target for manual or wallet-executed transfers. */\nexport interface NativeAddressSupplyTarget {\n /** Target discriminator. */\n type: \"nativeAddress\";\n /** Pool principal text receiving the inflow. */\n poolId: string;\n /** Asset expected by the target. */\n asset: MarketAsset;\n /** Chain where the target address is valid. */\n chain: MarketChain;\n /** Deposit or repayment action for the inflow. */\n action: SupplyAction;\n /** External-chain address where funds should be sent. */\n address: string;\n}\n\n/** ICRC account target for ck-asset or contract-interaction inflows. */\nexport interface IcrcAccountSupplyTarget {\n /** Target discriminator. */\n type: \"icrcAccount\";\n /** Pool principal text receiving the inflow. */\n poolId: string;\n /** Asset expected by the target. */\n asset: MarketAsset;\n /** Chain associated with the inflow. */\n chain: MarketChain;\n /** Deposit or repayment action for the inflow. */\n action: SupplyAction;\n /** ICRC account owner principal text. */\n owner: string;\n /** ICRC subaccount bytes. */\n subaccount: Uint8Array;\n /** Text-encoded ICRC account. */\n account: string;\n}\n\n/** Supply destination returned by `lending.supply(...)`. */\nexport type SupplyTarget = NativeAddressSupplyTarget | IcrcAccountSupplyTarget;\n\ninterface BaseSupplyFlowRequest {\n profileId: string;\n poolId: string;\n action: SupplyAction;\n}\n\n/** Manual transfer-based `lending.supply` request. */\nexport interface ManualTransferSupplyFlowRequest extends BaseSupplyFlowRequest {\n /** Optional explicit transfer mechanism. */\n mechanism?: typeof SupplyPlanType.transfer;\n /** Disallowed for manual transfer flows. */\n walletAdapter?: never;\n /** Disallowed for manual transfer flows. */\n account?: never;\n /** Disallowed for manual transfer flows. */\n amount?: never;\n}\n\n/** Wallet-executed transfer-based `lending.supply` request. */\nexport interface WalletTransferSupplyFlowRequest extends BaseSupplyFlowRequest {\n /** Optional explicit transfer mechanism. */\n mechanism?: typeof SupplyPlanType.transfer;\n /** Wallet adapter used to broadcast the transfer. */\n walletAdapter: Pick<\n WalletAdapter,\n \"sendBtcTransaction\" | \"sendEthTransaction\"\n >;\n /** Sender wallet account. */\n account: string;\n /** Transfer amount in the target asset's base units. */\n amount: bigint;\n}\n\n/** Transfer-based supply request, either manual or wallet-executed. */\nexport type TransferSupplyFlowRequest =\n | ManualTransferSupplyFlowRequest\n | WalletTransferSupplyFlowRequest;\n\n/** Input for contract-interaction `lending.supply`, which always executes now. */\nexport interface ContractInteractionSupplyFlowRequest\n extends BaseSupplyFlowRequest {\n /** Contract-interaction mechanism discriminator. */\n mechanism: typeof SupplyPlanType.contractInteraction;\n /** ETH wallet adapter used to approve and deposit ERC-20 assets. */\n walletAdapter: Pick<WalletAdapter, \"sendEthTransaction\">;\n /** Sender EVM wallet address. */\n account: string;\n /** Deposit or repayment amount in token base units. */\n amount: bigint;\n}\n\n/** Request accepted by `lending.supply(...)`. */\nexport type SupplyFlowRequest =\n | TransferSupplyFlowRequest\n | ContractInteractionSupplyFlowRequest;\n\n/**\n * Supply receipt returned by `lending.supply(...)`.\n *\n * - `txid` is populated when the SDK broadcast the transaction on your behalf\n * (wallet-adapter path). When undefined, the caller is expected to broadcast\n * themselves and call {@link SupplyFlow.submit} for flows that require txid\n * registration.\n * - `submit` registers a broadcast txid with the SDK API when needed. ETH\n * stablecoin deposit-address transfers are indexed from ERC-20 transfer logs,\n * so `submit` acknowledges the txid without posting it to the inflow endpoint.\n *\n * The SDK does not poll inflow status. When you have a `txid`, it is your\n * responsibility to track confirmation state with your own polling.\n */\nexport interface SupplyFlow {\n /** Execution plan used by the supply flow. */\n type: SupplyPlanType;\n /** Destination where funds should be sent or were sent. */\n target: SupplyTarget;\n /** Transaction id when the SDK broadcast the transaction. */\n txid?: string;\n /** Registers a broadcast transaction id when the flow requires an indexing hint. */\n submit(request: SubmitInflowRequest): Promise<SubmitInflowResponse>;\n}\n\n/** Body for `SupplyFlow.submit` / `lending.submitInflow`. */\nexport interface SubmitInflowRequest {\n /** Broadcast transaction id or hash. */\n txid: string;\n /** Chain where the transaction was broadcast, when not implied by the flow. */\n chain?: Chain;\n /** Deposit or repayment submit type, when not implied by the flow. */\n type?: InflowSubmitType;\n}\n\n/** Acknowledgement from the SDK API after submitting an inflow hint. */\nexport interface SubmitInflowResponse {\n /** Indicates the submit request was accepted by the SDK API. */\n success: true;\n /** Transaction id accepted by the SDK API. */\n txid: string;\n}\n\n/** Request for estimating the fee needed for an inflow target. */\nexport interface EstimateInflowFeeRequest {\n /** Asset to estimate for. */\n asset: Asset;\n /** Chain to estimate for. */\n chain: Chain;\n}\n\n/** Fee estimate for an inflow target. */\nexport interface InflowFeeEstimate {\n /** Estimated total fee in the asset's base units. */\n totalFee: bigint;\n}\n\n/** Request for ERC-20 approval and deposit planning. */\nexport interface GetEvmSupplyContextRequest {\n /** Liquidium profile principal text. */\n profileId: string;\n /** Pool principal text receiving the inflow. */\n poolId: string;\n /** EVM wallet address that will send funds. */\n walletAddress: string;\n /** Supply amount in token base units. */\n amount: bigint;\n /** Deposit or repayment action for the inflow. */\n action: SupplyAction;\n}\n\n/** Approval strategy required before an ERC-20 deposit contract call. */\nexport const EvmSupplyApprovalStrategy = {\n approveMax: \"approve-max\",\n none: \"none\",\n resetThenApproveMax: \"reset-then-approve-max\",\n} as const;\n/** Approval strategy required before an ERC-20 deposit contract call. */\nexport type EvmSupplyApprovalStrategy =\n (typeof EvmSupplyApprovalStrategy)[keyof typeof EvmSupplyApprovalStrategy];\n\n/** ERC-20 supply planning data returned by `lending.getEvmSupplyContext(...)`. */\nexport interface EvmSupplyContext {\n /** Indicates the context was computed successfully. */\n success: true;\n /** Liquidium profile principal text. */\n profileId: string;\n /** Pool principal text receiving the inflow. */\n poolId: string;\n /** Normalized EVM wallet address. */\n walletAddress: string;\n /** Deposit or repayment action for the inflow. */\n action: SupplyAction;\n /** Supported ETH stablecoin asset. */\n asset: typeof Asset.USDC | typeof Asset.USDT;\n /** ETH chain discriminator. */\n chain: typeof Chain.ETH;\n /** Requested amount serialized in token base units. */\n amount: string;\n /** ERC-20 token contract address. */\n tokenAddress: string;\n /** Contract address that must be approved as spender. */\n spenderAddress: string;\n /** Deposit helper contract address. */\n depositContractAddress: string;\n /** Current token balance serialized in base units. */\n balance: string;\n /** Current allowance serialized in base units. */\n allowance: string;\n /** Whether an approval transaction is needed before deposit. */\n requiresApproval: boolean;\n /** Approval sequence the caller should perform. */\n approvalStrategy: EvmSupplyApprovalStrategy;\n}\n","import { encodeIcrcAccount } from \"@dfinity/ledger-icrc\";\nimport { Principal } from \"@dfinity/principal\";\nimport { createCkBtcMinterActor } from \"../../../core/canisters/ckbtc/minter\";\nimport {\n createDepositAccountsActor,\n type DepositAccountErrors,\n} from \"../../../core/canisters/deposit-accounts/actor\";\nimport {\n createLendingActor,\n type LendingPoolRecord,\n} from \"../../../core/canisters/lending/actor\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../../core/errors\";\nimport {\n USDC_CONTRACT_ADDRESS,\n USDT_CONTRACT_ADDRESS,\n} from \"../../../core/evm\";\nimport type { CanisterContext } from \"../../../core/transports/canister-context\";\nimport { Asset, Chain, type SupplyAction } from \"../../../core/types\";\nimport { encodeInflowSubaccount } from \"../../../core/utils/inflow-subaccount\";\nimport { getVariantKey } from \"../../../core/utils/variant\";\nimport {\n type IcrcAccountSupplyTarget,\n type NativeAddressSupplyTarget,\n SupplyPlanType,\n type SupplyTarget,\n} from \"../types\";\n\nexport type SupplyMechanism = SupplyPlanType;\n\nexport interface InternalSupplyTargetRequest {\n profileId: string;\n poolId: string;\n action: SupplyAction;\n mechanism?: SupplyMechanism;\n}\n\ninterface SupplyTargetRequest {\n poolId: string;\n asset: string;\n chain: string;\n action: SupplyAction;\n}\n\nexport async function resolveSupplyTarget(\n canisterContext: CanisterContext,\n request: InternalSupplyTargetRequest\n): Promise<SupplyTarget> {\n const selectedPool = await getPoolById(canisterContext, request.poolId);\n const asset = getVariantKey(selectedPool.asset);\n const chain = getVariantKey(selectedPool.chain);\n const mechanism = resolveSupplyMechanism({\n asset,\n chain,\n requestedMechanism: request.mechanism,\n });\n\n switch (mechanism) {\n case SupplyPlanType.transfer:\n return await getNativeAddressSupplyTarget(\n canisterContext,\n request.profileId,\n {\n poolId: request.poolId,\n asset,\n chain,\n action: request.action,\n }\n );\n case SupplyPlanType.contractInteraction:\n return getIcrcAccountSupplyTarget(request.profileId, {\n poolId: request.poolId,\n asset,\n chain,\n action: request.action,\n });\n }\n}\n\nexport function resolveSupplyMechanism(params: {\n asset: string;\n chain: string;\n requestedMechanism?: SupplyMechanism;\n}): SupplyMechanism {\n if (params.asset === Asset.BTC && params.chain === Chain.BTC) {\n if (params.requestedMechanism === SupplyPlanType.contractInteraction) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Contract-interaction supply is not supported for BTC on BTC\"\n );\n }\n\n return SupplyPlanType.transfer;\n }\n\n if (isEthStablecoin(params.asset, params.chain)) {\n if (params.requestedMechanism) {\n return params.requestedMechanism;\n }\n\n return SupplyPlanType.transfer;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `No supply mechanism is configured for ${params.asset} on ${params.chain}`\n );\n}\n\nexport function isEthStablecoin(asset: string, chain: string): boolean {\n return chain === Chain.ETH && (asset === Asset.USDC || asset === Asset.USDT);\n}\n\nexport function getEthStablecoinContractAddress(asset: string): string {\n if (asset === Asset.USDC) {\n return USDC_CONTRACT_ADDRESS;\n }\n\n if (asset === Asset.USDT) {\n return USDT_CONTRACT_ADDRESS;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `ETH stablecoin contract address is not configured for ${asset}`\n );\n}\n\nexport function mapDepositAccountErrorToLiquidiumError(\n error: DepositAccountErrors\n): LiquidiumError {\n if (\"InvalidEvmAddress\" in error) {\n return new LiquidiumError(\n LiquidiumErrorCode.INVALID_ADDRESS,\n \"Invalid EVM deposit address\"\n );\n }\n\n if (\"Busy\" in error) {\n return new LiquidiumError(\n LiquidiumErrorCode.SERVICE_UNAVAILABLE,\n \"Deposit address service is busy\"\n );\n }\n\n if (\"Cooldown\" in error) {\n return new LiquidiumError(\n LiquidiumErrorCode.SERVICE_UNAVAILABLE,\n `Deposit address service is cooling down for ${error.Cooldown.retry_after_secs.toString()} seconds`\n );\n }\n\n if (\"Other\" in error) {\n return new LiquidiumError(\n LiquidiumErrorCode.DEPOSIT_ADDRESS_ERROR,\n error.Other\n );\n }\n\n if (\"AddressDerivationFailed\" in error) {\n return new LiquidiumError(\n LiquidiumErrorCode.DEPOSIT_ADDRESS_ERROR,\n \"Deposit address derivation failed\"\n );\n }\n\n if (\"NotFound\" in error) {\n return new LiquidiumError(\n LiquidiumErrorCode.DEPOSIT_ADDRESS_ERROR,\n \"Deposit address not found\"\n );\n }\n\n return new LiquidiumError(\n LiquidiumErrorCode.DEPOSIT_ADDRESS_ERROR,\n \"Deposit address canister returned an unknown error\"\n );\n}\n\nasync function getPoolById(\n canisterContext: CanisterContext,\n poolId: string\n): Promise<LendingPoolRecord> {\n const pools = await createLendingActor(canisterContext).list_pools();\n const selectedPool = pools.find((pool) => pool.principal.toText() === poolId);\n\n if (!selectedPool) {\n throw new LiquidiumError(\n LiquidiumErrorCode.POOL_NOT_FOUND,\n `Pool not found: ${poolId}`\n );\n }\n\n return selectedPool;\n}\n\nasync function getNativeAddressSupplyTarget(\n canisterContext: CanisterContext,\n profileId: string,\n request: SupplyTargetRequest\n): Promise<NativeAddressSupplyTarget> {\n assertSupportsNativeAddressInflowTarget(request.asset, request.chain);\n\n if (isEthStablecoin(request.asset, request.chain)) {\n const tokenAddress = getEthStablecoinContractAddress(request.asset);\n const subaccount = encodeInflowSubaccount({\n action: request.action,\n principal: Principal.fromText(profileId),\n });\n const result = await createDepositAccountsActor(\n canisterContext\n ).get_deposit_address(\n {\n owner: Principal.fromText(request.poolId),\n subaccount: [subaccount],\n },\n [tokenAddress]\n );\n\n if (\"Err\" in result) {\n throw mapDepositAccountErrorToLiquidiumError(result.Err);\n }\n\n return {\n type: \"nativeAddress\",\n poolId: request.poolId,\n asset: request.asset,\n chain: request.chain,\n action: request.action,\n address: result.Ok,\n };\n }\n\n const configuredBtcPoolId = canisterContext.canisterIds.btcPool;\n if (request.poolId !== configuredBtcPoolId) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Native BTC inflow targets require the configured BTC pool ${configuredBtcPoolId}, received ${request.poolId}`\n );\n }\n\n const subaccount = encodeInflowSubaccount({\n action: request.action,\n principal: Principal.fromText(profileId),\n });\n const address = await createCkBtcMinterActor(canisterContext).get_btc_address(\n {\n owner: [Principal.fromText(configuredBtcPoolId)],\n subaccount: [subaccount],\n }\n );\n\n return {\n type: \"nativeAddress\",\n poolId: request.poolId,\n asset: request.asset,\n chain: request.chain,\n action: request.action,\n address,\n };\n}\n\nfunction getIcrcAccountSupplyTarget(\n profileId: string,\n request: SupplyTargetRequest\n): IcrcAccountSupplyTarget {\n assertSupportsIcrcAccountInflowTarget(request.asset);\n\n const poolPrincipal = Principal.fromText(request.poolId);\n const subaccount = encodeInflowSubaccount({\n action: request.action,\n principal: Principal.fromText(profileId),\n });\n\n return {\n type: \"icrcAccount\",\n poolId: request.poolId,\n asset: request.asset,\n chain: request.chain,\n action: request.action,\n owner: poolPrincipal.toText(),\n subaccount,\n account: encodeIcrcAccount({\n owner: Principal.fromText(poolPrincipal.toText()),\n subaccount,\n }),\n };\n}\n\nfunction assertSupportsNativeAddressInflowTarget(\n asset: string,\n chain: string\n): void {\n if (asset === Asset.BTC && chain === Chain.BTC) {\n return;\n }\n\n if (isEthStablecoin(asset, chain)) {\n return;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Native address inflow targets are not supported for ${asset} on ${chain}`\n );\n}\n\nfunction assertSupportsIcrcAccountInflowTarget(asset: string): void {\n if (asset === Asset.BTC || asset === Asset.USDT || asset === Asset.USDC) {\n return;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `ICRC account inflow targets are not supported for ${asset}`\n );\n}\n","/** Input for calculating required collateral from a target LTV. */\nexport interface QuoteRequest {\n /** Requested borrow amount in borrow asset base units. */\n borrowAmount: bigint;\n /** Pool principal text for the borrow side. */\n borrowPoolId: string;\n /** Pool principal text for the collateral side. */\n collateralPoolId: string;\n /** Target loan-to-value ratio in basis points. */\n targetLtvBps: bigint;\n}\n\n/** Input for calculating LTV from explicit borrow and collateral amounts. */\nexport interface CalculateLtvRequest {\n /** Requested borrow amount in borrow asset base units. */\n borrowAmount: bigint;\n /** Pool principal text for the borrow side. */\n borrowPoolId: string;\n /** Collateral amount in collateral asset base units. */\n collateralAmount: bigint;\n /** Pool principal text for the collateral side. */\n collateralPoolId: string;\n}\n\n/** Validation error produced by quote helpers. */\nexport interface QuoteValidationError {\n /** Stable machine-readable validation code. */\n code: QuoteValidationErrorCode;\n /** Human-readable validation message. */\n message: string;\n}\n\n/** Stable validation codes produced by quote helpers. */\nexport enum QuoteValidationErrorCode {\n INVALID_LTV = \"INVALID_LTV\",\n LTV_EXCEEDS_MAX = \"LTV_EXCEEDS_MAX\",\n SAME_ASSET_NOT_ALLOWED = \"SAME_ASSET_NOT_ALLOWED\",\n BORROW_AMOUNT_TOO_LOW = \"BORROW_AMOUNT_TOO_LOW\",\n PRICE_NOT_AVAILABLE = \"PRICE_NOT_AVAILABLE\",\n POOL_NOT_FOUND = \"POOL_NOT_FOUND\",\n UNKNOWN = \"UNKNOWN\",\n}\n\n/** Non-blocking warning produced by quote helpers. */\nexport interface QuoteWarning {\n /** Stable machine-readable warning code. */\n code: QuoteWarningCode;\n /** Human-readable warning message. */\n message: string;\n}\n\n/** Stable warning codes produced by quote helpers. */\nexport enum QuoteWarningCode {\n HIGH_LTV = \"HIGH_LTV\",\n SAME_ASSET_BORROWING = \"SAME_ASSET_BORROWING\",\n}\n\n/** Quote result for a requested borrow amount and target LTV. */\nexport interface QuoteResult {\n /** Requested borrow amount in borrow asset base units. */\n borrowAmount: bigint;\n /** Borrow value in internal USD units. */\n borrowUsd: bigint;\n /** Required collateral amount in collateral asset base units. */\n requiredCollateralAmount: bigint;\n /** Required collateral value in internal USD units. */\n requiredCollateralUsd: bigint;\n /** Maximum allowed LTV in basis points for the collateral pool. */\n maxAllowedLtvBps: bigint;\n /** Requested target LTV in basis points. */\n targetLtvBps: bigint;\n /** Pool principal text for the borrow side. */\n borrowPoolId: string;\n /** Pool principal text for the collateral side. */\n collateralPoolId: string;\n /** Borrow asset symbol. */\n borrowAsset: string;\n /** Collateral asset symbol. */\n collateralAsset: string;\n /** Blocking validation errors. Empty when the quote is usable. */\n validationErrors: QuoteValidationError[];\n /** Non-blocking quote warnings. */\n warnings: QuoteWarning[];\n}\n\n/** LTV calculation result for explicit borrow and collateral amounts. */\nexport interface LtvCalculation {\n /** Requested borrow amount in borrow asset base units. */\n borrowAmount: bigint;\n /** Collateral amount in collateral asset base units. */\n collateralAmount: bigint;\n /** Borrow value in internal USD units. */\n borrowUsd: bigint;\n /** Collateral value in internal USD units. */\n collateralUsd: bigint;\n /** Computed LTV in basis points. */\n ltvBps: bigint;\n /** Maximum allowed LTV in basis points for the collateral pool. */\n maxAllowedLtvBps: bigint;\n /** Pool principal text for the borrow side. */\n borrowPoolId: string;\n /** Pool principal text for the collateral side. */\n collateralPoolId: string;\n /** Borrow asset symbol. */\n borrowAsset: string;\n /** Collateral asset symbol. */\n collateralAsset: string;\n /** Blocking validation errors. Empty when the calculation is usable. */\n validationErrors: QuoteValidationError[];\n}\n","import { ceilDivBigint } from \"../../core/utils/bigint\";\nimport type { AssetPrices, Pool } from \"../market/types\";\nimport type {\n CalculateLtvRequest,\n LtvCalculation,\n QuoteRequest,\n QuoteResult,\n QuoteValidationError,\n QuoteWarning,\n} from \"./types\";\nimport { QuoteValidationErrorCode, QuoteWarningCode } from \"./types\";\n\nconst BASIS_POINTS_DENOMINATOR = 10_000n;\nconst BPS_PER_PERCENT = 100n;\nconst MIN_LTV_BPS = 0n;\nconst HIGH_LTV_WARNING_THRESHOLD_BPS = 8_000n;\nconst MIN_BORROW_AMOUNT_BASE_UNITS = 5_000n;\nconst INTERNAL_USD_DECIMAL_PLACES = 8;\nconst PRICE_SCALE_DECIMAL_PLACES = 8;\n\ntype CreateQuoteResultParams = {\n borrowAmount: bigint;\n borrowPoolId: string;\n collateralPoolId: string;\n borrowUsd: bigint;\n requiredCollateralAmount: bigint;\n requiredCollateralUsd: bigint;\n maxAllowedLtvBps: bigint;\n targetLtvBps: bigint;\n borrowAsset: string;\n collateralAsset: string;\n validationErrors: QuoteValidationError[];\n warnings: QuoteWarning[];\n};\n\n/** Pure quote helpers for LTV and required-collateral calculations. */\nexport class QuoteModule {\n /**\n * Calculates current LTV from caller-supplied borrow and collateral amounts.\n *\n * Amount fields are base units. USD fields are scaled to 8 decimal places.\n *\n * @param request - Borrow and collateral pool ids plus base-unit amounts.\n * @param pools - Available pools, usually from `client.market.listPools()`.\n * @param prices - USD price map, usually from `client.market.getAssetPrices()`.\n * @returns LTV calculation plus validation errors when inputs are unusable.\n */\n calculateLtv(\n request: CalculateLtvRequest,\n pools: Pool[],\n prices: AssetPrices\n ): LtvCalculation {\n const validationErrors: QuoteValidationError[] = [];\n const borrowPool = pools.find((pool) => pool.id === request.borrowPoolId);\n const collateralPool = pools.find(\n (pool) => pool.id === request.collateralPoolId\n );\n\n if (!borrowPool) {\n validationErrors.push({\n code: QuoteValidationErrorCode.POOL_NOT_FOUND,\n message: `Borrow pool not found: ${request.borrowPoolId}`,\n });\n }\n\n if (!collateralPool) {\n validationErrors.push({\n code: QuoteValidationErrorCode.POOL_NOT_FOUND,\n message: `Collateral pool not found: ${request.collateralPoolId}`,\n });\n }\n\n if (!borrowPool || !collateralPool) {\n return createLtvCalculation({\n request,\n borrowUsd: 0n,\n collateralUsd: 0n,\n ltvBps: 0n,\n maxAllowedLtvBps: 0n,\n borrowAsset: \"\",\n collateralAsset: \"\",\n validationErrors,\n });\n }\n\n const borrowPrice = prices[borrowPool.asset];\n const collateralPrice = prices[collateralPool.asset];\n\n if (!isValidPrice(borrowPrice)) {\n validationErrors.push({\n code: QuoteValidationErrorCode.PRICE_NOT_AVAILABLE,\n message: `Price not available for borrow asset: ${borrowPool.asset}`,\n });\n }\n\n if (!isValidPrice(collateralPrice)) {\n validationErrors.push({\n code: QuoteValidationErrorCode.PRICE_NOT_AVAILABLE,\n message: `Price not available for collateral asset: ${collateralPool.asset}`,\n });\n }\n\n if (request.borrowAmount <= 0n) {\n validationErrors.push({\n code: QuoteValidationErrorCode.BORROW_AMOUNT_TOO_LOW,\n message: \"Borrow amount must be greater than 0\",\n });\n }\n\n if (request.collateralAmount <= 0n) {\n validationErrors.push({\n code: QuoteValidationErrorCode.INVALID_LTV,\n message: \"Collateral amount must be greater than 0\",\n });\n }\n\n if (validationErrors.length > 0) {\n return createLtvCalculation({\n request,\n borrowUsd: 0n,\n collateralUsd: 0n,\n ltvBps: 0n,\n maxAllowedLtvBps: collateralPool.maxLtv,\n borrowAsset: borrowPool.asset,\n collateralAsset: collateralPool.asset,\n validationErrors,\n });\n }\n\n const borrowUsd = computeUsdInternalFromBaseUnits({\n amountBaseUnits: request.borrowAmount,\n priceScaled: scalePriceUsdToBigint(borrowPrice as number),\n assetDecimalPlaces: getPoolDecimalPlaces(borrowPool),\n });\n const collateralUsd = computeUsdInternalFromBaseUnits({\n amountBaseUnits: request.collateralAmount,\n priceScaled: scalePriceUsdToBigint(collateralPrice as number),\n assetDecimalPlaces: getPoolDecimalPlaces(collateralPool),\n });\n\n if (collateralUsd <= 0n) {\n validationErrors.push({\n code: QuoteValidationErrorCode.INVALID_LTV,\n message: \"Collateral value must be greater than 0\",\n });\n\n return createLtvCalculation({\n request,\n borrowUsd,\n collateralUsd,\n ltvBps: 0n,\n maxAllowedLtvBps: collateralPool.maxLtv,\n borrowAsset: borrowPool.asset,\n collateralAsset: collateralPool.asset,\n validationErrors,\n });\n }\n\n return createLtvCalculation({\n request,\n borrowUsd,\n collateralUsd,\n ltvBps: roundDivBigint(\n borrowUsd * BASIS_POINTS_DENOMINATOR,\n collateralUsd\n ),\n maxAllowedLtvBps: collateralPool.maxLtv,\n borrowAsset: borrowPool.asset,\n collateralAsset: collateralPool.asset,\n validationErrors,\n });\n }\n\n /**\n * Calculates a loan quote based on borrow amount, LTV, and pool selections.\n *\n * All arithmetic is performed in bigint. `requiredCollateralAmount` and\n * `requiredCollateralUsd` are rounded UP so the caller never under-collateralizes\n * due to integer truncation. `borrowUsd` is floored for display.\n *\n * @param request - Quote request parameters.\n * @param pools - All available pools (use MarketModule.listPools() to fetch).\n * @param prices - Asset prices in USD (use MarketModule.getAssetPrices() to fetch).\n * @returns Quote result with required collateral and validation state.\n */\n getQuote(\n request: QuoteRequest,\n pools: Pool[],\n prices: AssetPrices\n ): QuoteResult {\n const { borrowAmount, borrowPoolId, collateralPoolId, targetLtvBps } =\n request;\n\n const validationErrors: QuoteValidationError[] = [];\n const warnings: QuoteWarning[] = [];\n\n const borrowPool = pools.find((p) => p.id === borrowPoolId);\n const collateralPool = pools.find((p) => p.id === collateralPoolId);\n\n if (!borrowPool) {\n validationErrors.push({\n code: QuoteValidationErrorCode.POOL_NOT_FOUND,\n message: `Borrow pool not found: ${borrowPoolId}`,\n });\n }\n\n if (!collateralPool) {\n validationErrors.push({\n code: QuoteValidationErrorCode.POOL_NOT_FOUND,\n message: `Collateral pool not found: ${collateralPoolId}`,\n });\n }\n\n if (!borrowPool || !collateralPool) {\n return createQuoteResult({\n borrowAmount,\n borrowPoolId,\n collateralPoolId,\n borrowUsd: 0n,\n requiredCollateralAmount: 0n,\n requiredCollateralUsd: 0n,\n maxAllowedLtvBps: 0n,\n targetLtvBps,\n borrowAsset: \"\",\n collateralAsset: \"\",\n validationErrors,\n warnings,\n });\n }\n\n const borrowAsset = borrowPool.asset;\n const collateralAsset = collateralPool.asset;\n const borrowPrice = prices[borrowAsset];\n const collateralPrice = prices[collateralAsset];\n\n if (\n borrowPrice === undefined ||\n !Number.isFinite(borrowPrice) ||\n borrowPrice <= 0\n ) {\n validationErrors.push({\n code: QuoteValidationErrorCode.PRICE_NOT_AVAILABLE,\n message: `Price not available for borrow asset: ${borrowAsset}`,\n });\n }\n\n if (\n collateralPrice === undefined ||\n !Number.isFinite(collateralPrice) ||\n collateralPrice <= 0\n ) {\n validationErrors.push({\n code: QuoteValidationErrorCode.PRICE_NOT_AVAILABLE,\n message: `Price not available for collateral asset: ${collateralAsset}`,\n });\n }\n\n if (borrowAmount < 0n) {\n validationErrors.push({\n code: QuoteValidationErrorCode.BORROW_AMOUNT_TOO_LOW,\n message: `Borrow amount must be non-negative`,\n });\n } else if (borrowAmount < MIN_BORROW_AMOUNT_BASE_UNITS) {\n validationErrors.push({\n code: QuoteValidationErrorCode.BORROW_AMOUNT_TOO_LOW,\n message: `Borrow amount must be at least ${MIN_BORROW_AMOUNT_BASE_UNITS} base units`,\n });\n }\n\n if (targetLtvBps <= MIN_LTV_BPS) {\n validationErrors.push({\n code: QuoteValidationErrorCode.INVALID_LTV,\n message: `LTV must be greater than 0`,\n });\n }\n\n if (targetLtvBps > BASIS_POINTS_DENOMINATOR) {\n validationErrors.push({\n code: QuoteValidationErrorCode.INVALID_LTV,\n message: `LTV must not exceed ${formatBpsAsPercent(BASIS_POINTS_DENOMINATOR)}%`,\n });\n }\n\n const maxAllowedLtvBps = collateralPool.maxLtv;\n if (targetLtvBps > maxAllowedLtvBps) {\n validationErrors.push({\n code: QuoteValidationErrorCode.LTV_EXCEEDS_MAX,\n message: `Target LTV ${formatBpsAsPercent(targetLtvBps)}% exceeds max allowed ${formatBpsAsPercent(maxAllowedLtvBps)}%`,\n });\n }\n\n const isSameAssetBorrowingRequest = borrowAsset === collateralAsset;\n if (isSameAssetBorrowingRequest && !collateralPool.sameAssetBorrowing) {\n validationErrors.push({\n code: QuoteValidationErrorCode.SAME_ASSET_NOT_ALLOWED,\n message: `Same asset borrowing not allowed for pool ${collateralPoolId}`,\n });\n }\n\n if (isSameAssetBorrowingRequest && collateralPool.sameAssetBorrowing) {\n warnings.push({\n code: QuoteWarningCode.SAME_ASSET_BORROWING,\n message: `Using same asset for borrow and collateral`,\n });\n }\n\n if (targetLtvBps >= HIGH_LTV_WARNING_THRESHOLD_BPS) {\n warnings.push({\n code: QuoteWarningCode.HIGH_LTV,\n message: `LTV above ${formatBpsAsPercent(HIGH_LTV_WARNING_THRESHOLD_BPS)}% may put your position at higher risk of liquidation`,\n });\n }\n\n if (validationErrors.length > 0) {\n return createQuoteResult({\n borrowAmount,\n borrowPoolId,\n collateralPoolId,\n borrowUsd: 0n,\n requiredCollateralAmount: 0n,\n requiredCollateralUsd: 0n,\n maxAllowedLtvBps,\n targetLtvBps,\n borrowAsset,\n collateralAsset,\n validationErrors,\n warnings,\n });\n }\n\n const borrowAssetDecimals = getPoolDecimalPlaces(borrowPool);\n const collateralAssetDecimals = getPoolDecimalPlaces(collateralPool);\n const borrowPriceScaled = scalePriceUsdToBigint(borrowPrice as number);\n const collateralPriceScaled = scalePriceUsdToBigint(\n collateralPrice as number\n );\n\n const borrowUsdInternal = computeUsdInternalFromBaseUnits({\n amountBaseUnits: borrowAmount,\n priceScaled: borrowPriceScaled,\n assetDecimalPlaces: borrowAssetDecimals,\n });\n\n const requiredCollateralUsdInternal = ceilDivBigint(\n borrowUsdInternal * BASIS_POINTS_DENOMINATOR,\n targetLtvBps\n );\n\n const requiredCollateralAmount = computeBaseUnitsFromUsdInternalCeil({\n usdInternal: requiredCollateralUsdInternal,\n priceScaled: collateralPriceScaled,\n assetDecimalPlaces: collateralAssetDecimals,\n });\n\n return createQuoteResult({\n borrowAmount,\n borrowPoolId,\n collateralPoolId,\n borrowUsd: borrowUsdInternal,\n requiredCollateralAmount,\n requiredCollateralUsd: requiredCollateralUsdInternal,\n maxAllowedLtvBps,\n targetLtvBps,\n borrowAsset,\n collateralAsset,\n validationErrors,\n warnings,\n });\n }\n}\n\nfunction createLtvCalculation(params: {\n request: CalculateLtvRequest;\n borrowUsd: bigint;\n collateralUsd: bigint;\n ltvBps: bigint;\n maxAllowedLtvBps: bigint;\n borrowAsset: string;\n collateralAsset: string;\n validationErrors: QuoteValidationError[];\n}): LtvCalculation {\n return {\n borrowAmount: params.request.borrowAmount,\n collateralAmount: params.request.collateralAmount,\n borrowUsd: params.borrowUsd,\n collateralUsd: params.collateralUsd,\n ltvBps: params.ltvBps,\n maxAllowedLtvBps: params.maxAllowedLtvBps,\n borrowPoolId: params.request.borrowPoolId,\n collateralPoolId: params.request.collateralPoolId,\n borrowAsset: params.borrowAsset,\n collateralAsset: params.collateralAsset,\n validationErrors: params.validationErrors,\n };\n}\n\nfunction createQuoteResult(params: CreateQuoteResultParams): QuoteResult {\n return {\n borrowAmount: params.borrowAmount,\n borrowUsd: params.borrowUsd,\n requiredCollateralAmount: params.requiredCollateralAmount,\n requiredCollateralUsd: params.requiredCollateralUsd,\n maxAllowedLtvBps: params.maxAllowedLtvBps,\n targetLtvBps: params.targetLtvBps,\n borrowPoolId: params.borrowPoolId,\n collateralPoolId: params.collateralPoolId,\n borrowAsset: params.borrowAsset,\n collateralAsset: params.collateralAsset,\n validationErrors: params.validationErrors,\n warnings: params.warnings,\n };\n}\n\nfunction computeUsdInternalFromBaseUnits(params: {\n amountBaseUnits: bigint;\n priceScaled: bigint;\n assetDecimalPlaces: number;\n}): bigint {\n const { amountBaseUnits, priceScaled, assetDecimalPlaces } = params;\n const scaleDiff = INTERNAL_USD_DECIMAL_PLACES - PRICE_SCALE_DECIMAL_PLACES;\n const numerator = amountBaseUnits * priceScaled;\n const assetDecimalFactor = 10n ** BigInt(assetDecimalPlaces);\n\n if (scaleDiff >= 0) {\n return (numerator * 10n ** BigInt(scaleDiff)) / assetDecimalFactor;\n }\n\n return numerator / (assetDecimalFactor * 10n ** BigInt(-scaleDiff));\n}\n\nfunction computeBaseUnitsFromUsdInternalCeil(params: {\n usdInternal: bigint;\n priceScaled: bigint;\n assetDecimalPlaces: number;\n}): bigint {\n const { usdInternal, priceScaled, assetDecimalPlaces } = params;\n const scaleDiff = INTERNAL_USD_DECIMAL_PLACES - PRICE_SCALE_DECIMAL_PLACES;\n const assetDecimalFactor = 10n ** BigInt(assetDecimalPlaces);\n\n if (scaleDiff >= 0) {\n return ceilDivBigint(\n usdInternal * assetDecimalFactor,\n priceScaled * 10n ** BigInt(scaleDiff)\n );\n }\n\n return ceilDivBigint(\n usdInternal * assetDecimalFactor * 10n ** BigInt(-scaleDiff),\n priceScaled\n );\n}\n\nfunction roundDivBigint(numerator: bigint, denominator: bigint): bigint {\n return (numerator + denominator / 2n) / denominator;\n}\n\nfunction scalePriceUsdToBigint(priceUsd: number): bigint {\n const scaled = Math.round(priceUsd * 10 ** PRICE_SCALE_DECIMAL_PLACES);\n return BigInt(scaled);\n}\n\nfunction isValidPrice(price: number | undefined): price is number {\n return typeof price === \"number\" && Number.isFinite(price) && price > 0;\n}\n\nfunction getPoolDecimalPlaces(pool: Pool): number {\n return Number(pool.decimals);\n}\n\nfunction formatBpsAsPercent(bps: bigint): string {\n const whole = bps / BPS_PER_PERCENT;\n const fractional = bps % BPS_PER_PERCENT;\n if (fractional === 0n) {\n return whole.toString();\n }\n\n const padded = fractional.toString().padStart(2, \"0\").replace(/0+$/, \"\");\n return `${whole}.${padded}`;\n}\n","import {\n createInstantLoansActor,\n type HeadlessLoanEvent,\n type HeadlessLoanEventType,\n type InstantLoanAccountType,\n type InstantLoanAuthorisation,\n type InstantLoanLeg as InstantLoanCanisterLeg,\n type InstantLoanCanisterRecord,\n type InstantLoansCanisterError,\n type WarmedProfile,\n} from \"../../core/canisters/instant-loans/actor\";\nimport { mapCanisterCallErrorToLiquidiumError } from \"../../core/canisters/lending/error-mappers\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport {\n buildInstantLoanAddressLookupPath,\n SdkApiPath,\n} from \"../../core/sdk-api-paths\";\nimport type { ApiClient } from \"../../core/transports/api-client\";\nimport type { CanisterContext } from \"../../core/transports/canister-context\";\nimport { type Asset, type Chain, SupplyAction } from \"../../core/types\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport { resolveSupplyTarget } from \"../lending/_internal/supply-targets\";\nimport type { LendingModule } from \"../lending/lending\";\nimport { SupplyPlanType } from \"../lending/types\";\nimport type { PositionsModule } from \"../positions\";\nimport type { Position } from \"../positions/types\";\nimport { QuoteModule } from \"../quote\";\nimport { QuoteValidationErrorCode } from \"../quote/types\";\nimport { intFromPublicId, publicIdFromInt } from \"./ref-code\";\nimport type {\n CreateInstantLoanRequest,\n ExternalAccount,\n InstantLoan,\n InstantLoanAccount,\n InstantLoanAsset,\n InstantLoanAuthorization,\n InstantLoanCandidate,\n InstantLoanConfig,\n InstantLoanEvent,\n InstantLoanEventType,\n InstantLoanGetRequest,\n InstantLoanLeg,\n InstantLoanListEventsRequest,\n InstantLoanStatus,\n InstantLoanWarmedProfile,\n} from \"./types\";\n\nconst REPAYMENT_BUFFER_SECONDS = 86_400n;\nconst RATE_SCALE = 10n ** 27n;\nconst SECONDS_PER_YEAR = 31_536_000n;\nconst ETH_STABLECOIN_INFLOW_FEE_FALLBACK = 1_500_000n;\nconst INSTANT_LOAN_MIN_SLIPPAGE_BUFFER_BPS = 200n;\n\ntype InstantLoanLtvPolicy = {\n ltvBps: bigint;\n minLtvMaxBps: bigint;\n maxLtvMaxBps: bigint;\n};\n\ntype InstantLoanCandidateWire = {\n loanId?: string | bigint;\n loan_id?: string | bigint;\n ref?: string;\n short_ref?: string;\n profileId?: string;\n lending_profile?: string;\n createdAt?: string;\n created_at?: string;\n collateralPoolId?: string;\n lend_pool_ic_id?: string;\n borrowPoolId?: string;\n borrow_pool_ic_id?: string;\n collateralAsset?: string;\n lend_asset?: string;\n borrowAsset?: string;\n borrow_asset?: string;\n collateralAmountHint?: string | bigint;\n min_deposit_hint?: string | bigint;\n};\n\ntype InstantLoanCreateRequestWire = {\n collateralPoolId: string;\n borrowPoolId: string;\n collateralAsset: InstantLoanAsset;\n borrowAsset: InstantLoanAsset;\n collateralAmount: string;\n borrowAmount: string;\n ltvMaxBps: string;\n depositWindowSeconds: string;\n borrowDestination: InstantLoanCreateAccountWire;\n refundDestination: InstantLoanCreateAccountWire;\n};\n\ntype InstantLoanCreateAccountWire = { External: string };\ntype InstantLoanAccountVariantWire =\n | InstantLoanCreateAccountWire\n | { Native: string };\n\ntype InstantLoanAccountWire =\n | { address: string; type: \"External\" }\n | { principal: string; type: \"Native\" }\n | InstantLoanAccountVariantWire;\n\ntype InstantLoanWire = {\n loanId: string | bigint;\n ref?: string;\n profileId: string;\n ltvMaxBps: string | bigint;\n depositWindowSeconds: string | bigint;\n collateral: {\n poolId: string;\n asset: string;\n amountHint: string | bigint;\n };\n borrow: {\n poolId: string;\n asset: string;\n amount: string | bigint;\n destination: InstantLoanAccountWire;\n };\n refundDestination: InstantLoanAccountWire;\n};\n\ntype InstantLoanHydrationInput = {\n loanId: bigint;\n profileId: string;\n ltvMaxBps: bigint;\n depositWindowSeconds: bigint;\n collateralPoolId: string;\n borrowPoolId: string;\n collateralAsset: string;\n borrowAsset: string;\n borrowAmount: bigint;\n borrowDestination: InstantLoanAccount;\n refundDestination: InstantLoanAccount;\n started?: boolean;\n};\n\n/** Accountless instant-loan creation, lookup, recovery, and canister query helpers. */\nexport class InstantLoansModule {\n constructor(\n readonly canisterContext: CanisterContext,\n readonly apiClient: ApiClient | undefined,\n readonly lending: LendingModule,\n readonly positions: PositionsModule\n ) {}\n\n /**\n * Creates a profileless instant loan and returns canonical canister state plus\n * deposit/repay targets for the generated lending profile.\n *\n * Choose `collateralPoolId` and `borrowPoolId` from\n * `client.market.listPools()`, convert UI amounts to base units with the\n * selected pool decimals, and call `client.quote.calculateLtv(...)` before\n * creation to block invalid LTV input.\n *\n * `borrowDestination` receives the borrowed asset after the loan starts.\n * `refundDestination` receives collateral refunds or withdrawals. Use\n * `depositWindowSeconds` for the user-facing collateral deposit timeout; the\n * SDK maps it to the canister's internal `ltv_timer_s` field.\n *\n * @param request - Pool ids, assets, base-unit amounts, LTV limit, timeout, and destinations.\n * @returns Hydrated loan state plus generated deposit and repayment targets.\n */\n async create(request: CreateInstantLoanRequest): Promise<InstantLoan> {\n validateCreateRequest(request);\n const apiClient = this.requireApi(\"Instant loan creation\");\n\n await this.validateInstantLoanLtvPolicy(request);\n\n const response = await apiClient.post<\n { loan: InstantLoanWire; success?: true },\n InstantLoanCreateRequestWire\n >(SdkApiPath.instantLoans, {\n collateralPoolId: request.collateralPoolId,\n borrowPoolId: request.borrowPoolId,\n collateralAsset: request.collateralAsset,\n borrowAsset: request.borrowAsset,\n collateralAmount: request.collateralAmount.toString(),\n borrowAmount: request.borrowAmount.toString(),\n ltvMaxBps: request.ltvMaxBps.toString(),\n depositWindowSeconds: request.depositWindowSeconds.toString(),\n borrowDestination: accountWireFromInput(request.borrowDestination),\n refundDestination: accountWireFromInput(request.refundDestination),\n });\n\n const loan = await this.mapLoanWire(response.loan);\n\n return {\n ...loan,\n collateral: {\n ...loan.collateral,\n amount: request.collateralAmount,\n },\n };\n }\n\n /**\n * Resolves canonical canister state by loan id or short reference.\n *\n * References are decoded locally, then the corresponding loan id is loaded\n * from the instant-loans canister.\n *\n * @param request - Canister loan id or short public reference.\n * @returns Hydrated loan state plus generated deposit and repayment targets.\n */\n async get(request: InstantLoanGetRequest): Promise<InstantLoan> {\n const loanId =\n \"loanId\" in request ? request.loanId : decodeRef(request.ref);\n\n try {\n const result = await createInstantLoansActor(\n this.canisterContext\n ).get_loan(loanId);\n\n if (\"Err\" in result) {\n throw mapInstantLoansErrorToLiquidiumError(result.Err);\n }\n\n return await this.mapLoanRecord(result.Ok);\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_loan\", error);\n }\n }\n\n /**\n * Returns the active instant-loans canister config via direct query.\n *\n * @returns Active canister configuration.\n */\n async getConfig(): Promise<InstantLoanConfig> {\n try {\n const config = await createInstantLoansActor(\n this.canisterContext\n ).get_config();\n\n return {\n lendingCanisterId: config.lending_canister.toText(),\n };\n } catch (error) {\n throw mapCanisterCallErrorToLiquidiumError(\"get_config\", error);\n }\n }\n\n /**\n * Returns a single canister event by id via direct query.\n *\n * @param eventId - Event id to load.\n * @returns The event when found, otherwise `null`.\n */\n async getEvent(eventId: bigint): Promise<InstantLoanEvent | null> {\n try {\n const event = await createInstantLoansActor(\n this.canisterContext\n ).get_event(eventId);\n\n return event[0] ? mapInstantLoanEvent(event[0]) : null;\n } catch (error) {\n throw mapCanisterCallErrorToLiquidiumError(\"get_event\", error);\n }\n }\n\n /**\n * Returns a page of canister events via direct query.\n *\n * @param request - Start event id and maximum number of events to return.\n * @returns Canister events in ascending id order.\n */\n async listEvents(\n request: InstantLoanListEventsRequest\n ): Promise<InstantLoanEvent[]> {\n try {\n const events = await createInstantLoansActor(\n this.canisterContext\n ).list_events(request.start, request.limit);\n\n return events.map(([, event]) => mapInstantLoanEvent(event));\n } catch (error) {\n throw mapCanisterCallErrorToLiquidiumError(\"list_events\", error);\n }\n }\n\n /**\n * Returns principals authorized for protected update callbacks.\n *\n * @returns Principal text values on the canister access list.\n */\n async listAccessList(): Promise<string[]> {\n try {\n const principals = await createInstantLoansActor(\n this.canisterContext\n ).list_access_list();\n\n return principals.map((principal) => principal.toText());\n } catch (error) {\n throw mapCanisterCallErrorToLiquidiumError(\"list_access_list\", error);\n }\n }\n\n /**\n * Returns the current size of the warmed-profile pool via direct query.\n *\n * @returns Number of warmed profiles available on the canister.\n */\n async countWarmedProfiles(): Promise<bigint> {\n try {\n return await createInstantLoansActor(\n this.canisterContext\n ).count_warmed_profiles();\n } catch (error) {\n throw mapCanisterCallErrorToLiquidiumError(\n \"count_warmed_profiles\",\n error\n );\n }\n }\n\n /**\n * Returns warmed profiles currently available for future instant loans.\n *\n * @returns Warmed profile records available for assignment.\n */\n async listWarmedProfiles(): Promise<InstantLoanWarmedProfile[]> {\n try {\n const profiles = await createInstantLoansActor(\n this.canisterContext\n ).list_warmed_profiles();\n\n return profiles.map(mapWarmedProfile);\n } catch (error) {\n throw mapCanisterCallErrorToLiquidiumError(\"list_warmed_profiles\", error);\n }\n }\n\n /**\n * Finds candidate loans associated with an address through the Liquidium SDK\n * API. Returns discovery candidates only; call `get(...)` to hydrate canister state.\n *\n * Candidates are useful for recovery flows where the user knows a borrow or\n * refund address but not the loan reference.\n *\n * @param address - Borrow or refund address to search for.\n * @returns Lightweight loan candidates associated with the address.\n */\n async findByAddress(address: string): Promise<InstantLoanCandidate[]> {\n const trimmedAddress = address.trim();\n if (!trimmedAddress) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Address lookup requires a non-empty address\"\n );\n }\n\n const apiClient = this.requireApi(\"Instant loan address lookup\");\n const response = await apiClient.get<{\n success?: true;\n loans?: InstantLoanCandidateWire[];\n candidates?: InstantLoanCandidateWire[];\n }>(buildInstantLoanAddressLookupPath({ address: trimmedAddress }));\n\n return (response.candidates ?? response.loans ?? []).map(mapCandidateWire);\n }\n\n private async mapLoanRecord(\n record: InstantLoanCanisterRecord\n ): Promise<InstantLoan> {\n return await this.hydrateLoan({\n loanId: record.id,\n profileId: record.lending_profile.toText(),\n ltvMaxBps: record.ltv_max_bps,\n depositWindowSeconds: record.ltv_timer_s,\n collateralPoolId: record.lend_pool_id.toText(),\n borrowPoolId: record.borrow_pool_id.toText(),\n collateralAsset: getVariantKey(record.lend_asset),\n borrowAsset: getVariantKey(record.borrow_asset),\n borrowAmount: record.borrow_amount,\n borrowDestination: accountFromCanister(record.borrow_destination),\n refundDestination: accountFromCanister(record.refund_destination),\n started: record.started,\n });\n }\n\n private async mapLoanWire(loan: InstantLoanWire): Promise<InstantLoan> {\n const loanId = parseBigintWire(loan.loanId, \"loan ID\");\n\n return await this.hydrateLoan({\n loanId,\n profileId: loan.profileId,\n ltvMaxBps: parseBigintWire(loan.ltvMaxBps, \"max LTV\"),\n depositWindowSeconds: parseBigintWire(\n loan.depositWindowSeconds,\n \"deposit window\"\n ),\n collateralPoolId: loan.collateral.poolId,\n borrowPoolId: loan.borrow.poolId,\n collateralAsset: loan.collateral.asset,\n borrowAsset: loan.borrow.asset,\n borrowAmount: parseBigintWire(loan.borrow.amount, \"borrow amount\"),\n borrowDestination: accountFromWire(loan.borrow.destination),\n refundDestination: accountFromWire(loan.refundDestination),\n });\n }\n\n private async hydrateLoan(\n input: InstantLoanHydrationInput\n ): Promise<InstantLoan> {\n const profileId = input.profileId;\n const collateralPoolId = input.collateralPoolId;\n const borrowPoolId = input.borrowPoolId;\n const collateralAsset = input.collateralAsset;\n const borrowAsset = input.borrowAsset;\n\n const [\n depositTarget,\n repayTarget,\n collateralPosition,\n borrowPosition,\n borrowPoolRate,\n ] = await Promise.all([\n resolveSupplyTarget(this.canisterContext, {\n profileId,\n poolId: collateralPoolId,\n action: SupplyAction.deposit,\n mechanism: SupplyPlanType.transfer,\n }),\n resolveSupplyTarget(this.canisterContext, {\n profileId,\n poolId: borrowPoolId,\n action: SupplyAction.repayment,\n mechanism: SupplyPlanType.transfer,\n }),\n this.positions.getPosition(profileId, collateralPoolId),\n this.positions.getPosition(profileId, borrowPoolId),\n this.positions.market.getPoolRate(borrowPoolId),\n ]);\n const totalDebtAmount = calculateTotalDebtAmount(borrowPosition);\n const interestBufferAmount = calculateInterestBufferAmount(\n borrowPosition,\n borrowPoolRate.borrowRate\n );\n const repaymentInflowFee =\n totalDebtAmount > 0n\n ? await this.estimateRepaymentInflowFee(borrowAsset, repayTarget.chain)\n : { totalFee: 0n, estimateAvailable: false };\n const repaymentAmount =\n totalDebtAmount + interestBufferAmount + repaymentInflowFee.totalFee;\n const collateralAmount = collateralPosition?.deposited ?? 0n;\n const collateralDecimals = collateralPosition?.depositedDecimals ?? 0n;\n const collateralInterestAmount = collateralPosition?.earnedInterest ?? 0n;\n const borrowedAmount = borrowPosition?.borrowed ?? 0n;\n const borrowedDecimals = borrowPosition?.borrowedDecimals ?? 0n;\n const debtInterestAmount = borrowPosition?.debtInterest ?? 0n;\n const status = deriveInstantLoanStatus({\n collateralAmount,\n started: input.started,\n totalDebtAmount,\n });\n\n return {\n loanId: input.loanId,\n ref: publicIdFromInt(input.loanId),\n status,\n profileId,\n ltvMaxBps: input.ltvMaxBps,\n depositWindowSeconds: input.depositWindowSeconds,\n collateral: {\n poolId: collateralPoolId,\n asset: collateralAsset,\n chain: depositTarget.chain,\n amount: collateralAmount,\n },\n borrow: {\n poolId: borrowPoolId,\n asset: borrowAsset,\n chain: repayTarget.chain,\n amount: input.borrowAmount,\n destination: input.borrowDestination,\n },\n refundDestination: input.refundDestination,\n depositTarget,\n repayTarget,\n repayment: {\n amount: repaymentAmount,\n decimals: borrowedDecimals,\n debtAmount: totalDebtAmount,\n interestBufferAmount,\n interestBufferSeconds: REPAYMENT_BUFFER_SECONDS,\n inflowFeeAmount: repaymentInflowFee.totalFee,\n inflowFeeEstimateAvailable: repaymentInflowFee.estimateAvailable,\n asset: borrowAsset,\n chain: repayTarget.chain,\n target: repayTarget,\n },\n position: {\n collateralAmount,\n collateralDecimals,\n collateralInterestAmount,\n borrowedAmount,\n borrowedDecimals,\n debtInterestAmount,\n totalDebtAmount,\n },\n };\n }\n\n private async estimateRepaymentInflowFee(\n asset: string,\n chain: string\n ): Promise<{ totalFee: bigint; estimateAvailable: boolean }> {\n try {\n const fee = await this.lending.estimateInflowFee({\n asset: asset as Asset,\n chain: chain as Chain,\n });\n return { totalFee: fee.totalFee, estimateAvailable: true };\n } catch {\n return {\n totalFee: getRepaymentInflowFeeFallback(asset, chain),\n estimateAvailable: false,\n };\n }\n }\n\n private requireApi(action: string): ApiClient {\n if (!this.apiClient) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `${action} requires an API client`\n );\n }\n\n return this.apiClient;\n }\n\n private async validateInstantLoanLtvPolicy(\n request: CreateInstantLoanRequest\n ): Promise<void> {\n const ltvCalculation = await this.calculateInstantLoanLtv(request);\n\n if (request.ltvMaxBps < ltvCalculation.minLtvMaxBps) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Instant loan max LTV ${formatBpsAsPercent(request.ltvMaxBps)} is below minimum allowed ${formatBpsAsPercent(ltvCalculation.minLtvMaxBps)} (current implied LTV ${formatBpsAsPercent(ltvCalculation.ltvBps)} + ${formatBpsAsPercent(INSTANT_LOAN_MIN_SLIPPAGE_BUFFER_BPS)} buffer)`\n );\n }\n\n if (request.ltvMaxBps > ltvCalculation.maxLtvMaxBps) {\n throw new LiquidiumError(\n LiquidiumErrorCode.MAX_LTV_EXCEEDED,\n `Instant loan max LTV ${formatBpsAsPercent(request.ltvMaxBps)} exceeds collateral pool max ${formatBpsAsPercent(ltvCalculation.maxLtvMaxBps)}`\n );\n }\n }\n\n private async calculateInstantLoanLtv(\n request: CreateInstantLoanRequest\n ): Promise<InstantLoanLtvPolicy> {\n const [pools, assetPrices] = await Promise.all([\n this.positions.market.listPools(),\n this.positions.market.getAssetPrices(),\n ]);\n const ltvCalculation = new QuoteModule().calculateLtv(\n {\n borrowAmount: request.borrowAmount,\n borrowPoolId: request.borrowPoolId,\n collateralAmount: request.collateralAmount,\n collateralPoolId: request.collateralPoolId,\n },\n pools,\n assetPrices\n );\n\n if (ltvCalculation.validationErrors.length > 0) {\n throwLtvCalculationError(ltvCalculation.validationErrors[0]);\n }\n\n const minLtvMaxBps =\n ltvCalculation.ltvBps + INSTANT_LOAN_MIN_SLIPPAGE_BUFFER_BPS;\n\n return {\n ltvBps: ltvCalculation.ltvBps,\n minLtvMaxBps,\n maxLtvMaxBps: ltvCalculation.maxAllowedLtvBps,\n };\n }\n}\n\nfunction getRepaymentInflowFeeFallback(asset: string, chain: string): bigint {\n if (chain === \"ETH\" && (asset === \"USDT\" || asset === \"USDC\")) {\n return ETH_STABLECOIN_INFLOW_FEE_FALLBACK;\n }\n\n return 0n;\n}\n\nfunction calculateInterestBufferAmount(\n borrowPosition: Position | null,\n annualBorrowRate: bigint\n): bigint {\n const totalDebtAmount = calculateTotalDebtAmount(borrowPosition);\n if (totalDebtAmount <= 0n || annualBorrowRate <= 0n) {\n return 0n;\n }\n\n const interestBuffer =\n (totalDebtAmount * annualBorrowRate * REPAYMENT_BUFFER_SECONDS) /\n RATE_SCALE /\n SECONDS_PER_YEAR;\n\n return interestBuffer > 1n ? interestBuffer : 1n;\n}\n\nfunction calculateTotalDebtAmount(borrowPosition: Position | null): bigint {\n if (!borrowPosition) {\n return 0n;\n }\n\n return borrowPosition.borrowed + borrowPosition.debtInterest;\n}\n\nfunction deriveInstantLoanStatus(input: {\n collateralAmount: bigint;\n started: boolean | undefined;\n totalDebtAmount: bigint;\n}): InstantLoanStatus {\n if (input.totalDebtAmount > 0n) {\n return \"active\";\n }\n\n if (input.collateralAmount > 0n) {\n return input.started ? \"settling\" : \"deposit_detected\";\n }\n\n if (input.started) {\n return \"closed\";\n }\n\n return \"awaiting_deposit\";\n}\n\nfunction validateCreateRequest(request: CreateInstantLoanRequest): void {\n if (request.collateralAmount <= 0n) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Instant loan collateral amount must be greater than zero\"\n );\n }\n if (request.borrowAmount <= 0n) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Instant loan borrow amount must be greater than zero\"\n );\n }\n if (request.ltvMaxBps <= 0n) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Instant loan max LTV must be greater than zero\"\n );\n }\n if (request.depositWindowSeconds <= 0n) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Instant loan deposit window must be greater than zero seconds\"\n );\n }\n}\n\nfunction throwLtvCalculationError(\n error: { code: QuoteValidationErrorCode; message: string } | undefined\n): never {\n throw new LiquidiumError(\n error?.code === QuoteValidationErrorCode.POOL_NOT_FOUND\n ? LiquidiumErrorCode.POOL_NOT_FOUND\n : LiquidiumErrorCode.VALIDATION_ERROR,\n error?.message ?? \"Unable to calculate instant loan LTV\"\n );\n}\n\nfunction accountWireFromInput(\n account: string | ExternalAccount\n): InstantLoanCreateAccountWire {\n const address =\n typeof account === \"string\" ? account.trim() : account.address.trim();\n if (!address) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Instant loan account address must be non-empty\"\n );\n }\n\n return { External: address };\n}\n\nfunction accountFromCanister(\n account: InstantLoanAccountType\n): InstantLoanAccount {\n if (\"Native\" in account) {\n return { type: \"Native\", principal: account.Native.toText() };\n }\n\n return { type: \"External\", address: account.External };\n}\n\nfunction accountFromWire(account: InstantLoanAccountWire): InstantLoanAccount {\n if (\"Native\" in account) {\n return { type: \"Native\", principal: account.Native };\n }\n\n if (\"External\" in account) {\n return { type: \"External\", address: account.External };\n }\n\n if (account.type === \"Native\") {\n return { type: \"Native\", principal: account.principal };\n }\n\n return { type: \"External\", address: account.address };\n}\n\nfunction mapInstantLoanEvent(event: HeadlessLoanEvent): InstantLoanEvent {\n return {\n id: event.id,\n schemaVersion: event.schema_version,\n timestamp: event.timestamp,\n eventType: mapInstantLoanEventType(event.event_type),\n };\n}\n\nfunction mapInstantLoanEventType(\n eventType: HeadlessLoanEventType\n): InstantLoanEventType {\n if (\"LoanCreated\" in eventType) {\n const event = eventType.LoanCreated;\n return {\n type: \"LoanCreated\",\n loanId: event.loan_id,\n borrowDestination: accountFromCanister(event.borrow_destination),\n collateralAsset: assetFromCanister(event.lend_asset),\n borrowAmount: event.borrow_amount,\n collateralPoolId: event.lend_pool_id.toText(),\n refundDestination: accountFromCanister(event.refund_destination),\n ltvMaxBps: event.ltv_max_bps,\n depositWindowSeconds: event.ltv_timer_s,\n profileId: event.lending_profile.toText(),\n borrowPoolId: event.borrow_pool_id.toText(),\n borrowAsset: assetFromCanister(event.borrow_asset),\n };\n }\n\n if (\"FullLendWithdrawalRequested\" in eventType) {\n const event = eventType.FullLendWithdrawalRequested;\n return {\n type: \"FullLendWithdrawalRequested\",\n loanId: event.loan_id,\n account: accountFromCanister(event.account),\n poolId: event.pool_id.toText(),\n };\n }\n\n if (\"BorrowRequested\" in eventType) {\n const event = eventType.BorrowRequested;\n return {\n type: \"BorrowRequested\",\n loanId: event.loan_id,\n account: accountFromCanister(event.account),\n poolId: event.pool_id.toText(),\n amount: event.amount,\n };\n }\n\n if (\"DepositTimerExceeded\" in eventType) {\n return {\n type: \"DepositTimerExceeded\",\n loanId: eventType.DepositTimerExceeded.loan_id,\n };\n }\n\n if (\"StuckFundsWithdrawalRequested\" in eventType) {\n const event = eventType.StuckFundsWithdrawalRequested;\n return {\n type: \"StuckFundsWithdrawalRequested\",\n leg: legFromCanister(event.leg),\n loanId: event.loan_id,\n account: accountFromCanister(event.account),\n poolId: event.pool_id.toText(),\n amount: event.amount,\n };\n }\n\n if (\"ProfileWarmed\" in eventType) {\n const event = eventType.ProfileWarmed;\n return {\n type: \"ProfileWarmed\",\n derivationIndex: event.derivation_index,\n warmedProfileId: event.warmed_profile_id,\n ethAddress: event.eth_address,\n profileId: event.lending_profile.toText(),\n };\n }\n\n if (\"RepayComplete\" in eventType) {\n return {\n type: \"RepayComplete\",\n loanId: eventType.RepayComplete.loan_id,\n profileId: eventType.RepayComplete.lending_profile.toText(),\n };\n }\n\n return {\n type: \"DepositTimerStarted\",\n loanId: eventType.DepositTimerStarted.loan_id,\n timestamp: eventType.DepositTimerStarted.timestamp,\n };\n}\n\nfunction mapWarmedProfile(profile: WarmedProfile): InstantLoanWarmedProfile {\n return {\n id: profile.id,\n authorization: authorizationFromCanister(profile.authorisation),\n createdAt: profile.created_at,\n profileId: profile.lending_profile.toText(),\n };\n}\n\nfunction authorizationFromCanister(\n authorization: InstantLoanAuthorisation\n): InstantLoanAuthorization {\n return {\n type: \"EthSignature\",\n derivationIndex: authorization.EthSignature.derivation_index,\n publicKey: authorization.EthSignature.pubkey,\n address: authorization.EthSignature.address,\n };\n}\n\nfunction assetFromCanister(asset: { [key: string]: null }): InstantLoanAsset {\n return getVariantKey(asset) as InstantLoanAsset;\n}\n\nfunction legFromCanister(leg: InstantLoanCanisterLeg): InstantLoanLeg {\n return getVariantKey(leg) as InstantLoanLeg;\n}\n\nfunction decodeRef(ref: string): bigint {\n try {\n return intFromPublicId(ref.trim());\n } catch (error) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Invalid instant loan reference\",\n error\n );\n }\n}\n\nfunction mapCandidateWire(\n wire: InstantLoanCandidateWire\n): InstantLoanCandidate {\n const loanId = parseBigintWire(wire.loanId ?? wire.loan_id, \"loan ID\");\n const ref = wire.ref ?? wire.short_ref ?? publicIdFromInt(loanId);\n const createdAt = wire.createdAt ?? wire.created_at;\n\n return {\n loanId,\n ref,\n profileId: requiredString(\n wire.profileId ?? wire.lending_profile,\n \"profile ID\"\n ),\n ...(createdAt ? { createdAt: new Date(createdAt) } : {}),\n collateralPoolId: requiredString(\n wire.collateralPoolId ?? wire.lend_pool_ic_id,\n \"collateral pool ID\"\n ),\n borrowPoolId: requiredString(\n wire.borrowPoolId ?? wire.borrow_pool_ic_id,\n \"borrow pool ID\"\n ),\n collateralAsset: requiredString(\n wire.collateralAsset ?? wire.lend_asset,\n \"collateral asset\"\n ),\n borrowAsset: requiredString(\n wire.borrowAsset ?? wire.borrow_asset,\n \"borrow asset\"\n ),\n collateralAmountHint: parseBigintWire(\n wire.collateralAmountHint ?? wire.min_deposit_hint,\n \"collateral amount hint\"\n ),\n };\n}\n\nfunction parseBigintWire(\n value: string | bigint | undefined,\n label: string\n): bigint {\n if (typeof value === \"bigint\") return value;\n if (typeof value === \"string\" && /^\\d+$/.test(value)) return BigInt(value);\n\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Invalid instant loan ${label}`\n );\n}\n\nfunction requiredString(value: string | undefined, label: string): string {\n if (value?.trim()) return value;\n\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Missing instant loan ${label}`\n );\n}\n\nfunction mapInstantLoansErrorToLiquidiumError(\n error: InstantLoansCanisterError\n): LiquidiumError {\n const [key, payload] = Object.entries(error)[0] as [string, unknown];\n\n switch (key) {\n case \"LoanNotFound\":\n case \"NoCollateralPosition\":\n return new LiquidiumError(\n LiquidiumErrorCode.POSITION_NOT_FOUND,\n stringifyErrorPayload(payload)\n );\n case \"LtvMaxExceeded\":\n case \"LtvMaxOutOfRange\":\n return new LiquidiumError(\n LiquidiumErrorCode.MAX_LTV_EXCEEDED,\n stringifyErrorPayload(payload)\n );\n case \"LtvTimerOutOfRange\":\n case \"InvalidLtvTimerS\":\n return new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n stringifyErrorPayload(payload) ?? key\n );\n case \"AccountRequired\":\n return new LiquidiumError(\n LiquidiumErrorCode.INVALID_ADDRESS,\n stringifyErrorPayload(payload)\n );\n case \"BorrowAmountRequired\":\n return new LiquidiumError(\n LiquidiumErrorCode.BORROW_CAP_EXCEEDED,\n stringifyErrorPayload(payload)\n );\n case \"AuthorizationFailed\":\n case \"UnauthorizedAccessListCaller\":\n return new LiquidiumError(\n LiquidiumErrorCode.NOT_ALLOWED,\n stringifyErrorPayload(payload)\n );\n default:\n return new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n stringifyErrorPayload(payload) ?? key\n );\n }\n}\n\nfunction stringifyErrorPayload(payload: unknown): string | undefined {\n if (payload === null || payload === undefined) return undefined;\n if (typeof payload === \"string\") return payload;\n\n return JSON.stringify(payload, (_key, value) => {\n if (typeof value === \"bigint\") return value.toString();\n if (value && typeof value === \"object\" && \"toText\" in value) {\n return (value as { toText: () => string }).toText();\n }\n\n return value;\n });\n}\n\nfunction formatBpsAsPercent(value: bigint): string {\n const sign = value < 0n ? \"-\" : \"\";\n const absoluteValue = value < 0n ? -value : value;\n const wholePart = absoluteValue / 100n;\n const fractionalPart = (absoluteValue % 100n).toString().padStart(2, \"0\");\n\n return `${sign}${wholePart.toString()}.${fractionalPart}%`;\n}\n","import type { Chain, MarketAsset, MarketChain } from \"../../core/types\";\nimport type { SupplyTarget } from \"../lending\";\n\n/** Asset symbols supported by the instant-loans canister. */\nexport type InstantLoanAsset = \"BTC\" | \"SOL\" | \"USDC\" | \"USDT\";\n\n/** External chain account used for borrow delivery or collateral refunds. */\nexport interface ExternalAccount {\n /**\n * Account kind discriminator.\n *\n * Use `External` for addresses outside the IC, such as BTC, Solana, or EVM\n * addresses. Instant-loan creation currently accepts external destinations.\n */\n type: \"External\";\n /**\n * Optional chain metadata for display and caller-side validation.\n *\n * The instant-loan API only sends `address` to the canister. Include `chain`\n * when your UI needs to remember which network the address belongs to.\n */\n chain?: Chain | MarketChain;\n /**\n * Destination address on the external chain.\n *\n * For `borrowDestination`, this receives the borrowed asset. For\n * `refundDestination`, this receives collateral refunds or withdrawals.\n */\n address: string;\n}\n\n/** IC principal account returned when a canister-native destination is used. */\nexport interface NativeAccount {\n /** Account kind discriminator. */\n type: \"Native\";\n /** Principal text for the canister-native account. */\n principal: string;\n}\n\n/** Borrow destination or refund account associated with an instant loan. */\nexport type InstantLoanAccount = ExternalAccount | NativeAccount;\n\n/**\n * Parameters for creating an accountless instant loan.\n *\n * Use market data from `client.market.listPools()` to choose the two pool ids,\n * and use `client.quote.calculateLtv(...)` before creation to validate the\n * amount pair and choose `ltvMaxBps`.\n *\n * Amount fields are in each asset's smallest/base units. For example, BTC uses\n * satoshis and ERC-20 assets use token base units according to the selected\n * pool decimals.\n */\nexport interface CreateInstantLoanRequest {\n /**\n * Principal text of the pool that receives the user's collateral deposit.\n *\n * This should be the `id` of the collateral `Pool` selected from\n * `client.market.listPools()`. The pool asset must match `collateralAsset`.\n */\n collateralPoolId: string;\n /**\n * Principal text of the pool that funds the borrow.\n *\n * This should be the `id` of the borrow `Pool` selected from\n * `client.market.listPools()`. The pool asset must match `borrowAsset`.\n */\n borrowPoolId: string;\n /**\n * Asset the user will deposit as collateral.\n *\n * Must match the asset for `collateralPoolId`; for example, use `\"BTC\"` with\n * a BTC collateral pool.\n */\n collateralAsset: InstantLoanAsset;\n /**\n * Asset the user wants to borrow from the borrow pool.\n *\n * Must match the asset for `borrowPoolId`; for example, use `\"USDC\"` with a\n * USDC borrow pool.\n */\n borrowAsset: InstantLoanAsset;\n /**\n * Amount the user is expected to deposit as collateral, in base units.\n *\n * This is used to validate LTV and initialize the loan record. For BTC, pass\n * satoshis. For token assets, convert the UI amount using the selected pool's\n * `decimals` value.\n */\n collateralAmount: bigint;\n /**\n * Amount to borrow, in the borrow asset's base units.\n *\n * For USDC/USDT, convert the UI amount using the selected borrow pool's\n * `decimals` value before passing it here.\n */\n borrowAmount: bigint;\n /**\n * Maximum allowed loan-to-value ratio in basis points.\n *\n * `6_000n` means 60%. Use `client.quote.calculateLtv(...)` to calculate the\n * implied LTV for the selected amounts and pass the policy value your app is\n * willing to accept. Creation is rejected if the requested borrow would exceed\n * this limit.\n */\n ltvMaxBps: bigint;\n /**\n * Seconds allowed for the user to send collateral after loan creation.\n *\n * If the collateral deposit is not detected before this window expires, the\n * instant-loan flow can time out. Internally this is sent to the canister as\n * `ltv_timer_s`.\n */\n depositWindowSeconds: bigint;\n /**\n * External destination that receives the borrowed asset after the loan starts.\n *\n * Pass either an address string or `{ type: \"External\", address }`. This is\n * usually the user's wallet address on the borrow asset's chain, such as an\n * EVM address for ETH USDC/USDT outflows.\n */\n borrowDestination: string | ExternalAccount;\n /**\n * External destination that receives collateral refunds or withdrawals.\n *\n * Pass either an address string or `{ type: \"External\", address }`. This\n * should be an address on the collateral asset's chain, such as a BTC address\n * when `collateralAsset` is `\"BTC\"`.\n */\n refundDestination: string | ExternalAccount;\n}\n\n/** Lookup request for loading canonical instant-loan state. */\nexport type InstantLoanGetRequest = { loanId: bigint } | { ref: string };\n\n/** Page request for direct instant-loan canister event queries. */\nexport interface InstantLoanListEventsRequest {\n /** Event id to start from. */\n start: bigint;\n /** Maximum number of events to return. */\n limit: bigint;\n}\n\n/** Active instant-loans canister config. */\nexport interface InstantLoanConfig {\n /** Principal text of the lending canister used by instant loans. */\n lendingCanisterId: string;\n}\n\n/** Authentication metadata for warmed instant-loan profiles. */\nexport interface InstantLoanAuthorization {\n type: \"EthSignature\";\n derivationIndex: Uint8Array;\n publicKey: Uint8Array;\n address: string;\n}\n\n/** Warmed profile available for a future instant loan. */\nexport interface InstantLoanWarmedProfile {\n id: bigint;\n authorization: InstantLoanAuthorization;\n createdAt: bigint;\n profileId: string;\n}\n\n/** Direct canister event returned by the instant-loans query API. */\nexport interface InstantLoanEvent {\n id: bigint;\n schemaVersion: number;\n timestamp: bigint;\n eventType: InstantLoanEventType;\n}\n\n/** Instant-loan leg used when stuck funds are withdrawn. */\nexport type InstantLoanLeg = \"Lend\" | \"Borrow\";\n\n/** Direct canister event payload returned by instant-loans event queries. */\nexport type InstantLoanEventType =\n | {\n type: \"LoanCreated\";\n loanId: bigint;\n borrowDestination: InstantLoanAccount;\n collateralAsset: InstantLoanAsset;\n borrowAmount: bigint;\n collateralPoolId: string;\n refundDestination: InstantLoanAccount;\n ltvMaxBps: bigint;\n depositWindowSeconds: bigint;\n profileId: string;\n borrowPoolId: string;\n borrowAsset: InstantLoanAsset;\n }\n | {\n type: \"FullLendWithdrawalRequested\";\n loanId: bigint;\n account: InstantLoanAccount;\n poolId: string;\n }\n | {\n type: \"BorrowRequested\";\n loanId: bigint;\n account: InstantLoanAccount;\n poolId: string;\n amount: bigint;\n }\n | { type: \"DepositTimerExceeded\"; loanId: bigint }\n | {\n type: \"StuckFundsWithdrawalRequested\";\n leg: InstantLoanLeg;\n loanId: bigint;\n account: InstantLoanAccount;\n poolId: string;\n amount: bigint;\n }\n | {\n type: \"ProfileWarmed\";\n derivationIndex: Uint8Array;\n warmedProfileId: bigint;\n ethAddress: string;\n profileId: string;\n }\n | { type: \"RepayComplete\"; loanId: bigint; profileId: string }\n | { type: \"DepositTimerStarted\"; loanId: bigint; timestamp: bigint };\n\n/** Current amount to send to the repayment target to close the debt. */\nexport interface InstantLoanRepayment {\n /** Full amount to send to the repayment target, including fee and interest buffer. */\n amount: bigint;\n /** Decimal scale for `amount`. */\n decimals: bigint;\n /** Current debt in base units, before fee and interest buffer. */\n debtAmount: bigint;\n /** Additional interest buffer in base units. */\n interestBufferAmount: bigint;\n /** Seconds of interest accrual included in `interestBufferAmount`. */\n interestBufferSeconds: bigint;\n /** Inflow fee amount in base units added to the repayment transfer. Falls back to the protocol minimum when live estimation is unavailable. */\n inflowFeeAmount: bigint;\n /** Whether `inflowFeeAmount` came from a live fee estimate. */\n inflowFeeEstimateAvailable: boolean;\n /** Asset to repay. */\n asset: MarketAsset;\n /** Chain used for repayment. */\n chain: MarketChain;\n /** Address or ICRC account where the repayment should be sent. */\n target: SupplyTarget;\n}\n\n/** Current lending position backing the instant loan. */\nexport interface InstantLoanPositionSummary {\n /** Current collateral amount in the collateral asset's base units. */\n collateralAmount: bigint;\n /** Decimal scale for `collateralAmount`. */\n collateralDecimals: bigint;\n /** Earned interest on the collateral side in base units. */\n collateralInterestAmount: bigint;\n /** Borrowed principal in the borrow asset's base units. */\n borrowedAmount: bigint;\n /** Decimal scale for borrowed/debt amounts. */\n borrowedDecimals: bigint;\n /** Accrued borrow interest in base units. */\n debtInterestAmount: bigint;\n /** Borrowed principal plus accrued interest in base units, before repayment buffer. */\n totalDebtAmount: bigint;\n}\n\n/** Simplified lifecycle status for consumer UIs. */\nexport const InstantLoanStatus = {\n awaitingDeposit: \"awaiting_deposit\",\n depositDetected: \"deposit_detected\",\n active: \"active\",\n settling: \"settling\",\n closed: \"closed\",\n} as const;\nexport type InstantLoanStatus =\n (typeof InstantLoanStatus)[keyof typeof InstantLoanStatus];\n\n/** Hydrated instant-loan state plus generated deposit and repayment targets. */\nexport interface InstantLoan {\n /** Canister-assigned loan id. */\n loanId: bigint;\n /** Short user-facing reference derived from `loanId`. */\n ref: string;\n /** Simplified lifecycle status for display and flow control. */\n status: InstantLoanStatus;\n /** Generated lending profile principal used by the instant loan. */\n profileId: string;\n /** Maximum loan-to-value ratio in basis points. */\n ltvMaxBps: bigint;\n /** Seconds allowed for the collateral deposit before timeout. */\n depositWindowSeconds: bigint;\n /** Collateral-side pool, asset, chain, and current or requested collateral amount. */\n collateral: {\n poolId: string;\n asset: MarketAsset;\n chain: MarketChain;\n amount: bigint;\n };\n /** Borrow-side pool, asset, chain, requested amount, and destination. */\n borrow: {\n poolId: string;\n asset: MarketAsset;\n chain: MarketChain;\n amount: bigint;\n destination: InstantLoanAccount;\n };\n /** Destination used for collateral refunds or withdrawals. */\n refundDestination: InstantLoanAccount;\n /** Address or ICRC account where the user deposits collateral. */\n depositTarget: SupplyTarget;\n /** Address or ICRC account where the user repays debt. */\n repayTarget: SupplyTarget;\n /** Current actionable repayment quote. */\n repayment: InstantLoanRepayment;\n /** Current lending position state for the generated profile. */\n position: InstantLoanPositionSummary;\n}\n\n/**\n * Discovery result returned by address lookup.\n *\n * Candidates are intentionally lightweight; call `instantLoans.get(...)` with\n * `loanId` or `ref` to load canonical canister state and transfer targets.\n */\nexport interface InstantLoanCandidate {\n /** Canister-assigned loan id. */\n loanId: bigint;\n /** Short user-facing reference derived from `loanId`. */\n ref: string;\n /** Generated lending profile principal used by the instant loan. */\n profileId: string;\n /** API-observed creation time, if provided by the indexer. */\n createdAt?: Date;\n /** Principal text of the collateral pool. */\n collateralPoolId: string;\n /** Principal text of the borrow pool. */\n borrowPoolId: string;\n /** Collateral asset symbol. */\n collateralAsset: MarketAsset;\n /** Borrow asset symbol. */\n borrowAsset: MarketAsset;\n /** Collateral amount hint in base units. */\n collateralAmountHint: bigint;\n}\n","import { encodeIcrcAccount } from \"@dfinity/ledger-icrc\";\nimport { Principal } from \"@dfinity/principal\";\nimport { encodeFunctionData } from \"viem\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport { CK_DEPOSIT_ABI, ERC20_ABI } from \"../../core/evm\";\nimport type { SupplyAction } from \"../../core/types\";\nimport { encodeInflowSubaccount } from \"../../core/utils/inflow-subaccount\";\n\n/** Builds calldata for an ERC-20 `approve(spender, amount)` transaction. */\nexport function createApproveTransaction(params: {\n tokenAddress: string;\n spenderAddress: string;\n amount: bigint;\n}): { to: string; data: string } {\n return {\n to: params.tokenAddress,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"approve\",\n args: [params.spenderAddress as `0x${string}`, params.amount],\n }),\n };\n}\n\n/** Builds calldata for an ERC-20 `transfer(recipient, amount)` transaction. */\nexport function createTransferErc20Transaction(params: {\n tokenAddress: string;\n recipientAddress: string;\n amount: bigint;\n}): { to: string; data: string } {\n return {\n to: params.tokenAddress,\n data: encodeFunctionData({\n abi: ERC20_ABI,\n functionName: \"transfer\",\n args: [params.recipientAddress as `0x${string}`, params.amount],\n }),\n };\n}\n\n/** Builds calldata for depositing ERC-20 funds into the ckETH deposit helper. */\nexport function createDepositErc20Transaction(params: {\n depositContractAddress: string;\n tokenAddress: string;\n amount: bigint;\n poolId: string;\n profileId: string;\n destinationAccount: string;\n action: SupplyAction;\n}): { to: string; data: string } {\n const expectedDestinationAccount = encodeIcrcAccount({\n owner: Principal.fromText(params.poolId),\n subaccount: encodeInflowSubaccount({\n action: params.action,\n principal: Principal.fromText(params.profileId),\n }),\n });\n\n if (params.destinationAccount !== expectedDestinationAccount) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"ETH supply destination account does not match the expected inflow account\"\n );\n }\n\n const principalBytes32 = encodePrincipalToBytes32(\n Principal.fromText(params.poolId)\n );\n const subaccountHex = encodeBytes32Hex(\n encodeInflowSubaccount({\n action: params.action,\n principal: Principal.fromText(params.profileId),\n })\n );\n\n return {\n to: params.depositContractAddress,\n data: encodeFunctionData({\n abi: CK_DEPOSIT_ABI,\n functionName: \"depositErc20\",\n args: [\n params.tokenAddress as `0x${string}`,\n params.amount,\n principalBytes32,\n subaccountHex,\n ],\n }),\n };\n}\n\nfunction encodePrincipalToBytes32(principal: Principal): `0x${string}` {\n const principalBytes = principal.toUint8Array();\n if (principalBytes.length > 29) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Principal length exceeds Ethereum bytes32 capacity\"\n );\n }\n\n const fixedBytes = new Uint8Array(32);\n fixedBytes[0] = principalBytes.length;\n fixedBytes.set(principalBytes, 1);\n\n return encodeBytes32Hex(fixedBytes);\n}\n\nfunction encodeBytes32Hex(bytes: Uint8Array): `0x${string}` {\n return `0x${Array.from(bytes, (byte) =>\n byte.toString(16).padStart(2, \"0\")\n ).join(\"\")}`;\n}\n","export type MessageAccount = {\n type: \"Native\" | \"External\";\n data: string;\n};\n\nexport type OutflowMessageRequest = {\n pool_id: string;\n amount: string;\n account: MessageAccount;\n expiry_timestamp: bigint;\n};\n\nexport function createBorrowAssetMessage(\n request: OutflowMessageRequest,\n nonce: bigint\n): string {\n return `Liquidium: Borrow Assets\n\nAction: Borrow from pool\nPool ID: ${request.pool_id}\nAmount: ${request.amount}\n${accountTypeToString(request.account)}\nExpires: ${request.expiry_timestamp}\nNonce: ${nonce}`;\n}\n\nexport function createWithdrawAssetMessage(\n request: OutflowMessageRequest,\n nonce: bigint\n): string {\n return `Liquidium: Withdraw Assets\n\nAction: Withdraw from pool\nPool ID: ${request.pool_id}\nAmount: ${request.amount}\n${accountTypeToString(request.account)}\nExpires: ${request.expiry_timestamp}\nNonce: ${nonce}`;\n}\n\nfunction accountTypeToString(accountType: MessageAccount): string {\n switch (accountType.type) {\n case \"External\":\n return `Address:${accountType.data}`;\n case \"Native\":\n return `Principal:${accountType.data}`;\n }\n}\n","import { LiquidiumError, LiquidiumErrorCode } from \"../errors\";\n\nconst MIN_ATTEMPTS = 1;\nconst MIN_INITIAL_RETRY_DELAY_MS = 0;\nconst MIN_BACKOFF_MULTIPLIER = 1;\n\nexport type RetryWithBackoffOptions<T> = {\n execute: () => Promise<T>;\n maxAttempts: number;\n initialRetryDelayMs: number;\n backoffMultiplier: number;\n shouldRetryError: (error: unknown) => boolean;\n waitForDelayMs?: (delayMs: number) => Promise<void>;\n};\n\nexport async function retryWithBackoff<T>(\n options: RetryWithBackoffOptions<T>\n): Promise<T> {\n assertValidRetryOptions(options);\n\n const waitForDelayMs = options.waitForDelayMs ?? defaultWaitForDelayMs;\n let retryDelayMs = options.initialRetryDelayMs;\n\n for (let attempt = 1; attempt <= options.maxAttempts; attempt += 1) {\n try {\n return await options.execute();\n } catch (error) {\n const isLastAttempt = attempt === options.maxAttempts;\n if (isLastAttempt || !options.shouldRetryError(error)) {\n throw error;\n }\n\n await waitForDelayMs(retryDelayMs);\n retryDelayMs *= options.backoffMultiplier;\n }\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n \"Retry exhausted unexpectedly\"\n );\n}\n\nasync function defaultWaitForDelayMs(delayMs: number): Promise<void> {\n await new Promise<void>((resolve) => {\n setTimeout(resolve, delayMs);\n });\n}\n\nfunction assertValidRetryOptions<T>(options: RetryWithBackoffOptions<T>): void {\n if (options.maxAttempts < MIN_ATTEMPTS) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Retry maxAttempts must be at least ${MIN_ATTEMPTS}, received ${options.maxAttempts}`\n );\n }\n\n if (options.initialRetryDelayMs < MIN_INITIAL_RETRY_DELAY_MS) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Retry initialRetryDelayMs must be a non-negative number\"\n );\n }\n\n if (options.backoffMultiplier < MIN_BACKOFF_MULTIPLIER) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Retry backoffMultiplier must be at least ${MIN_BACKOFF_MULTIPLIER}, received ${options.backoffMultiplier}`\n );\n }\n}\n","import type { Principal } from \"@dfinity/principal\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport { Chain, OutflowType } from \"../../core/types\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport type { OutflowDetails } from \"./types\";\n\nexport type WalletChain = Chain;\n\nexport type LendingChainVariant = { BTC: null } | { ETH: null };\n\nexport type CanisterOutflowReceiver =\n | { Native: Principal }\n | { External: string };\n\nexport type CanisterOutflowRecord = {\n id: string;\n txid: [] | [string];\n outflow_type: Record<string, null>;\n outflow_ref: [] | [string];\n amount: bigint;\n receiver: CanisterOutflowReceiver;\n};\n\nexport function mapCanisterOutflowDetails(\n outflow: CanisterOutflowRecord\n): OutflowDetails {\n const rawOutflowType = getVariantKey(outflow.outflow_type);\n\n return {\n id: outflow.id,\n outflowType: normalizeOutflowType(rawOutflowType),\n outflowRef: outflow.outflow_ref[0],\n txid: outflow.txid[0],\n amount: outflow.amount,\n receiver: mapCanisterAccountType(outflow.receiver),\n };\n}\n\nexport function mapCanisterAccountType(\n receiver: CanisterOutflowReceiver\n): OutflowDetails[\"receiver\"] {\n if (\"Native\" in receiver) {\n return {\n type: \"Native\",\n account: receiver.Native.toText(),\n };\n }\n\n return {\n type: \"External\",\n account: receiver.External,\n };\n}\n\nexport function normalizeOutflowType(\n rawOutflowType: string\n): OutflowDetails[\"outflowType\"] {\n switch (rawOutflowType) {\n case \"Withdraw\":\n return OutflowType.withdraw;\n case \"Borrow\":\n return OutflowType.borrow;\n case \"FeeClaim\":\n return OutflowType.feeClaim;\n default:\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Unsupported outflow type: ${rawOutflowType}`\n );\n }\n}\n\nexport function mapWalletChainToLendingChain(\n chain: WalletChain\n): LendingChainVariant {\n switch (chain) {\n case Chain.BTC:\n return { BTC: null };\n case Chain.ETH:\n return { ETH: null };\n }\n}\n","import { Principal } from \"@dfinity/principal\";\nimport { getAddress, isAddress } from \"viem\";\nimport { createDepositAccountsActor } from \"../../core/canisters/deposit-accounts/actor\";\nimport {\n createLendingActor,\n type LendingPoolRecord,\n} from \"../../core/canisters/lending/actor\";\nimport {\n mapCanisterCallErrorToLiquidiumError,\n mapLendingProtocolErrorToLiquidiumError,\n} from \"../../core/canisters/lending/error-mappers\";\nimport {\n createBorrowAssetMessage,\n createWithdrawAssetMessage,\n} from \"../../core/canisters/lending/messages\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport {\n CK_ETH_DEPOSIT_CONTRACT_ADDRESS,\n ERC20_ABI,\n MAX_UINT256,\n normalizeEvmAddress,\n} from \"../../core/evm\";\nimport { SdkApiPath } from \"../../core/sdk-api-paths\";\nimport type { ApiClient } from \"../../core/transports/api-client\";\nimport type { CanisterContext } from \"../../core/transports/canister-context\";\nimport {\n Asset,\n Chain,\n type EvmReadClient,\n InflowSubmitType,\n OutflowType,\n SupplyAction,\n} from \"../../core/types\";\nimport { encodeInflowSubaccount } from \"../../core/utils/inflow-subaccount\";\nimport { retryWithBackoff } from \"../../core/utils/retry\";\nimport { normalizeHexSignature } from \"../../core/utils/signature\";\nimport { computeExpiryTimestampFromNow } from \"../../core/utils/time\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport {\n TransferMode,\n WalletActionKind,\n type WalletAdapter,\n WalletExecutionKind,\n} from \"../../core/wallet-actions\";\nimport { executeWith } from \"../../execute\";\nimport {\n getEthStablecoinContractAddress,\n isEthStablecoin,\n mapDepositAccountErrorToLiquidiumError,\n resolveSupplyMechanism,\n resolveSupplyTarget,\n} from \"./_internal/supply-targets\";\nimport {\n createApproveTransaction,\n createDepositErc20Transaction,\n createTransferErc20Transaction,\n} from \"./evm-transactions\";\nimport {\n mapCanisterOutflowDetails,\n mapWalletChainToLendingChain,\n} from \"./mappers\";\nimport {\n type BorrowAction,\n type BorrowOutflowDetails,\n type BorrowSubmitSignatureInfo,\n type CreateBorrowRequest,\n type CreateWithdrawRequest,\n type EstimateInflowFeeRequest,\n EvmSupplyApprovalStrategy,\n type EvmSupplyContext,\n type GetEvmSupplyContextRequest,\n type InflowFeeEstimate,\n type OutflowDetails,\n type SubmitInflowRequest,\n type SubmitInflowResponse,\n type SupplyFlow,\n type SupplyFlowRequest,\n SupplyPlanType,\n type SupplyTarget,\n type WithdrawAction,\n type WithdrawOutflowDetails,\n type WithdrawSubmitSignatureInfo,\n} from \"./types\";\n\nconst SUBMIT_INFLOW_MAX_ATTEMPTS = 4;\nconst SUBMIT_INFLOW_INITIAL_RETRY_DELAY_MS = 1_500;\nconst SUBMIT_INFLOW_RETRY_BACKOFF_MULTIPLIER = 2;\nconst ETH_APPROVAL_POLL_INTERVAL_MS = 2_000;\nconst ETH_APPROVAL_MAX_POLLS = 30;\n\ntype WalletExecutionParams = {\n signerChain: Chain;\n signerWalletAdapter: WalletAdapter;\n};\n\ntype OutflowRequestData = {\n profileId: string;\n poolId: string;\n amount: bigint;\n receiverAddress: string;\n signerWalletAddress: string;\n expiryTimestamp: bigint;\n};\n\ntype SupplyInstruction = {\n poolId: string;\n asset: string;\n chain: string;\n action: SupplyAction;\n target: SupplyTarget;\n};\n\ntype EvmAddress = `0x${string}`;\n\n/** Borrow, withdraw, supply, inflow reporting, and fee-estimation helpers. */\nexport class LendingModule {\n constructor(\n readonly canisterContext: CanisterContext,\n readonly apiClient: ApiClient | undefined,\n readonly evmReadClient: EvmReadClient | undefined\n ) {}\n\n /**\n * Prepares a withdraw action that can be signed and submitted later.\n *\n * Use this when you need explicit control over signing and submission.\n *\n * @param request - Profile, pool, amount (pool asset base units), outflow address, and signer wallet.\n * @returns A signable {@link WithdrawAction} with `submit` wired to the canister.\n */\n async prepareWithdraw(\n request: CreateWithdrawRequest\n ): Promise<WithdrawAction> {\n const destinationAccount = request.receiverAddress.trim();\n const signerAccount = normalizeEvmAddress(\n request.signerWalletAddress.trim()\n );\n if (!destinationAccount) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Withdraw requires a custom outflow account\"\n );\n }\n if (!signerAccount) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Withdraw requires a signer account\"\n );\n }\n\n const lendingActor = createLendingActor(this.canisterContext);\n\n try {\n const expiryTimestamp = computeExpiryTimestampFromNow();\n const nonce = await lendingActor.get_nonce(signerAccount);\n const withdrawRequestData = {\n profileId: request.profileId,\n poolId: request.poolId,\n amount: request.amount,\n receiverAddress: destinationAccount,\n signerWalletAddress: signerAccount,\n expiryTimestamp,\n };\n\n return {\n kind: WalletActionKind.createWithdraw,\n executionKind: WalletExecutionKind.signMessage,\n actionType: WalletActionKind.createWithdraw,\n transferMode: TransferMode.native,\n account: signerAccount,\n message: createWithdrawAssetMessage(\n {\n pool_id: request.poolId,\n amount: request.amount.toString(),\n account: { type: \"External\", data: destinationAccount },\n expiry_timestamp: expiryTimestamp,\n },\n nonce\n ),\n data: withdrawRequestData,\n submit: async (signatureInfo: WithdrawSubmitSignatureInfo) => {\n return await this.submitWithdraw(withdrawRequestData, signatureInfo);\n },\n };\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_nonce\", error);\n }\n }\n\n private async submitWithdraw(\n request: OutflowRequestData,\n signatureInfo: WithdrawSubmitSignatureInfo\n ): Promise<WithdrawOutflowDetails> {\n try {\n const result = await createLendingActor(this.canisterContext).withdraw(\n Principal.fromText(request.profileId),\n {\n data: {\n expiry_timestamp: request.expiryTimestamp,\n account: { External: request.receiverAddress },\n pool_id: Principal.fromText(request.poolId),\n amount: request.amount,\n },\n signature_info: {\n Wallet: {\n signature: normalizeHexSignature(signatureInfo.signature),\n chain: mapWalletChainToLendingChain(signatureInfo.chain),\n account: request.signerWalletAddress,\n },\n },\n }\n );\n\n if (\"Err\" in result) {\n throw mapLendingProtocolErrorToLiquidiumError(result.Err);\n }\n\n return mapExpectedOutflowDetails(\n mapCanisterOutflowDetails(result.Ok),\n OutflowType.withdraw,\n \"withdraw\"\n );\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"withdraw\", error);\n }\n }\n\n /**\n * Creates a withdraw outflow using the provided wallet adapter.\n *\n * This is the convenience form of `prepareWithdraw(...)` plus execution.\n *\n * @param params - Withdraw request fields plus `signerChain` and `signerWalletAdapter`.\n * @returns The canister {@link OutflowDetails} for the completed withdraw.\n */\n async withdraw(\n params: CreateWithdrawRequest & WalletExecutionParams\n ): Promise<WithdrawOutflowDetails> {\n const action = await this.prepareWithdraw(params);\n\n return await executeWith({\n walletAdapter: params.signerWalletAdapter,\n chain: params.signerChain,\n account: action.account,\n })(action);\n }\n\n /**\n * Prepares a borrow action that can be signed and submitted later.\n *\n * Use this when you need explicit control over signing and submission.\n *\n * @param request - Profile, pool, amount (borrow asset base units), outflow address, and signer wallet.\n * @returns A signable {@link BorrowAction} with `submit` wired to the canister.\n */\n async prepareBorrow(request: CreateBorrowRequest): Promise<BorrowAction> {\n const destinationAccount = request.receiverAddress.trim();\n const signerAccount = normalizeEvmAddress(\n request.signerWalletAddress.trim()\n );\n if (!destinationAccount) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Borrow requires a custom outflow account\"\n );\n }\n if (!signerAccount) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Borrow requires a signer account\"\n );\n }\n\n const lendingActor = createLendingActor(this.canisterContext);\n\n try {\n const expiryTimestamp = computeExpiryTimestampFromNow();\n const nonce = await lendingActor.get_nonce(signerAccount);\n const borrowRequestData = {\n profileId: request.profileId,\n poolId: request.poolId,\n amount: request.amount,\n receiverAddress: destinationAccount,\n signerWalletAddress: signerAccount,\n expiryTimestamp,\n };\n\n return {\n kind: WalletActionKind.createBorrow,\n executionKind: WalletExecutionKind.signMessage,\n actionType: WalletActionKind.createBorrow,\n transferMode: TransferMode.native,\n account: signerAccount,\n message: createBorrowAssetMessage(\n {\n pool_id: request.poolId,\n amount: request.amount.toString(),\n account: { type: \"External\", data: destinationAccount },\n expiry_timestamp: expiryTimestamp,\n },\n nonce\n ),\n data: borrowRequestData,\n submit: async (signatureInfo: BorrowSubmitSignatureInfo) => {\n return await this.submitBorrow(borrowRequestData, signatureInfo);\n },\n };\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_nonce\", error);\n }\n }\n\n private async submitBorrow(\n request: OutflowRequestData,\n signatureInfo: BorrowSubmitSignatureInfo\n ): Promise<BorrowOutflowDetails> {\n try {\n const result = await createLendingActor(\n this.canisterContext\n ).borrow_assets(Principal.fromText(request.profileId), {\n data: {\n expiry_timestamp: request.expiryTimestamp,\n account: { External: request.receiverAddress },\n pool_id: Principal.fromText(request.poolId),\n amount: request.amount,\n },\n signature_info: {\n Wallet: {\n signature: normalizeHexSignature(signatureInfo.signature),\n chain: mapWalletChainToLendingChain(signatureInfo.chain),\n account: request.signerWalletAddress,\n },\n },\n });\n\n if (\"Err\" in result) {\n throw mapLendingProtocolErrorToLiquidiumError(result.Err);\n }\n\n return mapExpectedOutflowDetails(\n mapCanisterOutflowDetails(result.Ok),\n OutflowType.borrow,\n \"borrow_assets\"\n );\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"borrow_assets\", error);\n }\n }\n\n /**\n * Creates a borrow outflow using the provided wallet adapter.\n *\n * This is the convenience form of `prepareBorrow(...)` plus execution.\n *\n * @param params - Borrow request fields plus `signerChain` and `signerWalletAdapter`.\n * @returns The lending canister receipt as {@link OutflowDetails}.\n *\n * @remarks\n * `id` is always present. `txid` may be missing on the first response; the SDK does not\n * poll for it. Use history or app-level polling if you need the chain transaction id.\n */\n async borrow(\n params: CreateBorrowRequest & WalletExecutionParams\n ): Promise<BorrowOutflowDetails> {\n const action = await this.prepareBorrow(params);\n\n return await executeWith({\n walletAdapter: params.signerWalletAdapter,\n chain: params.signerChain,\n account: action.account,\n })(action);\n }\n\n /**\n * Resolves a supply target for a deposit or repayment and optionally broadcasts it.\n *\n * Transfer mode can return manual broadcast instructions when wallet fields are\n * omitted. Contract-interaction mode always requires `walletAdapter`, `account`,\n * and `amount` because it must prepare and submit approval/deposit calls.\n *\n * The SDK does not poll for inflow status. When a `txid` is returned, it is the\n * caller's responsibility to track confirmation state using their own polling.\n *\n * @returns A {@link SupplyFlow} receipt with `type`, `target`, `submit`, and\n * an optional `txid` present when the SDK broadcast for you.\n */\n async supply(request: SupplyFlowRequest): Promise<SupplyFlow> {\n const target = await resolveSupplyTarget(this.canisterContext, request);\n const instruction: SupplyInstruction = {\n poolId: request.poolId,\n asset: target.asset,\n chain: target.chain,\n action: request.action,\n target,\n };\n const mechanism = resolveSupplyMechanism({\n asset: instruction.asset,\n chain: instruction.chain,\n requestedMechanism: request.mechanism,\n });\n const defaultSubmitInflowRequest = getDefaultSubmitInflowRequest({\n action: request.action,\n chain:\n mechanism === SupplyPlanType.contractInteraction\n ? Chain.ETH\n : instruction.chain,\n });\n\n let txid: string | undefined;\n switch (mechanism) {\n case SupplyPlanType.transfer:\n if (request.walletAdapter) {\n txid = await this.sendAndSubmitNativeSupplyInflow({\n request,\n instruction,\n defaultSubmitInflowRequest,\n });\n }\n break;\n case SupplyPlanType.contractInteraction:\n txid = await this.executeContractSupply({\n request,\n instruction,\n defaultSubmitInflowRequest,\n });\n break;\n }\n\n return {\n type: mechanism,\n target: instruction.target,\n txid,\n submit: async (submitRequest) => {\n return await this.submitSupplyFlowInflow({\n instruction,\n mechanism,\n defaultSubmitInflowRequest,\n submitRequest,\n });\n },\n };\n }\n\n /**\n * Fetches ERC-20 supply planning data with the configured EVM read client.\n *\n * Requires `evmRpcUrl` or `evmPublicClient` on the client. Used internally by\n * contract-interaction `supply`.\n *\n * @param request - Profile, pool, wallet, amount (token base units), and action.\n * @returns Locally computed {@link EvmSupplyContext} for approvals and deposit.\n */\n async getEvmSupplyContext(\n request: GetEvmSupplyContextRequest\n ): Promise<EvmSupplyContext> {\n const selectedPool = await this.getPoolById(request.poolId);\n\n return await this.getEvmSupplyContextForPool({\n request,\n asset: getVariantKey(selectedPool.asset),\n chain: getVariantKey(selectedPool.chain),\n });\n }\n\n private async getEvmSupplyContextForPool(params: {\n request: GetEvmSupplyContextRequest;\n asset: string;\n chain: string;\n }): Promise<EvmSupplyContext> {\n const { request, asset, chain } = params;\n const evmReadClient = this.requireEvmReadClient(\n \"EVM supply context requires an EVM RPC URL or public client\"\n );\n const walletAddress = normalizeAndValidateEvmAddress(\n request.walletAddress,\n \"Invalid EVM wallet address\"\n );\n\n if (request.amount <= 0n) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"EVM supply context requires a positive amount\"\n );\n }\n\n if (!isEthStablecoin(asset, chain)) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `EVM supply context only supports ETH stablecoin pools, received ${asset} on ${chain}`\n );\n }\n\n const tokenAddress = getEthStablecoinContractAddress(asset);\n const spenderAddress = CK_ETH_DEPOSIT_CONTRACT_ADDRESS;\n const [allowance, balance] = await Promise.all([\n readErc20Allowance({\n evmReadClient,\n tokenAddress,\n ownerAddress: walletAddress,\n spenderAddress,\n }),\n readErc20Balance({\n evmReadClient,\n tokenAddress,\n ownerAddress: walletAddress,\n }),\n ]);\n const approvalStrategy = getApprovalStrategy({\n allowance,\n amount: request.amount,\n });\n\n return {\n success: true,\n profileId: request.profileId,\n poolId: request.poolId,\n walletAddress,\n action: request.action,\n asset: asset as typeof Asset.USDC | typeof Asset.USDT,\n chain: Chain.ETH,\n amount: request.amount.toString(),\n tokenAddress,\n spenderAddress,\n depositContractAddress: CK_ETH_DEPOSIT_CONTRACT_ADDRESS,\n balance: balance.toString(),\n allowance: allowance.toString(),\n requiresApproval: approvalStrategy !== EvmSupplyApprovalStrategy.none,\n approvalStrategy,\n };\n }\n\n /**\n * Returns the read-only deposit address for an ETH stablecoin inflow target.\n *\n * This is a query call that does not create or mutate state. Use it when you\n * need the deposit address without hitting the authorization-gated update path.\n *\n * @param request - Profile, pool, asset, and supply action.\n * @returns The EVM deposit address for the derived account.\n */\n async getDepositAddress(request: {\n profileId: string;\n poolId: string;\n asset: string;\n action: SupplyAction;\n }): Promise<string> {\n if (!isEthStablecoin(request.asset, Chain.ETH)) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"getDepositAddress is only supported for ETH stablecoins\"\n );\n }\n\n const tokenAddress = getEthStablecoinContractAddress(request.asset);\n const subaccount = encodeInflowSubaccount({\n action: request.action,\n principal: Principal.fromText(request.profileId),\n });\n\n const result = await createDepositAccountsActor(\n this.canisterContext\n ).get_deposit_address(\n {\n owner: Principal.fromText(request.poolId),\n subaccount: [subaccount],\n },\n [tokenAddress]\n );\n\n if (\"Err\" in result) {\n throw mapDepositAccountErrorToLiquidiumError(result.Err);\n }\n\n return result.Ok;\n }\n\n /**\n * Estimates the network/deposit fee for an inflow target.\n *\n * ETH stablecoin deposit-address estimates are served by the deposit-address\n * canister. BTC estimates are not exposed by this SDK yet and return zero.\n *\n * @param request - Asset and chain pair to estimate for.\n * @returns Total fee estimate in the asset's base units.\n */\n async estimateInflowFee(\n request: EstimateInflowFeeRequest\n ): Promise<InflowFeeEstimate> {\n if (isEthStablecoin(request.asset, request.chain)) {\n const result = await createDepositAccountsActor(\n this.canisterContext\n ).estimate_deposit_fee([getEthStablecoinContractAddress(request.asset)]);\n\n if (\"Err\" in result) {\n throw mapDepositAccountErrorToLiquidiumError(result.Err);\n }\n\n return { totalFee: result.Ok };\n }\n\n if (request.asset === Asset.BTC && request.chain === Chain.BTC) {\n return { totalFee: 0n };\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Inflow fee estimates are not supported for ${request.asset} on ${request.chain}`\n );\n }\n\n private async sendAndSubmitNativeSupplyInflow(params: {\n request: SupplyFlowRequest;\n instruction: SupplyInstruction;\n defaultSubmitInflowRequest?: Omit<SubmitInflowRequest, \"txid\">;\n }): Promise<string> {\n const { request, instruction, defaultSubmitInflowRequest } = params;\n\n if (instruction.target.type !== \"nativeAddress\") {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Wallet-executed supply requires a native-address target\"\n );\n }\n\n if (!request.walletAdapter) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Wallet-executed supply requires a wallet adapter\"\n );\n }\n\n const account = request.account?.trim();\n if (!account) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Wallet-executed transfer supply requires an account\"\n );\n }\n\n if (!request.amount || request.amount <= 0n) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Wallet-executed supply requires a positive amount\"\n );\n }\n\n const txid = await this.sendNativeSupplyTransaction({\n walletAdapter: request.walletAdapter,\n chain: instruction.chain,\n toAddress: instruction.target.address,\n amount: request.amount,\n senderAccount: account,\n asset: instruction.asset,\n action: request.action,\n });\n\n if (\n shouldSubmitInflow({ instruction, mechanism: SupplyPlanType.transfer })\n ) {\n await this.submitInflowWithRetry(txid, defaultSubmitInflowRequest);\n }\n\n return txid;\n }\n\n private async submitSupplyFlowInflow(params: {\n instruction: SupplyInstruction;\n mechanism: SupplyPlanType;\n defaultSubmitInflowRequest?: Omit<SubmitInflowRequest, \"txid\">;\n submitRequest: SubmitInflowRequest;\n }): Promise<SubmitInflowResponse> {\n if (!shouldSubmitInflow(params)) {\n return { success: true, txid: params.submitRequest.txid };\n }\n\n return await this.submitInflow({\n ...params.defaultSubmitInflowRequest,\n ...params.submitRequest,\n });\n }\n\n private async executeContractSupply(params: {\n request: SupplyFlowRequest;\n instruction: SupplyInstruction;\n defaultSubmitInflowRequest?: Omit<SubmitInflowRequest, \"txid\">;\n }): Promise<string> {\n const { request, instruction, defaultSubmitInflowRequest } = params;\n\n if (\n instruction.target.type !== \"icrcAccount\" ||\n instruction.chain !== Chain.ETH\n ) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Contract-interaction supply is only supported for ETH ICRC-account targets\"\n );\n }\n\n const walletAddressInput = request.account?.trim();\n if (!walletAddressInput) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Contract-interaction supply requires an account\"\n );\n }\n const walletAddress = normalizeAndValidateEvmAddress(\n walletAddressInput,\n \"Invalid EVM wallet address\"\n );\n\n if (!request.amount || request.amount <= 0n) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Contract-interaction supply requires a positive amount\"\n );\n }\n\n const walletAdapter = request.walletAdapter;\n if (!walletAdapter?.sendEthTransaction) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Contract-interaction supply requires an ETH wallet adapter\"\n );\n }\n\n this.requireApi();\n this.requireEvmReadClient(\n \"Contract-interaction supply requires an EVM RPC URL or public client\"\n );\n\n const evmSupplyContext = await this.getEvmSupplyContextForPool({\n request: {\n profileId: request.profileId,\n poolId: request.poolId,\n walletAddress,\n amount: request.amount,\n action: request.action,\n },\n asset: instruction.asset,\n chain: instruction.chain,\n });\n const supplyAmount = BigInt(evmSupplyContext.amount);\n\n if (BigInt(evmSupplyContext.balance) < supplyAmount) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INSUFFICIENT_FUNDS,\n `Insufficient ${evmSupplyContext.asset} balance for ${request.action}`\n );\n }\n\n if (\n evmSupplyContext.approvalStrategy ===\n EvmSupplyApprovalStrategy.resetThenApproveMax\n ) {\n await this.sendEthContractTransaction(\n walletAdapter,\n walletAddress,\n createApproveTransaction({\n tokenAddress: evmSupplyContext.tokenAddress,\n spenderAddress: evmSupplyContext.spenderAddress,\n amount: 0n,\n }),\n `supply-${request.action}-approve-reset`\n );\n\n await this.waitForExpectedAllowance({\n walletAddress,\n tokenAddress: evmSupplyContext.tokenAddress,\n spenderAddress: evmSupplyContext.spenderAddress,\n amount: supplyAmount,\n expectation: \"zero\",\n });\n }\n\n if (evmSupplyContext.approvalStrategy !== EvmSupplyApprovalStrategy.none) {\n await this.sendEthContractTransaction(\n walletAdapter,\n walletAddress,\n createApproveTransaction({\n tokenAddress: evmSupplyContext.tokenAddress,\n spenderAddress: evmSupplyContext.spenderAddress,\n amount: MAX_UINT256,\n }),\n `supply-${request.action}-approve-max`\n );\n\n await this.waitForExpectedAllowance({\n walletAddress,\n tokenAddress: evmSupplyContext.tokenAddress,\n spenderAddress: evmSupplyContext.spenderAddress,\n amount: supplyAmount,\n expectation: \"sufficient\",\n });\n }\n\n const depositTxid = await this.sendEthContractTransaction(\n walletAdapter,\n walletAddress,\n createDepositErc20Transaction({\n depositContractAddress: evmSupplyContext.depositContractAddress,\n tokenAddress: evmSupplyContext.tokenAddress,\n amount: supplyAmount,\n poolId: request.poolId,\n profileId: request.profileId,\n destinationAccount: instruction.target.account,\n action: request.action,\n }),\n `supply-${request.action}-deposit-erc20`\n );\n\n try {\n await this.submitInflowWithRetry(depositTxid, defaultSubmitInflowRequest);\n } catch {\n // The deposit transaction is already broadcast and cannot be rolled back.\n // Return the txid so callers can track it even if the indexing hint fails.\n }\n\n return depositTxid;\n }\n\n private async sendNativeSupplyTransaction(params: {\n walletAdapter: Pick<\n WalletAdapter,\n \"sendBtcTransaction\" | \"sendEthTransaction\"\n >;\n chain: string;\n asset: string;\n toAddress: string;\n amount: bigint;\n senderAccount: string;\n action: SupplyAction;\n }): Promise<string> {\n switch (params.chain) {\n case Chain.BTC: {\n if (!params.walletAdapter.sendBtcTransaction) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"BTC wallet adapter does not support transaction sending\"\n );\n }\n\n return await params.walletAdapter.sendBtcTransaction({\n chain: Chain.BTC,\n toAddress: params.toAddress,\n amountSats: params.amount,\n account: params.senderAccount,\n actionType: `supply-${params.action}`,\n transferMode: TransferMode.native,\n });\n }\n case Chain.ETH: {\n if (!params.walletAdapter.sendEthTransaction) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"ETH wallet adapter does not support transaction sending\"\n );\n }\n\n if (isEthStablecoin(params.asset, params.chain)) {\n return await params.walletAdapter.sendEthTransaction({\n chain: Chain.ETH,\n account: params.senderAccount,\n actionType: `supply-${params.action}`,\n transferMode: TransferMode.native,\n transaction: createTransferErc20Transaction({\n tokenAddress: getEthStablecoinContractAddress(params.asset),\n recipientAddress: params.toAddress,\n amount: params.amount,\n }),\n });\n }\n\n return await params.walletAdapter.sendEthTransaction({\n chain: Chain.ETH,\n account: params.senderAccount,\n actionType: `supply-${params.action}`,\n transferMode: TransferMode.native,\n transaction: {\n to: params.toAddress,\n value: params.amount.toString(),\n },\n });\n }\n default:\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Native-address wallet execution is not supported for ${params.chain}`\n );\n }\n }\n\n private async submitInflowWithRetry(\n txid: string,\n extraRequest?: Omit<SubmitInflowRequest, \"txid\">\n ): Promise<void> {\n await retryWithBackoff({\n execute: async () => {\n await this.submitInflow({ txid, ...extraRequest });\n },\n maxAttempts: SUBMIT_INFLOW_MAX_ATTEMPTS,\n initialRetryDelayMs: SUBMIT_INFLOW_INITIAL_RETRY_DELAY_MS,\n backoffMultiplier: SUBMIT_INFLOW_RETRY_BACKOFF_MULTIPLIER,\n shouldRetryError: isRetriableInflowSubmitError,\n });\n }\n\n /**\n * Submits an inflow transaction id for faster indexing.\n *\n * Uses the Liquidium SDK API.\n *\n * @param request - Broadcast `txid` plus optional `chain` and inflow `type`.\n * @returns Acknowledgement including the submitted `txid`.\n */\n async submitInflow(\n request: SubmitInflowRequest\n ): Promise<SubmitInflowResponse> {\n const apiClient = this.requireApi();\n\n return await apiClient.post<SubmitInflowResponse, SubmitInflowRequest>(\n SdkApiPath.inflow,\n request\n );\n }\n\n /**\n * Returns whether borrowing is currently disabled by the protocol.\n *\n * @returns `true` when the lending canister reports borrowing disabled.\n */\n async isBorrowingDisabled(): Promise<boolean> {\n try {\n return await createLendingActor(\n this.canisterContext\n ).get_borrowing_disabled();\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\n \"get_borrowing_disabled\",\n error\n );\n }\n }\n\n private requireApi(): ApiClient {\n if (!this.apiClient) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Lending API actions require an API client\"\n );\n }\n\n return this.apiClient;\n }\n\n private requireEvmReadClient(message: string): EvmReadClient {\n if (!this.evmReadClient) {\n throw new LiquidiumError(LiquidiumErrorCode.VALIDATION_ERROR, message);\n }\n\n return this.evmReadClient;\n }\n\n private async getPoolById(poolId: string): Promise<LendingPoolRecord> {\n const pools = await createLendingActor(this.canisterContext).list_pools();\n const selectedPool = pools.find(\n (pool) => pool.principal.toText() === poolId\n );\n\n if (!selectedPool) {\n throw new LiquidiumError(\n LiquidiumErrorCode.POOL_NOT_FOUND,\n `Pool not found: ${poolId}`\n );\n }\n\n return selectedPool;\n }\n\n private async sendEthContractTransaction(\n walletAdapter: Pick<WalletAdapter, \"sendEthTransaction\">,\n walletAddress: string,\n request: { to: string; data: string },\n actionType: string\n ): Promise<string> {\n if (!walletAdapter.sendEthTransaction) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"ETH wallet adapter does not support transaction sending\"\n );\n }\n\n return await walletAdapter.sendEthTransaction({\n chain: Chain.ETH,\n account: walletAddress,\n actionType,\n transferMode: TransferMode.native,\n transaction: request,\n });\n }\n\n private async waitForExpectedAllowance(params: {\n walletAddress: string;\n tokenAddress: string;\n spenderAddress: string;\n amount: bigint;\n expectation: \"zero\" | \"sufficient\";\n }): Promise<void> {\n const evmReadClient = this.requireEvmReadClient(\n \"Contract-interaction supply requires an EVM RPC URL or public client\"\n );\n let lastPollingError: unknown;\n\n for (\n let pollIndex = 0;\n pollIndex < ETH_APPROVAL_MAX_POLLS;\n pollIndex += 1\n ) {\n try {\n const allowance = await readErc20Allowance({\n evmReadClient,\n tokenAddress: params.tokenAddress,\n ownerAddress: params.walletAddress,\n spenderAddress: params.spenderAddress,\n });\n const matchesExpectation =\n params.expectation === \"zero\"\n ? allowance === 0n\n : allowance >= params.amount;\n\n if (matchesExpectation) {\n return;\n }\n } catch (error) {\n lastPollingError = error;\n }\n\n await delay(ETH_APPROVAL_POLL_INTERVAL_MS);\n }\n\n const lastPollingErrorMessage = getUnknownErrorMessage(lastPollingError);\n throw new LiquidiumError(\n LiquidiumErrorCode.SERVICE_UNAVAILABLE,\n lastPollingErrorMessage\n ? `Timed out waiting for ${params.expectation} ETH allowance update. Last polling error: ${lastPollingErrorMessage}`\n : `Timed out waiting for ${params.expectation} ETH allowance update`\n );\n }\n}\n\nasync function readErc20Allowance(params: {\n evmReadClient: EvmReadClient;\n tokenAddress: string;\n ownerAddress: string;\n spenderAddress: string;\n}): Promise<bigint> {\n const allowance = await params.evmReadClient.readContract({\n address: params.tokenAddress as EvmAddress,\n abi: ERC20_ABI,\n functionName: \"allowance\",\n args: [\n params.ownerAddress as EvmAddress,\n params.spenderAddress as EvmAddress,\n ],\n });\n\n return BigInt(allowance);\n}\n\nasync function readErc20Balance(params: {\n evmReadClient: EvmReadClient;\n tokenAddress: string;\n ownerAddress: string;\n}): Promise<bigint> {\n const balance = await params.evmReadClient.readContract({\n address: params.tokenAddress as EvmAddress,\n abi: ERC20_ABI,\n functionName: \"balanceOf\",\n args: [params.ownerAddress as EvmAddress],\n });\n\n return BigInt(balance);\n}\n\nfunction getApprovalStrategy(params: {\n allowance: bigint;\n amount: bigint;\n}): EvmSupplyApprovalStrategy {\n if (params.allowance >= params.amount) {\n return EvmSupplyApprovalStrategy.none;\n }\n\n if (params.allowance === 0n) {\n return EvmSupplyApprovalStrategy.approveMax;\n }\n\n return EvmSupplyApprovalStrategy.resetThenApproveMax;\n}\n\nfunction normalizeAndValidateEvmAddress(\n address: string,\n errorMessage: string\n): EvmAddress {\n if (!isAddress(address)) {\n throw new LiquidiumError(LiquidiumErrorCode.INVALID_ADDRESS, errorMessage);\n }\n\n return getAddress(address) as EvmAddress;\n}\n\nfunction mapExpectedOutflowDetails(\n details: OutflowDetails,\n expectedOutflowType: typeof OutflowType.borrow,\n operation: string\n): BorrowOutflowDetails;\nfunction mapExpectedOutflowDetails(\n details: OutflowDetails,\n expectedOutflowType: typeof OutflowType.withdraw,\n operation: string\n): WithdrawOutflowDetails;\nfunction mapExpectedOutflowDetails(\n details: OutflowDetails,\n expectedOutflowType: typeof OutflowType.borrow | typeof OutflowType.withdraw,\n operation: string\n): BorrowOutflowDetails | WithdrawOutflowDetails {\n if (details.outflowType !== expectedOutflowType) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `${operation} returned unexpected outflow type ${details.outflowType}`\n );\n }\n\n if (details.receiver.type !== \"External\") {\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `${operation} returned unexpected receiver type ${details.receiver.type}`\n );\n }\n\n return details as BorrowOutflowDetails | WithdrawOutflowDetails;\n}\n\nasync function delay(timeoutMs: number): Promise<void> {\n await new Promise<void>((resolve) => setTimeout(resolve, timeoutMs));\n}\n\nfunction isRetriableInflowSubmitError(error: unknown): boolean {\n if (!(error instanceof LiquidiumError)) {\n return false;\n }\n\n return error.code === LiquidiumErrorCode.SERVICE_UNAVAILABLE;\n}\n\nfunction getUnknownErrorMessage(error: unknown): string | null {\n if (error instanceof Error) {\n return error.message;\n }\n\n if (typeof error === \"string\") {\n return error;\n }\n\n return null;\n}\n\nfunction getDefaultSubmitInflowRequest(params: {\n action: SupplyAction;\n chain: string;\n}): Omit<SubmitInflowRequest, \"txid\"> | undefined {\n if (params.chain !== Chain.BTC && params.chain !== Chain.ETH) {\n return undefined;\n }\n\n return {\n chain: params.chain,\n type:\n params.action === SupplyAction.repayment\n ? InflowSubmitType.REPAY\n : InflowSubmitType.DEPOSIT,\n };\n}\n\nfunction shouldSubmitInflow(params: {\n instruction: SupplyInstruction;\n mechanism: SupplyPlanType;\n}): boolean {\n if (params.mechanism !== SupplyPlanType.transfer) {\n return true;\n }\n\n return !isEthStablecoin(params.instruction.asset, params.instruction.chain);\n}\n","import { LiquidiumError, LiquidiumErrorCode } from \"../errors\";\n\nconst ASSET_NATIVE_DECIMALS: Record<string, bigint> = {\n BTC: 8n,\n USDC: 6n,\n USDT: 6n,\n SOL: 9n,\n};\n\nexport function getAssetNativeDecimals(asset: string): bigint {\n const decimals = ASSET_NATIVE_DECIMALS[asset];\n\n if (decimals === undefined) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Native decimals are not configured for asset: ${asset}`\n );\n }\n\n return decimals;\n}\n","import type {\n LendingPoolRecord,\n PoolRateTuple,\n PriceRecord,\n} from \"../../core/canisters/lending/actor\";\nimport { RATE_DECIMALS } from \"../../core/rates\";\nimport { getAssetNativeDecimals } from \"../../core/utils/asset-decimals\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport type { AssetPrices, Pool } from \"./types\";\n\nconst DECIMAL_BASE = 10;\nconst PAIR_SEPARATOR = \"_\";\nconst USDT_SYMBOL = \"USDT\";\n\nexport function mapLendingPoolRecordToPool(\n pool: LendingPoolRecord,\n rate: PoolRateTuple\n): Pool {\n const asset = getVariantKey(pool.asset);\n const totalSupply = pool.total_supply_at_last_sync;\n const totalDebt = pool.total_debt_at_last_sync;\n const availableLiquidity =\n totalSupply > totalDebt ? totalSupply - totalDebt : 0n;\n\n return {\n id: pool.principal.toString(),\n asset,\n chain: getVariantKey(pool.chain),\n decimals: getAssetNativeDecimals(asset),\n frozen: pool.frozen,\n totalSupply,\n totalDebt,\n availableLiquidity,\n supplyCap: pool.supply_cap[0],\n borrowCap: pool.borrow_cap[0],\n maxLtv: pool.max_ltv,\n liquidationThreshold: pool.liquidation_threshold,\n liquidationBonus: pool.liquidation_bonus,\n protocolLiquidationFee: pool.protocol_liquidation_fee,\n reserveFactor: pool.reserve_factor,\n rateDecimals: RATE_DECIMALS,\n lendingRate: rate[1],\n borrowingRate: rate[0],\n utilizationRate: rate[2],\n baseRate: pool.base_rate,\n optimalUtilizationRate: pool.optimal_utilization_rate,\n rateSlopeBefore: pool.rate_slope_before,\n rateSlopeAfter: pool.rate_slope_after,\n lendingIndex: pool.lending_index,\n borrowIndex: pool.borrow_index,\n sameAssetBorrowing: pool.same_asset_borrowing[0] ?? false,\n lastUpdated: pool.last_updated[0],\n };\n}\n\nexport function mapGetPricesResponseToAssetPrices(\n prices: PriceRecord[]\n): AssetPrices {\n const pairPricesByName = new Map(\n prices.map(([pair, price, decimals]) => [\n pair,\n formatPrice(price, decimals),\n ])\n );\n const assetPrices: AssetPrices = {};\n\n for (const [pairName, pairPrice] of pairPricesByName) {\n const [baseAsset, quoteAsset] = pairName.split(PAIR_SEPARATOR);\n\n if (!baseAsset || !quoteAsset || quoteAsset !== USDT_SYMBOL) {\n continue;\n }\n\n assetPrices[baseAsset] = pairPrice;\n }\n\n return assetPrices;\n}\n\nexport function mapGetPoolRateResponseToPoolRate(rate: PoolRateTuple): {\n rateDecimals: bigint;\n borrowRate: bigint;\n lendRate: bigint;\n utilizationRate: bigint;\n} {\n return {\n rateDecimals: RATE_DECIMALS,\n borrowRate: rate[0],\n lendRate: rate[1],\n utilizationRate: rate[2],\n };\n}\n\nfunction formatPrice(price: bigint, decimals: number): number {\n const decimalScale = DECIMAL_BASE ** decimals;\n\n return Number(price) / decimalScale;\n}\n","import { Principal } from \"@dfinity/principal\";\nimport {\n createLendingActor,\n type PoolRateTuple,\n} from \"../../core/canisters/lending/actor\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport type { ApiClient } from \"../../core/transports/api-client\";\nimport type { CanisterContext } from \"../../core/transports/canister-context\";\nimport {\n mapGetPoolRateResponseToPoolRate,\n mapGetPricesResponseToAssetPrices,\n mapLendingPoolRecordToPool,\n} from \"./mappers\";\nimport type { AssetPrices, FindPoolQuery, Pool, PoolRate } from \"./types\";\n\nconst ZERO_POOL_RATE: PoolRateTuple = [0n, 0n, 0n];\n\n/** Pool metadata, prices, and current rate helpers. */\nexport class MarketModule {\n constructor(\n readonly canisterContext: CanisterContext,\n readonly apiClient: ApiClient | undefined\n ) {}\n\n /**\n * Lists all pools with their current rates.\n *\n * @returns All configured lending pools enriched with their current rate data.\n */\n async listPools(): Promise<Pool[]> {\n void this.apiClient;\n\n try {\n const lendingActor = createLendingActor(this.canisterContext);\n const lendingPools = await lendingActor.list_pools();\n\n return await Promise.all(\n lendingPools.map(async (pool) => {\n const poolRate = await lendingActor.get_pool_rate(pool.principal);\n const resolvedPoolRate = poolRate[0] ?? ZERO_POOL_RATE;\n\n return mapLendingPoolRecordToPool(pool, resolvedPoolRate);\n })\n );\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.CANISTER_REJECTED,\n \"Canister call failed: list_pools\",\n error\n );\n }\n }\n\n /**\n * Returns the latest asset prices reported by the protocol.\n *\n * @returns The latest protocol price map keyed by market asset symbol.\n */\n async getAssetPrices(): Promise<AssetPrices> {\n try {\n return mapGetPricesResponseToAssetPrices(\n await createLendingActor(this.canisterContext).get_prices()\n );\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.CANISTER_REJECTED,\n \"Canister call failed: get_prices\",\n error\n );\n }\n }\n\n /**\n * Resolves a single pool for the given asset and chain pair.\n *\n * @param query - The market asset and chain pair to match.\n * @returns The single pool that matches the requested asset and chain.\n */\n async findPool(query: FindPoolQuery): Promise<Pool> {\n const pools = await this.listPools();\n const matchedPools = pools.filter(\n (pool) => pool.asset === query.asset && pool.chain === query.chain\n );\n\n if (matchedPools.length === 0) {\n throw new LiquidiumError(\n LiquidiumErrorCode.POOL_NOT_FOUND,\n `Pool not found for asset ${query.asset} on chain ${query.chain}`\n );\n }\n\n if (matchedPools.length > 1) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Multiple pools found for asset ${query.asset} on chain ${query.chain}. Select a specific pool id.`\n );\n }\n\n return matchedPools[0];\n }\n\n /**\n * Returns the full pool record for the given asset and chain pair.\n *\n * Convenience wrapper over {@link MarketModule.findPool}. `listPools()` already\n * enriches each pool with its current rate data, so no extra canister call is made.\n *\n * @param query - The market asset and chain pair to match.\n * @returns The matching pool enriched with current rate data.\n */\n async getReserveData(query: FindPoolQuery): Promise<Pool> {\n return await this.findPool(query);\n }\n\n /**\n * Returns the current borrow, lend, and utilization rates for a pool.\n *\n * @param poolId - The pool principal text.\n * @returns The borrow, lend, and utilization rates for the requested pool.\n */\n async getPoolRate(poolId: string): Promise<PoolRate> {\n try {\n const rate = await createLendingActor(this.canisterContext).get_pool_rate(\n Principal.fromText(poolId)\n );\n\n if (!rate[0]) {\n throw new LiquidiumError(\n LiquidiumErrorCode.POOL_NOT_FOUND,\n `Pool not found: ${poolId}`\n );\n }\n\n return mapGetPoolRateResponseToPoolRate(rate[0]);\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.CANISTER_REJECTED,\n \"Canister call failed: get_pool_rate\",\n error\n );\n }\n }\n}\n","import type {\n BorrowingPowerRecord,\n UserStatsRecord,\n} from \"../../core/canisters/lending/actor\";\nimport { getAssetNativeDecimals } from \"../../core/utils/asset-decimals\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport type { PositionView } from \"../../generated/canisters/lending/lending.did\";\nimport type { BorrowingPower, Position, UserStats } from \"./types\";\n\nexport const USD_VALUE_SCALE_DECIMALS = 27n;\n\nexport function mapPositionViewToPosition(view: PositionView): Position {\n const asset = getVariantKey(view.asset);\n const nativeDecimals = getAssetNativeDecimals(asset);\n\n return {\n poolId: view.pool_id.toText(),\n asset,\n deposited: view.deposited_native_now,\n depositedDecimals: nativeDecimals,\n borrowed: view.debt_native_now,\n borrowedDecimals: nativeDecimals,\n earnedInterest: view.total_earned_interest + view.earned_since_snapshot,\n debtInterest: view.total_debt_interest + view.interest_since_snapshot,\n lastUpdate: view.last_update,\n };\n}\n\nexport function mapBorrowingPowerRecordToBorrowingPower(\n record: BorrowingPowerRecord\n): BorrowingPower {\n return {\n weightedMaxLtv: record.weighted_max_ltv,\n maxBorrowableUsd: record.max_borrowable_usd,\n maxBorrowableUsdDecimals: USD_VALUE_SCALE_DECIMALS,\n };\n}\n\nexport function mapUserStatsRecordToUserStats(\n record: UserStatsRecord\n): UserStats {\n return {\n debt: record.debt,\n debtDecimals: USD_VALUE_SCALE_DECIMALS,\n collateral: record.collateral,\n collateralDecimals: USD_VALUE_SCALE_DECIMALS,\n weightedLiquidationThreshold: record.weighted_liquidation_threshold,\n borrowingPower: mapBorrowingPowerRecordToBorrowingPower(\n record.borrowing_power\n ),\n };\n}\n","import { Principal } from \"@dfinity/principal\";\nimport { createLendingActor } from \"../../core/canisters/lending/actor\";\nimport { mapCanisterCallErrorToLiquidiumError } from \"../../core/canisters/lending/error-mappers\";\nimport { LiquidiumError } from \"../../core/errors\";\nimport type { CanisterContext } from \"../../core/transports/canister-context\";\nimport type { MarketModule } from \"../market/market\";\nimport type { Pool } from \"../market/types\";\nimport {\n mapPositionViewToPosition,\n mapUserStatsRecordToUserStats,\n USD_VALUE_SCALE_DECIMALS,\n} from \"./mappers\";\nimport type {\n HealthFactor,\n MaxRepayAmount,\n Position,\n UserPositionSummary,\n UserReserve,\n UserStats,\n} from \"./types\";\n\nconst BPS_SCALE = 10000n;\nconst DEFAULT_REPAY_BUFFER_BPS = 10n;\n\n/** Profile position, health factor, and reserve valuation helpers. */\nexport class PositionsModule {\n constructor(\n readonly canisterContext: CanisterContext,\n readonly market: MarketModule\n ) {}\n\n /**\n * Returns a single position for a profile and pool.\n *\n * @param profileId - The Liquidium profile principal text.\n * @param poolId - The pool principal text.\n * @returns The position for the requested profile and pool, or `null` when no position exists.\n */\n async getPosition(\n profileId: string,\n poolId: string\n ): Promise<Position | null> {\n try {\n const result = await createLendingActor(\n this.canisterContext\n ).get_position(Principal.fromText(profileId), Principal.fromText(poolId));\n\n const view = result[0];\n if (!view) {\n return null;\n }\n\n return mapPositionViewToPosition(view);\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_position\", error);\n }\n }\n\n /**\n * Lists all positions for a profile.\n *\n * @param profileId - The Liquidium profile principal text.\n * @returns All positions currently associated with the requested profile.\n */\n async listPositions(profileId: string): Promise<Position[]> {\n try {\n const actor = createLendingActor(this.canisterContext);\n const profilePrincipal = Principal.fromText(profileId);\n const stats = await actor.get_profile_stats(profilePrincipal);\n\n const positionViews = await Promise.all(\n stats.positions.map((position) =>\n actor.get_position(profilePrincipal, position.pool_id)\n )\n );\n\n return positionViews\n .map((result) => result[0])\n .filter((view): view is NonNullable<typeof view> => view !== undefined)\n .map(mapPositionViewToPosition);\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"list_positions\", error);\n }\n }\n\n /**\n * Returns the current health factor for a profile.\n *\n * @param profileId - The Liquidium profile principal text.\n * @returns The current health factor for the requested profile.\n */\n async getHealthFactor(profileId: string): Promise<HealthFactor> {\n try {\n const [healthFactor, userStatsRecord] = await createLendingActor(\n this.canisterContext\n ).get_health_factor(Principal.fromText(profileId));\n\n return {\n healthFactor,\n userStats: mapUserStatsRecordToUserStats(userStatsRecord),\n };\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_health_factor\", error);\n }\n }\n\n /**\n * Returns aggregate borrowing and collateral stats for a profile.\n *\n * @param profileId - The Liquidium profile principal text.\n * @returns Aggregate debt, collateral, and borrowing power metrics for the requested profile.\n */\n async getUserStats(profileId: string): Promise<UserStats> {\n try {\n const result = await createLendingActor(\n this.canisterContext\n ).get_profile_stats(Principal.fromText(profileId));\n\n return mapUserStatsRecordToUserStats(result);\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_profile_stats\", error);\n }\n }\n\n /**\n * Returns an aggregate summary of a profile's position.\n *\n * Single canister round-trip (`get_health_factor`). Derived fields:\n * `availableBorrowsUsd = max(0, maxBorrowableUsd - debt)`,\n * `netWorthUsd = collateral - debt` (may be negative if underwater),\n * `currentLtvBps = debt * 10_000 / collateral` (0 when collateral is 0).\n *\n * @param profileId - The Liquidium profile principal text.\n * @returns Derived position summary for the requested profile.\n */\n async getUserPositionSummary(\n profileId: string\n ): Promise<UserPositionSummary> {\n const { healthFactor, userStats } = await this.getHealthFactor(profileId);\n\n const collateral = userStats.collateral;\n const debt = userStats.debt;\n const maxBorrowableUsd = userStats.borrowingPower.maxBorrowableUsd;\n const availableBorrowsUsd =\n maxBorrowableUsd > debt ? maxBorrowableUsd - debt : 0n;\n const netWorthUsd = collateral - debt;\n const currentLtvBps =\n collateral > 0n ? (debt * BPS_SCALE) / collateral : 0n;\n\n return {\n totalCollateralUsd: collateral,\n totalDebtUsd: debt,\n availableBorrowsUsd,\n netWorthUsd,\n usdDecimals: USD_VALUE_SCALE_DECIMALS,\n currentLtvBps,\n weightedMaxLtvBps: userStats.borrowingPower.weightedMaxLtv,\n weightedLiquidationThresholdBps: userStats.weightedLiquidationThreshold,\n healthFactor,\n };\n }\n\n /**\n * Returns the per-reserve breakdown of a profile's supplies and borrows,\n * joined with pool metadata, rates, and current USD prices.\n *\n * USD values are scaled to {@link USD_VALUE_SCALE_DECIMALS} (27).\n *\n * @param profileId - The Liquidium profile principal text.\n * @returns Per-reserve position rows joined with pool metadata and USD values.\n */\n async getUserReserves(profileId: string): Promise<UserReserve[]> {\n const [positions, pools, prices] = await Promise.all([\n this.listPositions(profileId),\n this.market.listPools(),\n this.market.getAssetPrices(),\n ]);\n\n const poolsById = new Map<string, Pool>(\n pools.map((pool) => [pool.id, pool])\n );\n\n return positions.flatMap((position) => {\n const pool = poolsById.get(position.poolId);\n if (!pool) {\n return [];\n }\n\n const priceUsd = prices[position.asset] ?? 0;\n\n return [\n {\n position,\n pool,\n priceUsd,\n suppliedUsd: nativeAmountToUsdScaled(\n position.deposited + position.earnedInterest,\n position.depositedDecimals,\n priceUsd\n ),\n borrowedUsd: nativeAmountToUsdScaled(\n position.borrowed + position.debtInterest,\n position.borrowedDecimals,\n priceUsd\n ),\n usdDecimals: USD_VALUE_SCALE_DECIMALS,\n },\n ];\n });\n }\n\n /**\n * Returns the full repayment amount for a position, with a small buffer to\n * account for interest that accrues between quote and submit.\n *\n * @param profileId - The Liquidium profile principal text.\n * @param poolId - The pool principal text.\n * @param bufferBps - Optional buffer in basis points (default 10 = 0.1%).\n * @returns Buffered repayment amount in the borrowed asset's base units.\n */\n async getMaxRepayAmount(\n profileId: string,\n poolId: string,\n bufferBps: bigint = DEFAULT_REPAY_BUFFER_BPS\n ): Promise<MaxRepayAmount> {\n const position = await this.getPosition(profileId, poolId);\n if (!position) {\n return { amount: 0n, decimals: 0n };\n }\n\n const rawDebt = position.borrowed + position.debtInterest;\n if (rawDebt <= 0n) {\n return { amount: 0n, decimals: position.borrowedDecimals };\n }\n\n const buffered = (rawDebt * (BPS_SCALE + bufferBps)) / BPS_SCALE;\n\n return { amount: buffered, decimals: position.borrowedDecimals };\n }\n}\n\nfunction nativeAmountToUsdScaled(\n amount: bigint,\n nativeDecimals: bigint,\n priceUsd: number\n): bigint {\n if (amount <= 0n || priceUsd <= 0) {\n return 0n;\n }\n\n const priceScaleDecimals = 12n;\n const priceScale = 10n ** priceScaleDecimals;\n const priceScaled = BigInt(Math.round(priceUsd * Number(priceScale)));\n const nativeToUsdScale = USD_VALUE_SCALE_DECIMALS - nativeDecimals;\n\n return (amount * priceScaled * 10n ** nativeToUsdScale) / priceScale;\n}\n","import { createPublicClient, http } from \"viem\";\nimport { mainnet } from \"viem/chains\";\nimport {\n DEFAULT_API_BASE_URL,\n DEFAULT_ENVIRONMENT,\n DEFAULT_TIMEOUT_MS,\n resolveCanisterIds,\n} from \"./core/config\";\nimport type { ApiClient } from \"./core/transports/api-client\";\nimport { createApiClient } from \"./core/transports/api-client\";\nimport type { CanisterContext } from \"./core/transports/canister-context\";\nimport { createCanisterContext } from \"./core/transports/canister-context\";\nimport type { EvmReadClient, LiquidiumClientConfig } from \"./core/types\";\nimport { AccountsModule } from \"./modules/accounts\";\nimport { ActivitiesModule } from \"./modules/activities\";\nimport { HistoryModule } from \"./modules/history\";\nimport { InstantLoansModule } from \"./modules/instant-loans\";\nimport { LendingModule } from \"./modules/lending\";\nimport { MarketModule } from \"./modules/market\";\nimport { PositionsModule } from \"./modules/positions\";\nimport { QuoteModule } from \"./modules/quote\";\n\n/**\n * Root client for Liquidium protocol integration (canister + optional HTTP API).\n *\n * Construct with `new LiquidiumClient(config)`.\n */\nexport class LiquidiumClient {\n /** Profile lifecycle: create, resolve, linked wallets. */\n readonly accounts: AccountsModule;\n /** Borrow, withdraw, supply, inflow reporting and tracking. */\n readonly lending: LendingModule;\n /** Per-pool positions, health, aggregate stats. */\n readonly positions: PositionsModule;\n /** Pool list, prices, pool rate lookups. */\n readonly market: MarketModule;\n /** Receipt-oriented activity status and activity lists. */\n readonly activities: ActivitiesModule;\n /** Pool and user history through the Liquidium SDK API. */\n readonly history: HistoryModule;\n /** Accountless instant loans backed by generated deposit/repay targets. */\n readonly instantLoans: InstantLoansModule;\n /** Pure quote helpers from market inputs. */\n readonly quote: QuoteModule;\n\n private readonly canisterContext: CanisterContext;\n private readonly apiClient: ApiClient | undefined;\n private readonly evmReadClient: EvmReadClient | undefined;\n\n /**\n * Creates a Liquidium SDK client.\n *\n * @param config - Runtime transport, canister, API, identity, and EVM read options.\n */\n constructor(config: LiquidiumClientConfig = {}) {\n const environment = config.environment ?? DEFAULT_ENVIRONMENT;\n const canisterIds = resolveCanisterIds(environment, config.canisterIds);\n const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n\n this.canisterContext = createCanisterContext({\n icHost: config.icHost,\n identity: config.identity,\n canisterIds,\n });\n\n this.apiClient = createApiClient({\n baseUrl: config.apiBaseUrl ?? DEFAULT_API_BASE_URL,\n headers: config.headers,\n fetchFn: config.fetch,\n timeoutMs,\n });\n\n this.evmReadClient = resolveEvmReadClient(config);\n\n this.accounts = new AccountsModule(this.canisterContext);\n this.lending = new LendingModule(\n this.canisterContext,\n this.apiClient,\n this.evmReadClient\n );\n this.market = new MarketModule(this.canisterContext, this.apiClient);\n this.positions = new PositionsModule(this.canisterContext, this.market);\n this.activities = new ActivitiesModule(\n this.apiClient,\n this.canisterContext\n );\n this.history = new HistoryModule(this.apiClient);\n this.instantLoans = new InstantLoansModule(\n this.canisterContext,\n this.apiClient,\n this.lending,\n this.positions\n );\n this.quote = new QuoteModule();\n }\n}\n\nfunction resolveEvmReadClient(\n config: LiquidiumClientConfig\n): EvmReadClient | undefined {\n if (config.evmPublicClient) {\n return config.evmPublicClient;\n }\n\n if (!config.evmRpcUrl) {\n return undefined;\n }\n\n return createPublicClient({\n chain: mainnet,\n transport: http(config.evmRpcUrl, {\n fetchOptions: config.evmRpcHeaders\n ? { headers: config.evmRpcHeaders }\n : undefined,\n }),\n });\n}\n"]}