@liquidium/client 0.3.3 → 0.4.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.
package/dist/index.js.map CHANGED
@@ -1 +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/utils/variant-tags.ts","../src/core/canisters/instant-loans/flexible-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/core/utils/api-response-parsers.ts","../src/core/utils/asset-decimals.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/core/borrow-minimums.ts","../src/modules/quote/types.ts","../src/modules/quote/quote.ts","../src/core/address-validation.ts","../src/modules/instant-loans/_internal/address-validation.ts","../src/modules/instant-loans/types.ts","../src/modules/instant-loans/instant-loans.ts","../src/modules/lending/evm-transactions.ts","../src/core/canisters/ckbtc/ledger.ts","../src/core/canisters/lending/messages.ts","../src/core/utils/retry.ts","../src/modules/lending/_internal/inflow-fee-rounding.ts","../src/modules/lending/mappers.ts","../src/modules/lending/lending.ts","../src/core/canisters/lending/flexible-actor.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","encodeBytesToHex","Actor","MILLISECONDS_PER_SECOND","idlFactory","subaccount","Principal","QuoteValidationErrorCode","QuoteWarningCode","validateBitcoinAddress","BitcoinAddressNetwork","isEthStablecoin","isAddress","getAddress","RATE_SCALE","formatBpsAsPercent","encodeIcrcAccount"],"mappings":";;;;;;;;;;;;AAwDO,IAAM,WAAA,GAAc;AAAA,EACzB,OAAA,EAAS;AACX;AAKO,IAAM,KAAA,GAAQ;AAAA,EACnB,GAAA,EAAK,KAAA;AAAA,EACL,GAAA,EAAK,KAAA;AAAA,EACL,IAAA,EAAM,MAAA;AAAA,EACN,IAAA,EAAM;AACR;AAKO,IAAM,KAAA,GAAQ;AAAA,EACnB,GAAA,EAAK,KAAA;AAAA,EACL,GAAA,EAAK;AACP;AAUO,IAAM,YAAA,GAAe;AAAA,EAC1B,OAAA,EAAS,SAAA;AAAA,EACT,SAAA,EAAW;AACb;AAKO,IAAM,WAAA,GAAc;AAAA,EACzB,MAAA,EAAQ,QAAA;AAAA,EACR,QAAA,EAAU,UAAA;AAAA,EACV,QAAA,EAAU;AACZ;AAKO,IAAM,gBAAA,GAAmB;AAAA,EAC9B,OAAA,EAAS,SAAA;AAAA,EACT,KAAA,EAAO;AACT;;;ACxGA,IAAM,YAAA,GAAe,oBAAA;AACd,IAAM,oBAAA,GAAuB,kCAAA;AAC7B,IAAM,sBAAmC,WAAA,CAAY,OAAA;AAE5D,IAAM,oBAAA,GAAoC;AAAA,EACxC,OAAA,EAAS,6BAAA;AAAA,EACT,OAAA,EAAS,6BAAA;AAAA,EACT,OAAA,EAAS,6BAAA;AAAA,EACT,UAAA,EAAY,6BAAA;AAAA,EACZ,YAAA,EAAc;AAChB,CAAA;AAEA,IAAM,2BAAA,GAAgE;AAAA,EACpE,OAAA,EAAS;AACX,CAAA;AAEO,SAAS,YAAY,QAAA,EAA2B;AACrD,EAAA,OAAO,QAAA,IAAY,YAAA;AACrB;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;AAAA,EAChB;AAEA,EAAA,IAAI,CAAC,OAAO,SAAA,EAAW;AACrB,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,OAAO,kBAAA,CAAmB;AAAA,IACxB,KAAA,EAAO,OAAA;AAAA,IACP,SAAA,EAAW,IAAA,CAAK,MAAA,CAAO,SAAA,EAAW;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 \"@icp-sdk/core/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 `@icp-sdk/core/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\ninterface CreateApiClientOptions {\n baseUrl: string;\n headers?: Record<string, string>;\n timeoutMs: number;\n fetchFn?: typeof fetch;\n}\n\ninterface SendRequestOptions {\n baseUrl: string;\n fetchFn?: typeof fetch;\n headers?: Record<string, string>;\n timeoutMs: number;\n}\n\ninterface ApiRequest {\n path: string;\n method: typeof HTTP_METHOD_GET | typeof HTTP_METHOD_POST;\n body?: unknown;\n}\n\ninterface ResponseErrorContext {\n traceId?: string;\n requestId?: string;\n}\n\ninterface JsonErrorPayload {\n message?: unknown;\n}\n\nexport function createApiClient(opts: CreateApiClientOptions): 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: SendRequestOptions,\n request: ApiRequest\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 JsonErrorPayload).message;\n return typeof message === \"string\" && message.length > 0 ? message : null;\n}\n\nfunction getResponseErrorContext(response: Response): ResponseErrorContext {\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: ResponseErrorContext\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 \"@icp-sdk/core/agent\";\nimport { HttpAgent } from \"@icp-sdk/core/agent\";\nimport { resolveHost } from \"../config\";\nimport type { CanisterIds } from \"../types\";\n\nexport interface CanisterContext {\n agent: HttpAgent;\n canisterIds: CanisterIds;\n}\n\ninterface CreateCanisterContextOptions {\n icHost?: string;\n identity?: Identity;\n canisterIds: CanisterIds;\n}\n\nexport function createCanisterContext(\n opts: CreateCanisterContextOptions\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 \"@icp-sdk/core/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\ninterface 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: object): 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. BTC adapters may return base64 BIP-322 or hex-encoded signature bytes. */\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. BTC signatures may be base64 BIP-322 or hex-encoded bytes. */\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/** Request submitted after a BTC PSBT has been signed. */\nexport interface SignPsbtSubmitRequest {\n /** Base64-encoded signed PSBT. */\n signedPsbtBase64: string;\n}\n\n/** Request submitted after an ETH transaction has been sent. */\nexport interface SendEthTransactionSubmitRequest {\n /** EVM transaction hash returned by the wallet. */\n txHash: 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: SignPsbtSubmitRequest): 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: SendEthTransactionSubmitRequest): 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\ninterface WalletExecutionKindCarrier {\n executionKind?: unknown;\n}\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 WalletExecutionKindCarrier).executionKind\n )}`\n );\n }\n };\n}\n","import { base64, base64nopad } from \"@scure/base\";\nimport { bytesToHex as encodeBytesToHex, isHex } from \"viem\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../errors\";\nimport { Chain, type Chain as ChainName } from \"../types\";\n\nconst HEX_PREFIX = \"0x\";\nconst HEX_BYTE_CHAR_LENGTH = 2;\nconst BASE64_PADDING = \"=\";\n\nexport function normalizeWalletSignature(\n signature: string,\n chain: ChainName\n): string {\n switch (chain) {\n case Chain.BTC:\n return normalizeBtcSignature(signature);\n case Chain.ETH:\n return normalizeHexSignature(signature);\n }\n}\n\nexport function normalizeHexSignature(signature: string): string {\n if (!isPrefixedHex(signature)) {\n return signature;\n }\n\n return signature.slice(HEX_PREFIX.length);\n}\n\nfunction normalizeBtcSignature(signature: string): string {\n const signatureWithoutPrefix = signature.startsWith(HEX_PREFIX)\n ? signature.slice(HEX_PREFIX.length)\n : signature;\n\n if (isHexBytes(signatureWithoutPrefix)) {\n return signatureWithoutPrefix;\n }\n\n if (signature.startsWith(HEX_PREFIX)) {\n throw invalidBtcSignatureFormatError();\n }\n\n return bytesToUnprefixedHex(decodeBase64Signature(signature));\n}\n\nfunction isHexBytes(signature: string): boolean {\n return (\n signature.length > 0 &&\n signature.length % HEX_BYTE_CHAR_LENGTH === 0 &&\n isHex(`${HEX_PREFIX}${signature}`)\n );\n}\n\nfunction decodeBase64Signature(signature: string): Uint8Array {\n try {\n const bytes = decodeBase64Bytes(signature);\n\n if (bytes.length === 0) {\n throw invalidBtcSignatureFormatError();\n }\n\n return bytes;\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw invalidBtcSignatureFormatError(error);\n }\n}\n\nfunction bytesToUnprefixedHex(bytes: Uint8Array): string {\n return normalizeHexSignature(encodeBytesToHex(bytes));\n}\n\nfunction isPrefixedHex(signature: string): boolean {\n return signature.length > HEX_PREFIX.length && isHex(signature);\n}\n\nfunction decodeBase64Bytes(signature: string): Uint8Array {\n if (signature.includes(BASE64_PADDING)) {\n return base64.decode(signature);\n }\n\n return base64nopad.decode(signature);\n}\n\nfunction invalidBtcSignatureFormatError(cause?: unknown): LiquidiumError {\n return new LiquidiumError(\n LiquidiumErrorCode.SIGNATURE_ERROR,\n \"BTC signature must be hex or base64-encoded bytes\",\n cause\n );\n}\n","import type { RegisterProfileRequest } from \"../../core/canisters/lending/actor\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport { Chain } from \"../../core/types\";\nimport { normalizeWalletSignature } from \"../../core/utils/signature\";\nimport type { CreateAccountRequest } from \"./types\";\n\ninterface AccountBtcChainVariant {\n BTC: null;\n}\n\ninterface AccountEthChainVariant {\n ETH: null;\n}\n\ntype AccountChainVariant = AccountBtcChainVariant | AccountEthChainVariant;\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: normalizeWalletSignature(\n request.signatureInfo.signature,\n request.signatureInfo.chain\n ),\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 \"@icp-sdk/core/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 WalletExecutionKind,\n} from \"../../core/wallet-actions\";\nimport { executeWith } from \"../../execute\";\nimport { mapCreateAccountRequestToRegisterProfileRequest } from \"./mappers\";\nimport type {\n CreateAccountAction,\n CreateAccountRequest,\n CreateProfileParams,\n PrepareCreateProfileOptions,\n} from \"./types\";\n\n/** Profile lifecycle and linked-wallet helpers. */\nexport class AccountsModule {\n constructor(private 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 { idlLabelToId } from \"@icp-sdk/core/candid\";\n\n// Asset and chain tags supported by this SDK version. Unknown tags returned by\n// the canister are ignored rather than causing the whole call to fail.\nexport const KNOWN_ASSET_TAGS = [\"BTC\", \"SOL\", \"USDC\", \"USDT\"] as const;\nexport const KNOWN_CHAIN_TAGS = [\"BTC\", \"ETH\", \"SOL\"] as const;\n\nexport type KnownAssetTag = (typeof KNOWN_ASSET_TAGS)[number];\nexport type KnownChainTag = (typeof KNOWN_CHAIN_TAGS)[number];\n\nexport function extractVariantTag(\n variant: object,\n knownTags: readonly string[]\n): string | null {\n const [key] = Object.keys(variant);\n\n if (!key) {\n return null;\n }\n\n // Known variants decoded by a matching IDL already use the tag name.\n if (knownTags.includes(key)) {\n return key;\n }\n\n // IDL.Unknown returns variants with hashed field names: _${hash}_\n const hashMatch = /^_(\\d+)_$/.exec(key);\n if (!hashMatch) {\n return null;\n }\n\n const hash = Number(hashMatch[1]);\n\n for (const tag of knownTags) {\n if (idlLabelToId(tag) === hash) {\n return tag;\n }\n }\n\n return null;\n}\n","import type { ActorMethod } from \"@icp-sdk/core/agent\";\nimport { Actor } from \"@icp-sdk/core/agent\";\nimport type { IDL } from \"@icp-sdk/core/candid\";\nimport type { Principal } from \"@icp-sdk/core/principal\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { CanisterContext } from \"../../transports/canister-context\";\nimport { extractVariantTag, KNOWN_ASSET_TAGS } from \"../../utils/variant-tags\";\nimport type {\n CreateInstantLoanCanisterRequest,\n HeadlessLoanCreatedEventPayload,\n HeadlessLoanEventType,\n HeadlessLoansConfig,\n InstantLoanAccountType,\n InstantLoanAuthorisation,\n InstantLoansCanisterError,\n WarmedProfile,\n} from \"./actor\";\n\nexport interface FlexibleCreateInstantLoanCanisterResponse {\n loan_id: bigint;\n lending_profile: Principal;\n}\n\nexport interface FlexibleHeadlessLoanCreatedEventPayload {\n loan_id: bigint;\n borrow_destination: InstantLoanAccountType;\n lend_asset: object;\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: object;\n}\n\nexport interface FlexibleHeadlessLoanCreatedEventType {\n LoanCreated: FlexibleHeadlessLoanCreatedEventPayload;\n}\n\nexport type FlexibleHeadlessLoanEventType =\n | FlexibleHeadlessLoanCreatedEventType\n | HeadlessLoanEventTypeWithoutAssets;\n\ntype HeadlessLoanEventTypeWithoutAssets = Exclude<\n HeadlessLoanEventType,\n { LoanCreated: HeadlessLoanCreatedEventPayload }\n>;\n\nexport interface FlexibleHeadlessLoanEvent {\n id: bigint;\n schema_version: number;\n timestamp: bigint;\n event_type: FlexibleHeadlessLoanEventType;\n}\n\nexport interface FlexibleInstantLoanCanisterRecord {\n id: bigint;\n authorisation: InstantLoanAuthorisation;\n borrow_destination: InstantLoanAccountType;\n started: boolean;\n lend_asset: object;\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: object;\n expires_at: [] | [bigint];\n deposit_detected_ts: [] | [bigint];\n}\n\nexport interface DecodedHeadlessLoanCreatedEventPayload {\n loan_id: bigint;\n borrow_destination: InstantLoanAccountType;\n lend_asset: string;\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: string;\n}\n\nexport type DecodedHeadlessLoanEventType =\n | { LoanCreated: DecodedHeadlessLoanCreatedEventPayload }\n | HeadlessLoanEventTypeWithoutAssets;\n\nexport interface DecodedHeadlessLoanEvent {\n id: bigint;\n schema_version: number;\n timestamp: bigint;\n event_type: DecodedHeadlessLoanEventType;\n}\n\nexport interface DecodedInstantLoanCanisterRecord {\n id: bigint;\n authorisation: InstantLoanAuthorisation;\n borrow_destination: InstantLoanAccountType;\n started: boolean;\n lend_asset: string;\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: string;\n expires_at: [] | [bigint];\n deposit_detected_ts: [] | [bigint];\n}\n\ntype FlexibleResult<T> = { Ok: T } | { Err: InstantLoansCanisterError };\n\nexport interface FlexibleInstantLoansActor {\n create_loan: ActorMethod<\n [CreateInstantLoanCanisterRequest],\n FlexibleResult<FlexibleCreateInstantLoanCanisterResponse>\n >;\n count_warmed_profiles: ActorMethod<[], bigint>;\n get_config: ActorMethod<[], HeadlessLoansConfig>;\n get_event: ActorMethod<[bigint], [] | [FlexibleHeadlessLoanEvent]>;\n get_loan: ActorMethod<\n [bigint],\n FlexibleResult<FlexibleInstantLoanCanisterRecord>\n >;\n list_access_list: ActorMethod<[], Principal[]>;\n list_events: ActorMethod<\n [bigint, bigint],\n Array<[bigint, FlexibleHeadlessLoanEvent]>\n >;\n list_warmed_profiles: ActorMethod<[], WarmedProfile[]>;\n}\n\nconst flexibleInstantLoansIdlFactory: IDL.InterfaceFactory = ({ IDL }) => {\n const AccountType = IDL.Variant({\n Native: IDL.Principal,\n External: IDL.Text,\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: IDL.Unknown,\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: IDL.Unknown,\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: IDL.Unknown,\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: IDL.Unknown,\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: IDL.Unknown,\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: IDL.Unknown,\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 createFlexibleInstantLoansActor(\n canisterContext: CanisterContext\n): FlexibleInstantLoansActor {\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<FlexibleInstantLoansActor>(\n flexibleInstantLoansIdlFactory,\n {\n agent: canisterContext.agent,\n canisterId,\n }\n );\n}\n\nexport function decodeFlexibleInstantLoanRecord(\n record: FlexibleInstantLoanCanisterRecord\n): DecodedInstantLoanCanisterRecord | null {\n const lend_asset = extractVariantTag(record.lend_asset, KNOWN_ASSET_TAGS);\n const borrow_asset = extractVariantTag(record.borrow_asset, KNOWN_ASSET_TAGS);\n\n if (!lend_asset || !borrow_asset) {\n return null;\n }\n\n return {\n id: record.id,\n authorisation: record.authorisation,\n borrow_destination: record.borrow_destination,\n started: record.started,\n lend_asset,\n created_at: record.created_at,\n schema_version: record.schema_version,\n borrow_amount: record.borrow_amount,\n lend_pool_id: record.lend_pool_id,\n refund_destination: record.refund_destination,\n ltv_max_bps: record.ltv_max_bps,\n ltv_timer_s: record.ltv_timer_s,\n lending_profile: record.lending_profile,\n borrow_pool_id: record.borrow_pool_id,\n borrow_asset,\n expires_at: record.expires_at,\n deposit_detected_ts: record.deposit_detected_ts,\n };\n}\n\nexport function decodeFlexibleHeadlessLoanEvent(\n event: FlexibleHeadlessLoanEvent\n): DecodedHeadlessLoanEvent | null {\n if (\"LoanCreated\" in event.event_type) {\n const decoded = decodeLoanCreatedEvent(event.event_type.LoanCreated);\n\n if (!decoded) {\n return null;\n }\n\n return {\n id: event.id,\n schema_version: event.schema_version,\n timestamp: event.timestamp,\n event_type: decoded,\n };\n }\n\n return {\n id: event.id,\n schema_version: event.schema_version,\n timestamp: event.timestamp,\n event_type: event.event_type as DecodedHeadlessLoanEventType,\n };\n}\n\nfunction decodeLoanCreatedEvent(\n payload: FlexibleHeadlessLoanCreatedEventPayload\n): DecodedHeadlessLoanEventType | null {\n const lend_asset = extractVariantTag(payload.lend_asset, KNOWN_ASSET_TAGS);\n const borrow_asset = extractVariantTag(\n payload.borrow_asset,\n KNOWN_ASSET_TAGS\n );\n\n if (!lend_asset || !borrow_asset) {\n return null;\n }\n\n return {\n LoanCreated: {\n loan_id: payload.loan_id,\n borrow_destination: payload.borrow_destination,\n lend_asset,\n borrow_amount: payload.borrow_amount,\n lend_pool_id: payload.lend_pool_id,\n refund_destination: payload.refund_destination,\n ltv_max_bps: payload.ltv_max_bps,\n ltv_timer_s: payload.ltv_timer_s,\n lending_profile: payload.lending_profile,\n borrow_pool_id: payload.borrow_pool_id,\n borrow_asset,\n },\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\ninterface BuildActivitiesPathRequest {\n profileId: string;\n state?: string;\n}\n\ninterface BuildActivityStatusPathRequest {\n profileId: string;\n id: string;\n}\n\ninterface BuildInstantLoanFindPathRequest {\n query: string;\n}\n\ninterface BuildInstantLoanCollateralHintPathRequest {\n loanId: bigint;\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 buildInstantLoanFindPath(\n request: BuildInstantLoanFindPathRequest\n): string {\n const query = new URLSearchParams({ query: request.query });\n return `${INSTANT_LOANS}/find?${query.toString()}`;\n}\n\nexport function buildInstantLoanCollateralHintPath(\n request: BuildInstantLoanCollateralHintPathRequest\n): string {\n return `${INSTANT_LOANS}/${encodeURIComponent(\n request.loanId.toString()\n )}/collateral-hint`;\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/** Shared request fields for listing activities. */\nexport interface BaseListActivitiesRequest {\n /** Optional state filter; defaults to `all`. */\n filter?: ActivityFilter;\n}\n\n/** Activity list request scoped to a Liquidium profile. */\nexport interface ListActivitiesByProfileRequest\n extends BaseListActivitiesRequest {\n /** Profile principal text to list activities for. */\n profileId: string;\n}\n\n/** Activity list request scoped to an instant-loan short reference. */\nexport interface ListActivitiesByShortRefRequest\n extends BaseListActivitiesRequest {\n /** Instant-loan short reference to list activities for. */\n shortRef: string;\n}\n\n/** Request for listing activities by profile id or instant-loan short reference. */\nexport type ListActivitiesRequest =\n | ListActivitiesByProfileRequest\n | ListActivitiesByShortRefRequest;\n\n/** Shared request fields for an activity status lookup. */\nexport interface BaseGetActivityStatusRequest {\n /** Activity or receipt id to look up. */\n id: string;\n}\n\n/** Activity status lookup scoped to a Liquidium profile. */\nexport interface GetActivityStatusByProfileRequest\n extends BaseGetActivityStatusRequest {\n /** Profile principal text that owns the activity. */\n profileId: string;\n}\n\n/** Activity status lookup scoped to an instant-loan short reference. */\nexport interface GetActivityStatusByShortRefRequest\n extends BaseGetActivityStatusRequest {\n /** Instant-loan short reference that owns the activity. */\n shortRef: string;\n}\n\n/** Request for fetching one activity by id and owner identifier. */\nexport type GetActivityStatusRequest =\n | GetActivityStatusByProfileRequest\n | GetActivityStatusByShortRefRequest;\n\n/** Successful activity status lookup result. */\nexport interface ActivityStatusFoundResponse {\n /** Indicates the activity was found. */\n found: true;\n /** Matched activity. */\n activity: Activity;\n}\n\n/** Missing activity status lookup result. */\nexport interface ActivityStatusNotFoundResponse {\n /** Indicates the activity was not found. */\n found: false;\n /** Requested activity or receipt id. */\n id: string;\n}\n\n/** Result of an activity status lookup. */\nexport type GetActivityStatusResponse =\n | ActivityStatusFoundResponse\n | ActivityStatusNotFoundResponse;\n","import type { InstantLoansCanisterError } from \"../../core/canisters/instant-loans/actor\";\nimport { createFlexibleInstantLoansActor } from \"../../core/canisters/instant-loans/flexible-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\ninterface ActivityTopUpWire\n extends 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\ninterface 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\ninterface ListActivitiesResponseWire {\n success: true;\n activities: ActivityWire[];\n}\n\ninterface ActivityStatusFoundResponseWire {\n success: true;\n found: true;\n activity: ActivityWire;\n}\n\ninterface ActivityStatusNotFoundResponseWire {\n success: true;\n found: false;\n id: string;\n}\n\ntype ActivityStatusResponseWire =\n | ActivityStatusFoundResponseWire\n | ActivityStatusNotFoundResponseWire;\n\n/** Receipt-oriented activity list and status helpers. */\nexport class ActivitiesModule {\n constructor(\n private readonly apiClient: ApiClient | undefined,\n private 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 createFlexibleInstantLoansActor(\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(private 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","import { LiquidiumError, LiquidiumErrorCode } from \"../errors\";\n\nconst MILLISECONDS_PER_SECOND = 1_000;\n\nexport interface ApiResponseFieldContext {\n context: string;\n label: string;\n}\n\nexport function parseNonEmptyApiString(\n value: string | undefined,\n field: ApiResponseFieldContext\n): string {\n if (!value) {\n throwInvalidApiResponseField(field);\n }\n\n return value;\n}\n\nexport function parseUnsignedApiBigint(\n value: string | undefined,\n field: ApiResponseFieldContext\n): bigint {\n if (!value || !/^\\d+$/.test(value)) {\n throwInvalidApiResponseField(field);\n }\n\n return BigInt(value);\n}\n\nexport function parseIsoApiTimestampToUnixSeconds(\n value: string | undefined,\n field: ApiResponseFieldContext\n): bigint {\n const timestamp = parseNonEmptyApiString(value, field);\n const timestampMilliseconds = Date.parse(timestamp);\n\n if (!Number.isFinite(timestampMilliseconds)) {\n throwInvalidApiResponseField(field);\n }\n\n return BigInt(Math.floor(timestampMilliseconds / MILLISECONDS_PER_SECOND));\n}\n\nexport function parseApiStringUnion<const TValue extends string>(\n value: string | undefined,\n allowedValues: readonly TValue[],\n field: ApiResponseFieldContext\n): TValue {\n if (value !== undefined && allowedValues.includes(value as TValue)) {\n return value as TValue;\n }\n\n throwInvalidApiResponseField(field);\n}\n\nfunction throwInvalidApiResponseField(field: ApiResponseFieldContext): never {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Invalid ${field.context} ${field.label}`\n );\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","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 \"@icp-sdk/core/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 \"@icp-sdk/core/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 \"@icp-sdk/core/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\ninterface EncodeInflowSubaccountRequest {\n action: SupplyAction;\n principal: Principal;\n}\n\nexport function encodeInflowSubaccount(\n request: EncodeInflowSubaccountRequest\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/** Wallet execution dependencies for borrow and withdraw convenience methods. */\nexport interface WalletExecutionParams {\n /** Chain used by the signing wallet. */\n signerChain: Chain;\n /** Wallet adapter used to execute the prepared action. */\n signerWalletAdapter: WalletAdapter;\n}\n\n/** EVM transaction payload returned by lending transaction builders. */\nexport interface EvmContractTransaction {\n /** Contract address to call. */\n to: string;\n /** Hex-encoded calldata. */\n data: string;\n}\n\n/** Parameters for an ERC-20 transfer transaction. */\nexport interface CreateTransferErc20TransactionParams {\n /** ERC-20 token contract address. */\n tokenAddress: string;\n /** Destination EVM address. */\n recipientAddress: string;\n /** Transfer amount in token base units. */\n amount: bigint;\n}\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/** External-chain destination for a completed outflow. */\nexport interface ExternalOutflowReceiver {\n /** Destination account type reported by the protocol. */\n type: \"External\";\n /** External-chain destination 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: ExternalOutflowReceiver;\n};\n\n/** Withdraw receipt with an external-chain receiver. */\nexport type WithdrawOutflowDetails = OutflowDetails & {\n outflowType: \"withdraw\";\n receiver: ExternalOutflowReceiver;\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. Must match the borrow pool chain. */\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 /** Unix expiry timestamp in seconds, 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. Must match the pool chain. */\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 /** Unix expiry timestamp in seconds, 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/** Request for an ETH stablecoin deposit address. */\nexport interface GetDepositAddressRequest {\n /** Liquidium profile principal text. */\n profileId: string;\n /** Pool principal text receiving the inflow. */\n poolId: string;\n /** ETH stablecoin asset. */\n asset: string;\n /** Deposit or repayment action for the inflow. */\n action: SupplyAction;\n}\n\n/** Fee estimate for an inflow target, rounded up to the asset's fee unit. */\nexport interface InflowFeeEstimate {\n /** Estimated total fee rounded up 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 \"@icp-sdk/canisters/ledger/icrc\";\nimport { Principal } from \"@icp-sdk/core/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\ninterface ResolveSupplyMechanismParams {\n asset: string;\n chain: string;\n requestedMechanism?: SupplyMechanism;\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(\n params: ResolveSupplyMechanismParams\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: poolPrincipal,\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","/** Minimum borrow amounts in each asset's base units. */\nexport const MIN_BORROW_AMOUNTS_BY_ASSET = {\n BTC: 5_100n, // 5,100 sats = 0.000051 BTC\n USDC: 1_000_000n, // 1 USDC\n USDT: 1_000_000n, // 1 USDT\n} as const;\n\nexport type MinimumBorrowAsset = keyof typeof MIN_BORROW_AMOUNTS_BY_ASSET;\n\nexport interface BorrowAmountMinimumValidationParams {\n amount: bigint;\n asset: string;\n}\n\nexport interface BorrowAmountMinimumValidationError {\n asset: string;\n minimumAmount: bigint;\n message: string;\n}\n\n/**\n * Returns the minimum borrow amount for an asset in base units.\n *\n * Assets without a configured product minimum return `0n`.\n */\nexport function getMinimumBorrowAmount(asset: string): bigint {\n if (!isMinimumBorrowAsset(asset)) {\n return 0n;\n }\n\n return MIN_BORROW_AMOUNTS_BY_ASSET[asset];\n}\n\nexport function getBorrowAmountMinimumValidationError(\n params: BorrowAmountMinimumValidationParams\n): BorrowAmountMinimumValidationError | null {\n const minimumAmount = getMinimumBorrowAmount(params.asset);\n if (minimumAmount <= 0n || params.amount >= minimumAmount) {\n return null;\n }\n\n return {\n asset: params.asset,\n minimumAmount,\n message: formatMinimumBorrowAmountMessage(params.asset, minimumAmount),\n };\n}\n\nexport function formatMinimumBorrowAmountMessage(\n asset: string,\n minimumAmount: bigint\n): string {\n return `Borrow amount must be at least ${minimumAmount} base units for ${asset}`;\n}\n\nfunction isMinimumBorrowAsset(asset: string): asset is MinimumBorrowAsset {\n return Object.hasOwn(MIN_BORROW_AMOUNTS_BY_ASSET, asset);\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 { getBorrowAmountMinimumValidationError } from \"../../core/borrow-minimums\";\nimport { 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 INTERNAL_USD_DECIMAL_PLACES = 8;\nconst PRICE_SCALE_DECIMAL_PLACES = 8;\n\ninterface 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\ninterface CreateLtvCalculationParams {\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}\n\ninterface ComputeUsdInternalFromBaseUnitsParams {\n amountBaseUnits: bigint;\n priceScaled: bigint;\n assetDecimalPlaces: number;\n}\n\ninterface ComputeBaseUnitsFromUsdInternalCeilParams {\n usdInternal: bigint;\n priceScaled: bigint;\n assetDecimalPlaces: number;\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 const borrowAmountError = createBorrowAmountValidationError({\n amount: request.borrowAmount,\n asset: borrowPool.asset,\n });\n if (borrowAmountError) {\n validationErrors.push(borrowAmountError);\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 const borrowAmountError = createBorrowAmountValidationError({\n amount: borrowAmount,\n asset: borrowAsset,\n });\n if (borrowAmountError) {\n validationErrors.push(borrowAmountError);\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(\n params: CreateLtvCalculationParams\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 createBorrowAmountValidationError(params: {\n amount: bigint;\n asset: string;\n}): QuoteValidationError | null {\n if (params.amount <= 0n) {\n return {\n code: QuoteValidationErrorCode.BORROW_AMOUNT_TOO_LOW,\n message: \"Borrow amount must be greater than 0\",\n };\n }\n\n const minimumBorrowAmountError =\n getBorrowAmountMinimumValidationError(params);\n if (!minimumBorrowAmountError) {\n return null;\n }\n\n return {\n code: QuoteValidationErrorCode.BORROW_AMOUNT_TOO_LOW,\n message: minimumBorrowAmountError.message,\n };\n}\n\nfunction computeUsdInternalFromBaseUnits(\n params: ComputeUsdInternalFromBaseUnitsParams\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(\n params: ComputeBaseUnitsFromUsdInternalCeilParams\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 Network as BitcoinAddressNetwork,\n validate as validateBitcoinAddress,\n} from \"bitcoin-address-validation\";\nimport { getAddress, isAddress } from \"viem\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"./errors\";\nimport { Asset, Chain } from \"./types\";\n\nexport type EvmAddress = `0x${string}`;\n\ninterface NormalizeExternalAddressParams {\n address: string;\n asset: string;\n chain: string;\n}\n\nconst BTC_MAINNET_ADDRESS_ERROR = \"Address must be a valid mainnet BTC address\";\nconst EVM_ADDRESS_ERROR = \"Address must be a valid EVM address\";\nconst ADDRESS_CHAIN_MISMATCH_ERROR = \"Address chain must match asset\";\n\nexport function normalizeExternalAddress(\n params: NormalizeExternalAddressParams\n): string {\n if (params.asset === Asset.BTC) {\n if (params.chain !== Chain.BTC) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INVALID_ADDRESS,\n ADDRESS_CHAIN_MISMATCH_ERROR\n );\n }\n\n if (\n !validateBitcoinAddress(params.address, BitcoinAddressNetwork.mainnet)\n ) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INVALID_ADDRESS,\n BTC_MAINNET_ADDRESS_ERROR\n );\n }\n\n return params.address;\n }\n\n if (isEthStablecoin(params.asset)) {\n if (params.chain !== Chain.ETH) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INVALID_ADDRESS,\n ADDRESS_CHAIN_MISMATCH_ERROR\n );\n }\n\n if (!isAddress(params.address)) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INVALID_ADDRESS,\n EVM_ADDRESS_ERROR\n );\n }\n\n return getAddress(params.address);\n }\n\n return params.address;\n}\n\nexport function 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 isEthStablecoin(asset: string): boolean {\n return asset === Asset.USDC || asset === Asset.USDT;\n}\n","import { normalizeExternalAddress } from \"../../../core/address-validation\";\nimport { Asset, Chain } from \"../../../core/types\";\nimport type { InstantLoanAsset } from \"../types\";\n\nexport function validateInstantLoanBorrowDestination(\n address: string,\n asset: InstantLoanAsset\n): string {\n return normalizeExternalAddress({\n address,\n asset,\n chain: getChainForInstantLoanAsset(asset),\n });\n}\n\nexport function validateInstantLoanRefundDestination(\n address: string,\n asset: InstantLoanAsset\n): string {\n return normalizeExternalAddress({\n address,\n asset,\n chain: getChainForInstantLoanAsset(asset),\n });\n}\n\nfunction getChainForInstantLoanAsset(asset: InstantLoanAsset): string {\n if (asset === Asset.BTC) return Chain.BTC;\n if (asset === Asset.USDC || asset === Asset.USDT) return Chain.ETH;\n\n return asset;\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 * Intended credited collateral amount, in base units.\n *\n * This is used to validate LTV and initialize the loan record before\n * deposit/inflow fees are deducted. For BTC, pass satoshis. For token assets,\n * convert the UI amount using the selected pool's `decimals` value. After\n * creation, use `loan.initialDeposit.amount` as the fee-inclusive transfer\n * amount to send to `loan.initialDeposit.target`.\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 an instant loan by numeric canister id. */\nexport interface InstantLoanGetByIdRequest {\n /** Canister-assigned loan id. */\n loanId: bigint;\n}\n\n/** Lookup request for loading an instant loan by short user-facing reference. */\nexport interface InstantLoanGetByRefRequest {\n /** Short user-facing reference derived from `loanId`. */\n ref: string;\n}\n\n/** Lookup request for loading canonical instant-loan state. */\nexport type InstantLoanGetRequest =\n | InstantLoanGetByIdRequest\n | InstantLoanGetByRefRequest;\n\n/** Collateral leg returned by instant-loan search. */\nexport interface InstantLoanFindCollateral {\n /** Principal text of the collateral pool. */\n poolId: string;\n /** Asset the user deposits as collateral. */\n asset: InstantLoanAsset;\n /** Intended credited collateral amount in base units, before inflow fees. */\n amount: bigint;\n}\n\n/** Borrow leg returned by instant-loan search. */\nexport interface InstantLoanFindBorrow {\n /** Principal text of the borrow pool. */\n poolId: string;\n /** Asset the user borrows. */\n asset: InstantLoanAsset;\n}\n\n/** Lightweight search result for an instant loan match. */\nexport interface InstantLoanFindResult {\n /** Canister-assigned loan id. Use this with `client.instantLoans.get({ loanId })` to load full loan state. */\n loanId: bigint;\n /** Short user-facing reference derived from `loanId`. */\n ref: string;\n /** Unix creation timestamp in seconds. */\n createdAt: bigint;\n /** Collateral-side pool, asset, and requested credited amount. */\n collateral: InstantLoanFindCollateral;\n /** Borrow-side pool and asset. */\n borrow: InstantLoanFindBorrow;\n /** Generated profile principal from the search index. */\n profileId: string;\n}\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 /** Unix creation timestamp in seconds. */\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 /** Unix event timestamp in seconds. */\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/** Loan-created instant-loan event payload. */\nexport interface InstantLoanCreatedEventType {\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/** Full collateral withdrawal request event payload. */\nexport interface InstantLoanFullLendWithdrawalRequestedEventType {\n type: \"FullLendWithdrawalRequested\";\n loanId: bigint;\n account: InstantLoanAccount;\n poolId: string;\n}\n\n/** Borrow request event payload. */\nexport interface InstantLoanBorrowRequestedEventType {\n type: \"BorrowRequested\";\n loanId: bigint;\n account: InstantLoanAccount;\n poolId: string;\n amount: bigint;\n}\n\n/** Deposit timer exceeded event payload. */\nexport interface InstantLoanDepositTimerExceededEventType {\n type: \"DepositTimerExceeded\";\n loanId: bigint;\n}\n\n/** Stuck funds withdrawal request event payload. */\nexport interface InstantLoanStuckFundsWithdrawalRequestedEventType {\n type: \"StuckFundsWithdrawalRequested\";\n leg: InstantLoanLeg;\n loanId: bigint;\n account: InstantLoanAccount;\n poolId: string;\n amount: bigint;\n}\n\n/** Profile-warmed event payload. */\nexport interface InstantLoanProfileWarmedEventType {\n type: \"ProfileWarmed\";\n derivationIndex: Uint8Array;\n warmedProfileId: bigint;\n ethAddress: string;\n profileId: string;\n}\n\n/** Repay-complete event payload. */\nexport interface InstantLoanRepayCompleteEventType {\n type: \"RepayComplete\";\n loanId: bigint;\n profileId: string;\n}\n\n/** Deposit timer started event payload. */\nexport interface InstantLoanDepositTimerStartedEventType {\n type: \"DepositTimerStarted\";\n loanId: bigint;\n /** Unix timestamp in seconds when the deposit timer started. */\n timestamp: bigint;\n}\n\n/** Direct canister event payload returned by instant-loans event queries. */\nexport type InstantLoanEventType =\n | InstantLoanCreatedEventType\n | InstantLoanFullLendWithdrawalRequestedEventType\n | InstantLoanBorrowRequestedEventType\n | InstantLoanDepositTimerExceededEventType\n | InstantLoanStuckFundsWithdrawalRequestedEventType\n | InstantLoanProfileWarmedEventType\n | InstantLoanRepayCompleteEventType\n | InstantLoanDepositTimerStartedEventType;\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/** Initial collateral deposit quote returned when an instant loan is created. */\nexport interface InstantLoanInitialDeposit {\n /** Full amount to send to the deposit target, including the estimated inflow fee. */\n amount: bigint;\n /** Decimal scale for `amount`, `collateralAmount`, and `inflowFeeAmount`. */\n decimals: bigint;\n /** Intended credited collateral amount in base units, before inflow fees. */\n collateralAmount: bigint;\n /** Inflow fee amount in base units added to the transfer amount. */\n inflowFeeAmount: bigint;\n /** Collateral asset to deposit. */\n asset: MarketAsset;\n /** Chain used for the collateral deposit. */\n chain: MarketChain;\n /** Address or ICRC account where the collateral should be sent. */\n target: SupplyTarget;\n /** Unix timestamp in seconds when the collateral deposit was detected, or null before detection. */\n detectedTimestamp: bigint | null;\n /** Unix timestamp in seconds when the collateral deposit window expires, or null before detection when unavailable. */\n expiryTimestamp: bigint | null;\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 expired: \"expired\",\n} as const;\nexport type InstantLoanStatus =\n (typeof InstantLoanStatus)[keyof typeof InstantLoanStatus];\n\n/** Immutable terms selected for an instant loan. */\nexport interface InstantLoanTerms {\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}\n\n/** Collateral leg selected for an instant loan. */\nexport interface InstantLoanCollateral {\n /** Principal text of the collateral pool. */\n poolId: string;\n /** Collateral asset symbol. */\n asset: MarketAsset;\n /** Chain used for collateral deposits. */\n chain: MarketChain;\n /** Decimal scale for collateral amounts. */\n decimals: bigint;\n /** Intended credited collateral amount in base units, before inflow fees. */\n amount: bigint;\n}\n\n/** Borrow leg selected for an instant loan. */\nexport interface InstantLoanBorrow {\n /** Principal text of the borrow pool. */\n poolId: string;\n /** Borrow asset symbol. */\n asset: MarketAsset;\n /** Chain used for repayment. */\n chain: MarketChain;\n /** Decimal scale for borrow and debt amounts. */\n decimals: bigint;\n /** Requested borrow amount in base units. */\n amount: bigint;\n /** Destination that receives the borrowed asset. */\n destination: InstantLoanAccount;\n}\n\n/** Hydrated instant-loan state plus generated quote 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 profile principal used by the instant loan. */\n profileId: string;\n /** Immutable loan terms. */\n terms: InstantLoanTerms;\n /** Collateral-side pool, asset, chain, decimals, and requested credited amount. */\n collateral: InstantLoanCollateral;\n /** Borrow-side pool, asset, chain, decimals, requested amount, and destination. */\n borrow: InstantLoanBorrow;\n /** Destination used for collateral refunds or withdrawals. */\n refundDestination: InstantLoanAccount;\n /** Current actionable initial collateral deposit quote. */\n initialDeposit: InstantLoanInitialDeposit;\n /** Current repayment quote. Amount fields are zero when the loan has no debt. */\n repayment: InstantLoanRepayment;\n /** Current lending position state for the generated profile. */\n position: InstantLoanPositionSummary;\n}\n","import type {\n InstantLoanAccountType,\n InstantLoanAuthorisation,\n InstantLoanLeg as InstantLoanCanisterLeg,\n InstantLoansCanisterError,\n WarmedProfile,\n} from \"../../core/canisters/instant-loans/actor\";\nimport {\n createFlexibleInstantLoansActor,\n type DecodedHeadlessLoanEvent,\n type DecodedHeadlessLoanEventType,\n type DecodedInstantLoanCanisterRecord,\n decodeFlexibleHeadlessLoanEvent,\n decodeFlexibleInstantLoanRecord,\n} from \"../../core/canisters/instant-loans/flexible-actor\";\nimport { mapCanisterCallErrorToLiquidiumError } from \"../../core/canisters/lending/error-mappers\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport {\n buildInstantLoanCollateralHintPath,\n buildInstantLoanFindPath,\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 {\n type Asset,\n type Chain,\n Asset as CoreAsset,\n SupplyAction,\n} from \"../../core/types\";\nimport {\n parseApiStringUnion,\n parseIsoApiTimestampToUnixSeconds,\n parseNonEmptyApiString,\n parseUnsignedApiBigint,\n} from \"../../core/utils/api-response-parsers\";\nimport { getAssetNativeDecimals } from \"../../core/utils/asset-decimals\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport { resolveSupplyTarget } from \"../lending/_internal/supply-targets\";\nimport type { LendingModule } from \"../lending/lending\";\nimport { SupplyPlanType, type SupplyTarget } from \"../lending/types\";\nimport type { PositionsModule } from \"../positions\";\nimport type { Position } from \"../positions/types\";\nimport { QuoteModule } from \"../quote\";\nimport { QuoteValidationErrorCode } from \"../quote/types\";\nimport {\n validateInstantLoanBorrowDestination,\n validateInstantLoanRefundDestination,\n} from \"./_internal/address-validation\";\nimport { intFromPublicId, publicIdFromInt } from \"./ref-code\";\nimport type {\n CreateInstantLoanRequest,\n ExternalAccount,\n InstantLoan,\n InstantLoanAccount,\n InstantLoanAsset,\n InstantLoanAuthorization,\n InstantLoanConfig,\n InstantLoanEvent,\n InstantLoanEventType,\n InstantLoanFindBorrow,\n InstantLoanFindCollateral,\n InstantLoanFindResult,\n InstantLoanGetRequest,\n InstantLoanInitialDeposit,\n InstantLoanLeg,\n InstantLoanListEventsRequest,\n InstantLoanStatus as InstantLoanStatusValue,\n InstantLoanWarmedProfile,\n} from \"./types\";\nimport { InstantLoanStatus } 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;\nconst INSTANT_LOAN_FIND_QUERY_MAX_LENGTH = 256;\nconst INSTANT_LOAN_WIRE_CONTEXT = \"instant loan\";\nconst INSTANT_LOAN_ASSETS = [\n CoreAsset.BTC,\n CoreAsset.SOL,\n CoreAsset.USDC,\n CoreAsset.USDT,\n] as const satisfies readonly InstantLoanAsset[];\n\ninterface InstantLoanLtvPolicy {\n ltvBps: bigint;\n minLtvMaxBps: bigint;\n maxLtvMaxBps: bigint;\n}\n\ninterface InstantLoanFindCandidateWire {\n loan_id: string;\n short_ref: string;\n created_at: string;\n lend_asset: string;\n borrow_asset: string;\n collateral_amount: string;\n lend_pool_ic_id: string;\n borrow_pool_ic_id: string;\n profile: string;\n}\n\ninterface InstantLoanFindCandidate {\n loanId: bigint;\n ref: string;\n createdAt: bigint;\n collateral: InstantLoanFindCollateral;\n borrow: InstantLoanFindBorrow;\n profileId: string;\n}\n\ninterface 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\ninterface InstantLoanCollateralHintWire {\n collateralAmountHint: string;\n}\n\ninterface InstantLoanFindResponseWire {\n success?: true;\n loans?: InstantLoanFindCandidateWire[];\n candidates?: InstantLoanFindCandidateWire[];\n}\n\ninterface InstantLoanCollateralHintResponseWire\n extends InstantLoanCollateralHintWire {\n success?: true;\n}\n\ninterface InstantLoanCreateAccountWire {\n External: string;\n}\n\ninterface InstantLoanWireCollateral {\n amountHint: string;\n}\n\ninterface InstantLoanWire {\n loanId: string;\n collateral: InstantLoanWireCollateral;\n}\n\ninterface InstantLoanHydrationInput {\n loanId: bigint;\n profileId: string;\n ltvMaxBps: bigint;\n depositWindowSeconds: bigint;\n collateralPoolId: string;\n collateralAmount: bigint;\n borrowPoolId: string;\n collateralAsset: string;\n borrowAsset: string;\n borrowAmount: bigint;\n borrowDestination: InstantLoanAccount;\n refundDestination: InstantLoanAccount;\n depositDetectedTimestamp: bigint | null;\n expiryTimestamp: bigint | null;\n}\n\ninterface InstantLoanInitialDepositQuoteInput {\n collateralAmount: bigint;\n decimals: bigint;\n asset: string;\n target: SupplyTarget;\n detectedTimestamp: bigint | null;\n expiryTimestamp: bigint | null;\n}\n\ninterface RepaymentInflowFeeEstimate {\n totalFee: bigint;\n estimateAvailable: boolean;\n}\n\ninterface DeriveInstantLoanStatusInput {\n collateralAmount: bigint;\n totalDebtAmount: bigint;\n}\n\ninterface DeriveDepositExpiryTimestampInput {\n depositDetectedTimestamp: bigint | null;\n depositWindowSeconds: bigint;\n}\n\ninterface LtvCalculationErrorDetails {\n code: QuoteValidationErrorCode;\n message: string;\n}\n\n/** Accountless instant-loan creation, lookup, recovery, and canister query helpers. */\nexport class InstantLoansModule {\n constructor(\n private readonly canisterContext: CanisterContext,\n private readonly apiClient: ApiClient | undefined,\n private readonly lending: LendingModule,\n private readonly positions: PositionsModule\n ) {}\n\n /**\n * Creates a profileless instant loan and returns canonical canister state plus\n * generated initial-deposit and repayment quote targets.\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 initial-deposit and repayment quote targets.\n */\n async create(request: CreateInstantLoanRequest): Promise<InstantLoan> {\n validateCreateRequest(request);\n const borrowDestination = {\n External: validateInstantLoanBorrowDestination(\n addressFromAccountInput(request.borrowDestination),\n request.borrowAsset\n ),\n };\n const refundDestination = {\n External: validateInstantLoanRefundDestination(\n addressFromAccountInput(request.refundDestination),\n request.collateralAsset\n ),\n };\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,\n refundDestination,\n });\n\n const loanId = parseUnsignedApiBigint(response.loan.loanId, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"loan ID\",\n });\n const collateralAmount = parseUnsignedApiBigint(\n response.loan.collateral.amountHint,\n {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"collateral amount\",\n }\n );\n const record = await this.getLoanRecord(loanId);\n\n return await this.mapLoanRecord(record, collateralAmount);\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 initial-deposit and repayment quote targets.\n */\n async get(request: InstantLoanGetRequest): Promise<InstantLoan> {\n const loanId =\n \"loanId\" in request ? request.loanId : decodeRef(request.ref);\n\n const record = await this.getLoanRecord(loanId);\n const collateralAmount = await this.getCollateralAmountHint(loanId);\n\n return await this.mapLoanRecord(record, collateralAmount);\n }\n\n /**\n * Finds instant loans by short reference, numeric loan id string, address, or transaction id.\n *\n * Search returns lightweight matches. Call `get({ loanId })` or `get({ ref })`\n * when the user selects a match and you need hydrated loan state.\n *\n * @param query - Short reference, address, transaction id/hash, or numeric loan id string.\n * @returns Matching loan ids and references from the search index.\n */\n async find(query: string): Promise<InstantLoanFindResult[]> {\n const validatedQuery = validateInstantLoanFindQuery(query);\n const candidates = await this.findCandidateLoansByQuery(validatedQuery);\n\n return uniqueInstantLoanFindCandidates(candidates).map((candidate) => ({\n loanId: candidate.loanId,\n ref: candidate.ref,\n createdAt: candidate.createdAt,\n collateral: candidate.collateral,\n borrow: candidate.borrow,\n profileId: candidate.profileId,\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 createFlexibleInstantLoansActor(\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 createFlexibleInstantLoansActor(\n this.canisterContext\n ).get_event(eventId);\n\n const decoded = event[0]\n ? decodeFlexibleHeadlessLoanEvent(event[0])\n : null;\n\n return decoded ? mapInstantLoanEvent(decoded) : 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 createFlexibleInstantLoansActor(\n this.canisterContext\n ).list_events(request.start, request.limit);\n\n return events\n .map(([, event]) => decodeFlexibleHeadlessLoanEvent(event))\n .filter((event): event is DecodedHeadlessLoanEvent => event !== null)\n .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 createFlexibleInstantLoansActor(\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 createFlexibleInstantLoansActor(\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 createFlexibleInstantLoansActor(\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 private async findCandidateLoansByQuery(\n query: string\n ): Promise<InstantLoanFindCandidate[]> {\n const apiClient = this.requireApi(\"Instant loan find\");\n const response = await apiClient.get<InstantLoanFindResponseWire>(\n buildInstantLoanFindPath({ query })\n );\n\n return (response.candidates ?? response.loans ?? []).map(mapCandidateWire);\n }\n\n private async getLoanRecord(\n loanId: bigint\n ): Promise<DecodedInstantLoanCanisterRecord> {\n try {\n const result = await createFlexibleInstantLoansActor(\n this.canisterContext\n ).get_loan(loanId);\n\n if (\"Err\" in result) {\n throw mapInstantLoansErrorToLiquidiumError(result.Err);\n }\n\n const decoded = decodeFlexibleInstantLoanRecord(result.Ok);\n if (!decoded) {\n throw new LiquidiumError(\n LiquidiumErrorCode.POOL_NOT_FOUND,\n `Instant loan ${loanId.toString()} uses an unsupported asset`\n );\n }\n\n return decoded;\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_loan\", error);\n }\n }\n\n private async mapLoanRecord(\n record: DecodedInstantLoanCanisterRecord,\n collateralAmount: bigint\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 collateralAmount,\n borrowPoolId: record.borrow_pool_id.toText(),\n collateralAsset: record.lend_asset,\n borrowAsset: record.borrow_asset,\n borrowAmount: record.borrow_amount,\n borrowDestination: accountFromCanister(record.borrow_destination),\n refundDestination: accountFromCanister(record.refund_destination),\n depositDetectedTimestamp: record.deposit_detected_ts[0] ?? null,\n expiryTimestamp:\n record.expires_at[0] ??\n deriveDepositExpiryTimestamp({\n depositDetectedTimestamp: record.deposit_detected_ts[0] ?? null,\n depositWindowSeconds: record.ltv_timer_s,\n }),\n });\n }\n\n private async getCollateralAmountHint(loanId: bigint): Promise<bigint> {\n const apiClient = this.requireApi(\"Instant loan collateral hint\");\n const response = await apiClient.get<InstantLoanCollateralHintResponseWire>(\n buildInstantLoanCollateralHintPath({ loanId })\n );\n\n return parseUnsignedApiBigint(response.collateralAmountHint, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"collateral amount\",\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\n const totalDebtAmount = calculateTotalDebtAmount(borrowPosition);\n const interestBufferAmount = calculateInterestBufferAmount(\n borrowPosition,\n borrowPoolRate.borrowRate\n );\n\n const repaymentInflowFee =\n totalDebtAmount > 0n\n ? await this.estimateRepaymentInflowFee(borrowAsset, repayTarget.chain)\n : { totalFee: 0n, estimateAvailable: false };\n\n const repaymentAmount =\n totalDebtAmount + interestBufferAmount + repaymentInflowFee.totalFee;\n\n const currentCollateralAmount = collateralPosition?.deposited ?? 0n;\n\n const collateralAmount = input.collateralAmount;\n const collateralDecimals =\n collateralPosition?.depositedDecimals ??\n getAssetNativeDecimals(collateralAsset);\n const collateralInterestAmount = collateralPosition?.earnedInterest ?? 0n;\n\n const borrowedAmount = borrowPosition?.borrowed ?? 0n;\n const borrowedDecimals =\n borrowPosition?.borrowedDecimals ?? getAssetNativeDecimals(borrowAsset);\n\n const debtInterestAmount = borrowPosition?.debtInterest ?? 0n;\n\n const status = deriveInstantLoanStatus({\n collateralAmount: currentCollateralAmount,\n totalDebtAmount,\n });\n\n const initialDeposit = await this.createInitialDepositQuote({\n collateralAmount,\n decimals: collateralDecimals,\n asset: collateralAsset,\n target: depositTarget,\n detectedTimestamp: input.depositDetectedTimestamp,\n expiryTimestamp: input.expiryTimestamp,\n });\n\n const 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\n return {\n loanId: input.loanId,\n ref: publicIdFromInt(input.loanId),\n status,\n profileId,\n terms: {\n ltvMaxBps: input.ltvMaxBps,\n depositWindowSeconds: input.depositWindowSeconds,\n },\n collateral: {\n poolId: collateralPoolId,\n asset: collateralAsset,\n chain: depositTarget.chain,\n decimals: collateralDecimals,\n amount: collateralAmount,\n },\n borrow: {\n poolId: borrowPoolId,\n asset: borrowAsset,\n chain: repayTarget.chain,\n decimals: borrowedDecimals,\n amount: input.borrowAmount,\n destination: input.borrowDestination,\n },\n refundDestination: input.refundDestination,\n initialDeposit,\n repayment,\n position: {\n collateralAmount: currentCollateralAmount,\n collateralDecimals,\n collateralInterestAmount,\n borrowedAmount,\n borrowedDecimals,\n debtInterestAmount,\n totalDebtAmount,\n },\n };\n }\n\n private async createInitialDepositQuote(\n input: InstantLoanInitialDepositQuoteInput\n ): Promise<InstantLoanInitialDeposit> {\n const inflowFee = await this.lending.estimateInflowFee({\n asset: input.asset as Asset,\n chain: input.target.chain as Chain,\n });\n\n return {\n amount: input.collateralAmount + inflowFee.totalFee,\n decimals: input.decimals,\n collateralAmount: input.collateralAmount,\n inflowFeeAmount: inflowFee.totalFee,\n asset: input.asset,\n chain: input.target.chain,\n target: input.target,\n detectedTimestamp: input.detectedTimestamp,\n expiryTimestamp: input.expiryTimestamp,\n };\n }\n\n private async estimateRepaymentInflowFee(\n asset: string,\n chain: string\n ): Promise<RepaymentInflowFeeEstimate> {\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(\n input: DeriveInstantLoanStatusInput\n): InstantLoanStatusValue {\n if (input.totalDebtAmount > 0n) {\n return InstantLoanStatus.active;\n }\n\n if (input.collateralAmount > 0n) {\n return InstantLoanStatus.depositDetected;\n }\n\n return InstantLoanStatus.awaitingDeposit;\n}\n\nfunction deriveDepositExpiryTimestamp(\n input: DeriveDepositExpiryTimestampInput\n): bigint | null {\n if (input.depositDetectedTimestamp === null) {\n return null;\n }\n\n return input.depositDetectedTimestamp + input.depositWindowSeconds;\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: LtvCalculationErrorDetails | 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 addressFromAccountInput(account: string | ExternalAccount): string {\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 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 mapInstantLoanEvent(\n event: DecodedHeadlessLoanEvent\n): 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: DecodedHeadlessLoanEventType\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: event.lend_asset as InstantLoanAsset,\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: event.borrow_asset as InstantLoanAsset,\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 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 validateInstantLoanFindQuery(query: unknown): string {\n if (typeof query !== \"string\") {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Instant loan find query must be a string\"\n );\n }\n\n const trimmedQuery = query.trim();\n if (!trimmedQuery) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Instant loan find query must be non-empty\"\n );\n }\n if (trimmedQuery.length > INSTANT_LOAN_FIND_QUERY_MAX_LENGTH) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Instant loan find query must be at most ${INSTANT_LOAN_FIND_QUERY_MAX_LENGTH.toString()} characters`\n );\n }\n\n return trimmedQuery;\n}\n\nfunction uniqueInstantLoanFindCandidates(\n candidates: InstantLoanFindCandidate[]\n): InstantLoanFindCandidate[] {\n const candidatesByLoanId = new Map<bigint, InstantLoanFindCandidate>();\n\n for (const candidate of candidates) {\n if (!candidatesByLoanId.has(candidate.loanId)) {\n candidatesByLoanId.set(candidate.loanId, candidate);\n }\n }\n\n return [...candidatesByLoanId.values()];\n}\n\nfunction mapCandidateWire(\n wire: InstantLoanFindCandidateWire\n): InstantLoanFindCandidate {\n return {\n loanId: parseUnsignedApiBigint(wire.loan_id, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"loan ID\",\n }),\n ref: parseNonEmptyApiString(wire.short_ref, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"short reference\",\n }),\n createdAt: parseIsoApiTimestampToUnixSeconds(wire.created_at, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"creation timestamp\",\n }),\n collateral: {\n poolId: parseNonEmptyApiString(wire.lend_pool_ic_id, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"lend pool ID\",\n }),\n asset: parseApiStringUnion(wire.lend_asset, INSTANT_LOAN_ASSETS, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"lend asset\",\n }),\n amount: parseUnsignedApiBigint(wire.collateral_amount, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"collateral amount\",\n }),\n },\n borrow: {\n poolId: parseNonEmptyApiString(wire.borrow_pool_ic_id, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"borrow pool ID\",\n }),\n asset: parseApiStringUnion(wire.borrow_asset, INSTANT_LOAN_ASSETS, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"borrow asset\",\n }),\n },\n profileId: parseNonEmptyApiString(wire.profile, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"profile ID\",\n }),\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 { encodeIcrcAccount } from \"@icp-sdk/canisters/ledger/icrc\";\nimport { Principal } from \"@icp-sdk/core/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\";\nimport type {\n CreateTransferErc20TransactionParams,\n EvmContractTransaction,\n} from \"./types\";\n\n/** Parameters for an ERC-20 approve transaction. */\nexport interface CreateApproveTransactionParams {\n /** ERC-20 token contract address. */\n tokenAddress: string;\n /** Contract address approved to spend tokens. */\n spenderAddress: string;\n /** Approval amount in token base units. */\n amount: bigint;\n}\n\n/** Parameters for an ERC-20 deposit-helper transaction. */\nexport interface CreateDepositErc20TransactionParams {\n /** Deposit helper contract address. */\n depositContractAddress: string;\n /** ERC-20 token contract address. */\n tokenAddress: string;\n /** Deposit amount in token base units. */\n amount: bigint;\n /** Pool principal text receiving the inflow. */\n poolId: string;\n /** Liquidium profile principal text. */\n profileId: string;\n /** Expected ICRC destination account text. */\n destinationAccount: string;\n /** Deposit or repayment action for the inflow. */\n action: SupplyAction;\n}\n\n/** Builds calldata for an ERC-20 `approve(spender, amount)` transaction. */\nexport function createApproveTransaction(\n params: CreateApproveTransactionParams\n): EvmContractTransaction {\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(\n params: CreateTransferErc20TransactionParams\n): EvmContractTransaction {\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(\n params: CreateDepositErc20TransactionParams\n): EvmContractTransaction {\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","import { Actor, type ActorMethod } from \"@icp-sdk/core/agent\";\nimport type { IDL } from \"@icp-sdk/core/candid\";\nimport { CK_CANISTER_IDS } from \"../../config\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { CanisterContext } from \"../../transports/canister-context\";\n\nexport interface CkBtcLedgerActor {\n icrc1_fee: ActorMethod<[], bigint>;\n}\n\nconst idlFactory: IDL.InterfaceFactory = ({ IDL }) =>\n IDL.Service({\n icrc1_fee: IDL.Func([], [IDL.Nat], [\"query\"]),\n });\n\nexport function createCkBtcLedgerActor(\n canisterContext: CanisterContext\n): CkBtcLedgerActor {\n const canisterId = CK_CANISTER_IDS.btcLedger;\n\n if (!canisterId) {\n throw new LiquidiumError(\n LiquidiumErrorCode.SERVICE_UNAVAILABLE,\n \"ckBTC ledger canister ID is not configured\"\n );\n }\n\n return Actor.createActor<CkBtcLedgerActor>(idlFactory, {\n agent: canisterContext.agent,\n canisterId,\n });\n}\n","interface MessageAccount {\n type: \"Native\" | \"External\";\n data: string;\n}\n\ninterface 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 { Asset, Chain } from \"../../../core/types\";\nimport { ceilDivBigint } from \"../../../core/utils/bigint\";\nimport type { EstimateInflowFeeRequest } from \"../types\";\nimport { isEthStablecoin } from \"./supply-targets\";\n\nconst ETH_STABLECOIN_INFLOW_FEE_ROUND_UP_TO_NEAREST_10_CENTS = 100_000n;\nconst BTC_INFLOW_FEE_ROUND_UP_TO_NEAREST_SATS = 500n;\n\n/**\n * Rounds an inflow fee estimate up to the configured unit for its asset.\n *\n * ETH stablecoin fees use 6 decimals, so 100_000 base units is $0.10.\n * BTC fees use sats, so the fee is rounded up to the nearest 500 sats.\n */\nexport function roundInflowFeeEstimate(\n request: EstimateInflowFeeRequest,\n totalFee: bigint\n): bigint {\n if (totalFee <= 0n) {\n return 0n;\n }\n\n if (isEthStablecoin(request.asset, request.chain)) {\n return roundUpToNearest(\n totalFee,\n ETH_STABLECOIN_INFLOW_FEE_ROUND_UP_TO_NEAREST_10_CENTS\n );\n }\n\n if (request.asset === Asset.BTC && request.chain === Chain.BTC) {\n return roundUpToNearest(totalFee, BTC_INFLOW_FEE_ROUND_UP_TO_NEAREST_SATS);\n }\n\n return totalFee;\n}\n\n/** Rounds a positive bigint up to the nearest multiple of the rounding unit. */\nfunction roundUpToNearest(amount: bigint, roundingUnit: bigint): bigint {\n return ceilDivBigint(amount, roundingUnit) * roundingUnit;\n}\n","import type { Principal } from \"@icp-sdk/core/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 interface LendingBtcChainVariant {\n BTC: null;\n}\n\nexport interface LendingEthChainVariant {\n ETH: null;\n}\n\nexport type LendingChainVariant =\n | LendingBtcChainVariant\n | LendingEthChainVariant;\n\nexport interface CanisterNativeOutflowReceiver {\n Native: Principal;\n}\n\nexport interface CanisterExternalOutflowReceiver {\n External: string;\n}\n\nexport type CanisterOutflowReceiver =\n | CanisterNativeOutflowReceiver\n | CanisterExternalOutflowReceiver;\n\nexport interface 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 \"@icp-sdk/core/principal\";\nimport {\n type EvmAddress,\n normalizeAndValidateEvmAddress,\n normalizeExternalAddress,\n} from \"../../core/address-validation\";\nimport { getBorrowAmountMinimumValidationError } from \"../../core/borrow-minimums\";\nimport { createCkBtcLedgerActor } from \"../../core/canisters/ckbtc/ledger\";\nimport { createCkBtcMinterActor } from \"../../core/canisters/ckbtc/minter\";\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 { normalizeWalletSignature } from \"../../core/utils/signature\";\nimport { computeExpiryTimestampFromNow } from \"../../core/utils/time\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport {\n type EthTransactionRequest,\n TransferMode,\n WalletActionKind,\n type WalletAdapter,\n WalletExecutionKind,\n} from \"../../core/wallet-actions\";\nimport { executeWith } from \"../../execute\";\nimport { roundInflowFeeEstimate } from \"./_internal/inflow-fee-rounding\";\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 GetDepositAddressRequest,\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 WalletExecutionParams,\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 SubmitInflowDefaults = Omit<SubmitInflowRequest, \"txid\">;\n\ninterface OutflowRequestData {\n profileId: string;\n poolId: string;\n amount: bigint;\n receiverAddress: string;\n signerWalletAddress: string;\n expiryTimestamp: bigint;\n}\n\ninterface SupplyInstruction {\n poolId: string;\n asset: string;\n chain: string;\n action: SupplyAction;\n target: SupplyTarget;\n}\n\ninterface GetEvmSupplyContextForPoolParams {\n request: GetEvmSupplyContextRequest;\n asset: string;\n chain: string;\n}\n\ninterface SendAndSubmitNativeSupplyInflowParams {\n request: SupplyFlowRequest;\n instruction: SupplyInstruction;\n defaultSubmitInflowRequest?: SubmitInflowDefaults;\n}\n\ninterface SubmitSupplyFlowInflowParams {\n instruction: SupplyInstruction;\n mechanism: SupplyPlanType;\n defaultSubmitInflowRequest?: SubmitInflowDefaults;\n submitRequest: SubmitInflowRequest;\n}\n\ninterface ExecuteContractSupplyParams {\n request: SupplyFlowRequest;\n instruction: SupplyInstruction;\n defaultSubmitInflowRequest?: SubmitInflowDefaults;\n}\n\ninterface SendNativeSupplyTransactionParams {\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}\n\ninterface NormalizeOutflowReceiverAddressParams {\n poolId: string;\n receiverAddress: string;\n}\n\ninterface WaitForExpectedAllowanceParams {\n walletAddress: string;\n tokenAddress: string;\n spenderAddress: string;\n amount: bigint;\n expectation: AllowanceExpectation;\n}\n\ninterface ReadErc20AllowanceParams {\n evmReadClient: EvmReadClient;\n tokenAddress: string;\n ownerAddress: string;\n spenderAddress: string;\n}\n\ninterface ReadErc20BalanceParams {\n evmReadClient: EvmReadClient;\n tokenAddress: string;\n ownerAddress: string;\n}\n\ninterface ApprovalStrategyParams {\n allowance: bigint;\n amount: bigint;\n}\n\ninterface DefaultSubmitInflowRequestParams {\n action: SupplyAction;\n chain: string;\n}\n\ninterface ShouldSubmitInflowParams {\n instruction: SupplyInstruction;\n mechanism: SupplyPlanType;\n}\n\ntype AllowanceExpectation = \"zero\" | \"sufficient\";\n\n/** Borrow, withdraw, supply, inflow reporting, and fee-estimation helpers. */\nexport class LendingModule {\n constructor(\n private readonly canisterContext: CanisterContext,\n private readonly apiClient: ApiClient | undefined,\n private 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 const receiverAddress = await this.normalizeOutflowReceiverAddress({\n poolId: request.poolId,\n receiverAddress: destinationAccount,\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,\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: receiverAddress },\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: normalizeWalletSignature(\n signatureInfo.signature,\n signatureInfo.chain\n ),\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 if (request.amount <= 0n) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Borrow amount must be greater than 0\"\n );\n }\n const selectedPool = await this.getPoolById(request.poolId);\n const selectedAsset = getVariantKey(selectedPool.asset);\n const minimumBorrowAmountError = getBorrowAmountMinimumValidationError({\n amount: request.amount,\n asset: selectedAsset,\n });\n if (minimumBorrowAmountError) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n minimumBorrowAmountError.message\n );\n }\n const receiverAddress = normalizeExternalAddress({\n address: destinationAccount,\n asset: selectedAsset,\n chain: getVariantKey(selectedPool.chain),\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,\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: receiverAddress },\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: normalizeWalletSignature(\n signatureInfo.signature,\n signatureInfo.chain\n ),\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(\n params: GetEvmSupplyContextForPoolParams\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: GetDepositAddressRequest): 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 include the ckBTC minter deposit fee and ledger fee.\n *\n * @param request - Asset and chain pair to estimate for.\n * @returns Total fee estimate rounded up 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 {\n totalFee: roundInflowFeeEstimate(request, result.Ok),\n };\n }\n\n if (request.asset === Asset.BTC && request.chain === Chain.BTC) {\n const estimate = await this.estimateBtcInflowFee();\n return {\n totalFee: roundInflowFeeEstimate(request, estimate.totalFee),\n };\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 estimateBtcInflowFee(): Promise<InflowFeeEstimate> {\n const [minterFee, ledgerFee] = await Promise.all([\n createCkBtcMinterActor(this.canisterContext).get_deposit_fee(),\n createCkBtcLedgerActor(this.canisterContext).icrc1_fee(),\n ]);\n\n return { totalFee: minterFee + ledgerFee };\n }\n\n private async sendAndSubmitNativeSupplyInflow(\n params: SendAndSubmitNativeSupplyInflowParams\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(\n params: SubmitSupplyFlowInflowParams\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(\n params: ExecuteContractSupplyParams\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(\n params: SendNativeSupplyTransactionParams\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?: SubmitInflowDefaults\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 normalizeOutflowReceiverAddress(\n params: NormalizeOutflowReceiverAddressParams\n ): Promise<string> {\n const selectedPool = await this.getPoolById(params.poolId);\n\n return normalizeExternalAddress({\n address: params.receiverAddress,\n asset: getVariantKey(selectedPool.asset),\n chain: getVariantKey(selectedPool.chain),\n });\n }\n\n private async sendEthContractTransaction(\n walletAdapter: Pick<WalletAdapter, \"sendEthTransaction\">,\n walletAddress: string,\n request: EthTransactionRequest,\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(\n params: WaitForExpectedAllowanceParams\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(\n params: ReadErc20AllowanceParams\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(\n params: ReadErc20BalanceParams\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(\n params: ApprovalStrategyParams\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 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(\n params: DefaultSubmitInflowRequestParams\n): SubmitInflowDefaults | 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: ShouldSubmitInflowParams): boolean {\n if (params.mechanism !== SupplyPlanType.transfer) {\n return true;\n }\n\n return !isEthStablecoin(params.instruction.asset, params.instruction.chain);\n}\n","import { Actor } from \"@icp-sdk/core/agent\";\nimport type { IDL } from \"@icp-sdk/core/candid\";\nimport type { Principal } from \"@icp-sdk/core/principal\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { CanisterContext } from \"../../transports/canister-context\";\nimport {\n extractVariantTag,\n KNOWN_ASSET_TAGS,\n KNOWN_CHAIN_TAGS,\n} from \"../../utils/variant-tags\";\n\nconst flexibleLendingIdlFactory: IDL.InterfaceFactory = ({ IDL }) => {\n const PoolRecord = IDL.Record({\n principal: IDL.Principal,\n asset: IDL.Unknown,\n chain: IDL.Unknown,\n total_supply_at_last_sync: IDL.Nat,\n total_debt_at_last_sync: IDL.Nat,\n supply_cap: IDL.Opt(IDL.Nat),\n borrow_cap: IDL.Opt(IDL.Nat),\n max_ltv: IDL.Nat64,\n liquidation_threshold: IDL.Nat64,\n liquidation_bonus: IDL.Nat64,\n protocol_liquidation_fee: IDL.Nat64,\n reserve_factor: IDL.Nat64,\n base_rate: IDL.Nat,\n optimal_utilization_rate: IDL.Nat,\n rate_slope_before: IDL.Nat,\n rate_slope_after: IDL.Nat,\n lending_index: IDL.Nat,\n borrow_index: IDL.Nat,\n same_asset_borrowing: IDL.Opt(IDL.Bool),\n frozen: IDL.Bool,\n last_updated: IDL.Opt(IDL.Nat64),\n });\n\n const BorrowingPowerRecord = IDL.Record({\n max_borrowable_usd: IDL.Nat,\n weighted_max_ltv: IDL.Nat,\n });\n\n const PositionRecord = IDL.Record({\n asset: IDL.Unknown,\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\n const UserStatsRecord = IDL.Record({\n debt: IDL.Nat,\n collateral: IDL.Nat,\n acumulated_interest: IDL.Nat,\n borrowing_power: BorrowingPowerRecord,\n positions: IDL.Vec(PositionRecord),\n weighted_liquidation_threshold: IDL.Nat,\n });\n\n const PositionViewRecord = IDL.Record({\n lending_index_now: IDL.Nat,\n interest_since_snapshot: IDL.Nat,\n asset: IDL.Unknown,\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\n return IDL.Service({\n list_pools: IDL.Func([], [IDL.Vec(PoolRecord)], [\"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_health_factor: IDL.Func(\n [IDL.Principal],\n [IDL.Nat, UserStatsRecord],\n [\"query\"]\n ),\n get_profile_stats: IDL.Func([IDL.Principal], [UserStatsRecord], [\"query\"]),\n get_position: IDL.Func(\n [IDL.Principal, IDL.Principal],\n [IDL.Opt(PositionViewRecord)],\n [\"query\"]\n ),\n });\n};\n\nexport type FlexiblePool = {\n principal: Principal;\n asset: object;\n chain: object;\n total_supply_at_last_sync: bigint;\n total_debt_at_last_sync: bigint;\n supply_cap: [bigint] | [];\n borrow_cap: [bigint] | [];\n max_ltv: bigint;\n liquidation_threshold: bigint;\n liquidation_bonus: bigint;\n protocol_liquidation_fee: bigint;\n reserve_factor: bigint;\n base_rate: bigint;\n optimal_utilization_rate: bigint;\n rate_slope_before: bigint;\n rate_slope_after: bigint;\n lending_index: bigint;\n borrow_index: bigint;\n same_asset_borrowing: [boolean] | [];\n frozen: boolean;\n last_updated: [bigint] | [];\n};\n\nexport type FlexibleBorrowingPower = {\n max_borrowable_usd: bigint;\n weighted_max_ltv: bigint;\n};\n\nexport type FlexiblePosition = {\n asset: object;\n total_debt_interest: bigint;\n borrow_index_snapshot: bigint;\n lending_index_snapshot: bigint;\n debt_scaled: bigint;\n total_earned_interest: bigint;\n deposit_scaled: bigint;\n pool_id: Principal;\n unpaid_debt_interest: bigint;\n last_update: bigint;\n user_profile: Principal;\n};\n\nexport type FlexibleUserStats = {\n debt: bigint;\n collateral: bigint;\n acumulated_interest: bigint;\n borrowing_power: FlexibleBorrowingPower;\n positions: FlexiblePosition[];\n weighted_liquidation_threshold: bigint;\n};\n\nexport type FlexiblePositionView = {\n lending_index_now: bigint;\n interest_since_snapshot: bigint;\n asset: object;\n total_debt_interest: bigint;\n borrow_index_snapshot: bigint;\n debt_native_now: bigint;\n borrow_index_now: bigint;\n lending_index_snapshot: bigint;\n debt_scaled: bigint;\n total_earned_interest: bigint;\n deposit_scaled: bigint;\n earned_since_snapshot: bigint;\n deposited_native_now: bigint;\n pool_id: Principal;\n last_update: bigint;\n user_profile: Principal;\n};\n\nexport interface FlexibleLendingActor {\n list_pools: () => Promise<FlexiblePool[]>;\n get_pool_rate: (\n poolId: Principal\n ) => Promise<[] | [[bigint, bigint, bigint]]>;\n get_health_factor: (\n profileId: Principal\n ) => Promise<[bigint, FlexibleUserStats]>;\n get_profile_stats: (profileId: Principal) => Promise<FlexibleUserStats>;\n get_position: (\n profileId: Principal,\n poolId: Principal\n ) => Promise<[] | [FlexiblePositionView]>;\n}\n\nexport interface DecodedPool {\n principal: Principal;\n asset: string;\n chain: string;\n total_supply_at_last_sync: bigint;\n total_debt_at_last_sync: bigint;\n supply_cap: [bigint] | [];\n borrow_cap: [bigint] | [];\n max_ltv: bigint;\n liquidation_threshold: bigint;\n liquidation_bonus: bigint;\n protocol_liquidation_fee: bigint;\n reserve_factor: bigint;\n base_rate: bigint;\n optimal_utilization_rate: bigint;\n rate_slope_before: bigint;\n rate_slope_after: bigint;\n lending_index: bigint;\n borrow_index: bigint;\n same_asset_borrowing: [boolean] | [];\n frozen: boolean;\n last_updated: [bigint] | [];\n}\n\nexport interface DecodedPosition {\n asset: string;\n total_debt_interest: bigint;\n borrow_index_snapshot: bigint;\n lending_index_snapshot: bigint;\n debt_scaled: bigint;\n total_earned_interest: bigint;\n deposit_scaled: bigint;\n pool_id: Principal;\n unpaid_debt_interest: bigint;\n last_update: bigint;\n user_profile: Principal;\n}\n\nexport interface DecodedUserStats {\n debt: bigint;\n collateral: bigint;\n acumulated_interest: bigint;\n borrowing_power: FlexibleBorrowingPower;\n positions: DecodedPosition[];\n weighted_liquidation_threshold: bigint;\n}\n\nexport interface DecodedPositionView {\n lending_index_now: bigint;\n interest_since_snapshot: bigint;\n asset: string;\n total_debt_interest: bigint;\n borrow_index_snapshot: bigint;\n debt_native_now: bigint;\n borrow_index_now: bigint;\n lending_index_snapshot: bigint;\n debt_scaled: bigint;\n total_earned_interest: bigint;\n deposit_scaled: bigint;\n earned_since_snapshot: bigint;\n deposited_native_now: bigint;\n pool_id: Principal;\n last_update: bigint;\n user_profile: Principal;\n}\n\nexport function createFlexibleLendingActor(\n canisterContext: CanisterContext\n): FlexibleLendingActor {\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(flexibleLendingIdlFactory, {\n agent: canisterContext.agent,\n canisterId,\n }) as FlexibleLendingActor;\n}\n\nexport function decodeFlexiblePool(pool: FlexiblePool): DecodedPool | null {\n const asset = extractVariantTag(pool.asset, KNOWN_ASSET_TAGS);\n const chain = extractVariantTag(pool.chain, KNOWN_CHAIN_TAGS);\n\n if (!asset || !chain) {\n return null;\n }\n\n return {\n principal: pool.principal,\n asset,\n chain,\n total_supply_at_last_sync: pool.total_supply_at_last_sync,\n total_debt_at_last_sync: pool.total_debt_at_last_sync,\n supply_cap: pool.supply_cap,\n borrow_cap: pool.borrow_cap,\n max_ltv: pool.max_ltv,\n liquidation_threshold: pool.liquidation_threshold,\n liquidation_bonus: pool.liquidation_bonus,\n protocol_liquidation_fee: pool.protocol_liquidation_fee,\n reserve_factor: pool.reserve_factor,\n base_rate: pool.base_rate,\n optimal_utilization_rate: pool.optimal_utilization_rate,\n rate_slope_before: pool.rate_slope_before,\n rate_slope_after: pool.rate_slope_after,\n lending_index: pool.lending_index,\n borrow_index: pool.borrow_index,\n same_asset_borrowing: pool.same_asset_borrowing,\n frozen: pool.frozen,\n last_updated: pool.last_updated,\n };\n}\n\nexport function decodeFlexiblePosition(\n position: FlexiblePosition\n): DecodedPosition | null {\n const asset = extractVariantTag(position.asset, KNOWN_ASSET_TAGS);\n\n if (!asset) {\n return null;\n }\n\n return {\n asset,\n total_debt_interest: position.total_debt_interest,\n borrow_index_snapshot: position.borrow_index_snapshot,\n lending_index_snapshot: position.lending_index_snapshot,\n debt_scaled: position.debt_scaled,\n total_earned_interest: position.total_earned_interest,\n deposit_scaled: position.deposit_scaled,\n pool_id: position.pool_id,\n unpaid_debt_interest: position.unpaid_debt_interest,\n last_update: position.last_update,\n user_profile: position.user_profile,\n };\n}\n\nexport function decodeFlexiblePositionView(\n view: FlexiblePositionView\n): DecodedPositionView | null {\n const asset = extractVariantTag(view.asset, KNOWN_ASSET_TAGS);\n\n if (!asset) {\n return null;\n }\n\n return {\n lending_index_now: view.lending_index_now,\n interest_since_snapshot: view.interest_since_snapshot,\n asset,\n total_debt_interest: view.total_debt_interest,\n borrow_index_snapshot: view.borrow_index_snapshot,\n debt_native_now: view.debt_native_now,\n borrow_index_now: view.borrow_index_now,\n lending_index_snapshot: view.lending_index_snapshot,\n debt_scaled: view.debt_scaled,\n total_earned_interest: view.total_earned_interest,\n deposit_scaled: view.deposit_scaled,\n earned_since_snapshot: view.earned_since_snapshot,\n deposited_native_now: view.deposited_native_now,\n pool_id: view.pool_id,\n last_update: view.last_update,\n user_profile: view.user_profile,\n };\n}\n\nexport function decodeFlexibleUserStats(\n stats: FlexibleUserStats\n): DecodedUserStats {\n return {\n debt: stats.debt,\n collateral: stats.collateral,\n acumulated_interest: stats.acumulated_interest,\n borrowing_power: stats.borrowing_power,\n positions: stats.positions\n .map(decodeFlexiblePosition)\n .filter((position): position is DecodedPosition => position !== null),\n weighted_liquidation_threshold: stats.weighted_liquidation_threshold,\n };\n}\n","import type {\n LendingPoolRecord,\n PoolRateTuple,\n PriceRecord,\n} from \"../../core/canisters/lending/actor\";\nimport type { DecodedPool } from \"../../core/canisters/lending/flexible-actor\";\nimport { RATE_DECIMALS } from \"../../core/rates\";\nimport { getAssetNativeDecimals } from \"../../core/utils/asset-decimals\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport type { AssetPrices, Pool, PoolRate } 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 return mapDecodedPoolToPool(\n {\n ...pool,\n asset: getVariantKey(pool.asset),\n chain: getVariantKey(pool.chain),\n },\n rate\n );\n}\n\nexport function mapDecodedPoolToPool(\n pool: DecodedPool,\n rate: PoolRateTuple\n): Pool {\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: pool.asset,\n chain: pool.chain,\n decimals: getAssetNativeDecimals(pool.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(\n rate: PoolRateTuple\n): PoolRate {\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 \"@icp-sdk/core/principal\";\nimport {\n createLendingActor,\n type PoolRateTuple,\n} from \"../../core/canisters/lending/actor\";\nimport {\n createFlexibleLendingActor,\n type DecodedPool,\n decodeFlexiblePool,\n} from \"../../core/canisters/lending/flexible-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 mapDecodedPoolToPool,\n mapGetPoolRateResponseToPoolRate,\n mapGetPricesResponseToAssetPrices,\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 private readonly canisterContext: CanisterContext,\n private 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 flexibleActor = createFlexibleLendingActor(this.canisterContext);\n const rawPools = await flexibleActor.list_pools();\n\n const decodedPools = rawPools\n .map(decodeFlexiblePool)\n .filter((pool): pool is DecodedPool => pool !== null);\n\n return await Promise.all(\n decodedPools.map(async (pool) => {\n const poolRate = await flexibleActor.get_pool_rate(pool.principal);\n const resolvedPoolRate = poolRate[0] ?? ZERO_POOL_RATE;\n\n return mapDecodedPoolToPool(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 type {\n DecodedPositionView,\n DecodedUserStats,\n} from \"../../core/canisters/lending/flexible-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\ninterface UserStatsLike {\n debt: bigint;\n collateral: bigint;\n weighted_liquidation_threshold: bigint;\n borrowing_power: BorrowingPowerRecord;\n}\n\nexport function mapPositionViewToPosition(view: PositionView): Position {\n return mapDecodedPositionViewToPosition({\n ...view,\n asset: getVariantKey(view.asset),\n });\n}\n\nexport function mapDecodedPositionViewToPosition(\n view: DecodedPositionView\n): Position {\n const nativeDecimals = getAssetNativeDecimals(view.asset);\n\n return {\n poolId: view.pool_id.toText(),\n asset: view.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 mapUserStatsLikeToUserStats(record);\n}\n\nexport function mapDecodedUserStatsToUserStats(\n stats: DecodedUserStats\n): UserStats {\n return mapUserStatsLikeToUserStats(stats);\n}\n\nfunction mapUserStatsLikeToUserStats(stats: UserStatsLike): UserStats {\n return {\n debt: stats.debt,\n debtDecimals: USD_VALUE_SCALE_DECIMALS,\n collateral: stats.collateral,\n collateralDecimals: USD_VALUE_SCALE_DECIMALS,\n weightedLiquidationThreshold: stats.weighted_liquidation_threshold,\n borrowingPower: mapBorrowingPowerRecordToBorrowingPower(\n stats.borrowing_power\n ),\n };\n}\n","import { Principal } from \"@icp-sdk/core/principal\";\nimport { mapCanisterCallErrorToLiquidiumError } from \"../../core/canisters/lending/error-mappers\";\nimport {\n createFlexibleLendingActor,\n decodeFlexiblePositionView,\n decodeFlexibleUserStats,\n} from \"../../core/canisters/lending/flexible-actor\";\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 mapDecodedPositionViewToPosition,\n mapDecodedUserStatsToUserStats,\n USD_VALUE_SCALE_DECIMALS,\n} from \"./mappers\";\nimport type {\n FullWithdrawAmount,\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 private 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 createFlexibleLendingActor(\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 const decodedView = decodeFlexiblePositionView(view);\n if (!decodedView) {\n return null;\n }\n\n return mapDecodedPositionViewToPosition(decodedView);\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 = createFlexibleLendingActor(this.canisterContext);\n const profilePrincipal = Principal.fromText(profileId);\n const stats = await actor.get_profile_stats(profilePrincipal);\n const decodedStats = decodeFlexibleUserStats(stats);\n\n const positionViews = await Promise.all(\n decodedStats.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(decodeFlexiblePositionView)\n .filter((view): view is NonNullable<typeof view> => view !== null)\n .map(mapDecodedPositionViewToPosition);\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 createFlexibleLendingActor(\n this.canisterContext\n ).get_health_factor(Principal.fromText(profileId));\n\n return {\n healthFactor,\n userStats: mapDecodedUserStatsToUserStats(\n decodeFlexibleUserStats(userStatsRecord)\n ),\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 createFlexibleLendingActor(\n this.canisterContext\n ).get_profile_stats(Principal.fromText(profileId));\n\n return mapDecodedUserStatsToUserStats(decodeFlexibleUserStats(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 27 decimals.\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,\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 /**\n * Returns the current full withdraw amount for a position.\n *\n * `Position.deposited` already reflects the current supplied balance at the\n * latest lending index; do not add `earnedInterest` to this amount.\n * Pass `amount` to withdraw calls and use `decimals` for display formatting.\n *\n * @param profileId - The Liquidium profile principal text.\n * @param poolId - The pool principal text.\n * @returns Full withdraw amount in the supplied asset's base units.\n */\n async getFullWithdrawAmount(\n profileId: string,\n poolId: string\n ): Promise<FullWithdrawAmount> {\n const position = await this.getPosition(profileId, poolId);\n if (!position) {\n return { amount: 0n, decimals: 0n };\n }\n\n return { amount: position.deposited, decimals: position.depositedDecimals };\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"]}
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/utils/variant-tags.ts","../src/core/canisters/instant-loans/flexible-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/modules/history/history.ts","../src/core/status.ts","../src/core/utils/api-response-parsers.ts","../src/core/utils/asset-decimals.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/canisters/lending/flexible-actor.ts","../src/core/utils/inflow-subaccount.ts","../src/modules/lending/types.ts","../src/modules/lending/_internal/supply-targets.ts","../src/core/borrow-minimums.ts","../src/modules/quote/types.ts","../src/modules/quote/quote.ts","../src/core/address-validation.ts","../src/modules/instant-loans/_internal/address-validation.ts","../src/modules/instant-loans/instant-loans.ts","../src/modules/lending/evm-transactions.ts","../src/core/canisters/ckbtc/ledger.ts","../src/core/canisters/lending/messages.ts","../src/modules/lending/_internal/inflow-fee-rounding.ts","../src/core/utils/retry.ts","../src/modules/lending/_internal/supply-flow.ts","../src/modules/lending/mappers.ts","../src/modules/lending/lending.ts","../src/core/rates.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","encodeBytesToHex","Actor","MILLISECONDS_PER_SECOND","idlFactory","subaccount","Principal","QuoteValidationErrorCode","QuoteWarningCode","validateBitcoinAddress","BitcoinAddressNetwork","isEthStablecoin","isAddress","getAddress","formatBpsAsPercent","encodeIcrcAccount","normalizeOptionalSubaccount","RATE_SCALE"],"mappings":";;;;;;;;;;;;AAwDO,IAAM,WAAA,GAAc;AAAA,EACzB,OAAA,EAAS;AACX;AAKO,IAAM,KAAA,GAAQ;AAAA,EACnB,GAAA,EAAK,KAAA;AAAA,EACL,GAAA,EAAK,KAAA;AAAA,EACL,IAAA,EAAM,MAAA;AAAA,EACN,IAAA,EAAM;AACR;AAKO,IAAM,KAAA,GAAQ;AAAA,EACnB,GAAA,EAAK,KAAA;AAAA,EACL,GAAA,EAAK;AACP;AAUO,IAAM,YAAA,GAAe;AAAA,EAC1B,OAAA,EAAS,SAAA;AAAA,EACT,SAAA,EAAW;AACb;AAKO,IAAM,WAAA,GAAc;AAAA,EACzB,MAAA,EAAQ,QAAA;AAAA,EACR,QAAA,EAAU,UAAA;AAAA,EACV,UAAA,EAAY;AACd;;;AChGA,IAAM,YAAA,GAAe,oBAAA;AACd,IAAM,oBAAA,GAAuB,kCAAA;AAC7B,IAAM,sBAAmC,WAAA,CAAY,OAAA;AAE5D,IAAM,oBAAA,GAAoC;AAAA,EACxC,OAAA,EAAS,6BAAA;AAAA,EACT,OAAA,EAAS,6BAAA;AAAA,EACT,OAAA,EAAS,6BAAA;AAAA,EACT,UAAA,EAAY,6BAAA;AAAA,EACZ,YAAA,EAAc;AAChB,CAAA;AAEA,IAAM,2BAAA,GAAgE;AAAA,EACpE,OAAA,EAAS;AACX,CAAA;AAEO,SAAS,YAAY,QAAA,EAA2B;AACrD,EAAA,OAAO,QAAA,IAAY,YAAA;AACrB;AAGO,SAAS,kBAAA,CACd,WAAA,GAA2B,mBAAA,EAC3B,SAAA,EACa;AACb,EAAA,OAAO,EAAE,GAAG,2BAAA,CAA4B,WAAW,CAAA,EAAG,GAA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EA,SAAS,qBACP,MAAA,EAC2B;AAC3B,EAAA,IAAI,OAAO,eAAA,EAAiB;AAC1B,IAAA,OAAO,MAAA,CAAO,eAAA;AAAA,EAChB;AAEA,EAAA,IAAI,CAAC,OAAO,SAAA,EAAW;AACrB,IAAA,OAAO,MAAA;AAAA,EACT;AAEA,EAAA,OAAO,kBAAA,CAAmB;AAAA,IACxB,KAAA,EAAO,OAAA;AAAA,IACP,SAAA,EAAW,IAAA,CAAK,MAAA,CAAO,SAAA,EAAW;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 \"@icp-sdk/core/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 `@icp-sdk/core/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 withdrawal: \"withdrawal\",\n} as const;\n/** Outflow operation reported by the lending canister. */\nexport type OutflowType = (typeof OutflowType)[keyof typeof OutflowType];\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\ninterface CreateApiClientOptions {\n baseUrl: string;\n headers?: Record<string, string>;\n timeoutMs: number;\n fetchFn?: typeof fetch;\n}\n\ninterface SendRequestOptions {\n baseUrl: string;\n fetchFn?: typeof fetch;\n headers?: Record<string, string>;\n timeoutMs: number;\n}\n\ninterface ApiRequest {\n path: string;\n method: typeof HTTP_METHOD_GET | typeof HTTP_METHOD_POST;\n body?: unknown;\n}\n\ninterface ResponseErrorContext {\n traceId?: string;\n requestId?: string;\n}\n\ninterface JsonErrorPayload {\n message?: unknown;\n}\n\nexport function createApiClient(opts: CreateApiClientOptions): 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: SendRequestOptions,\n request: ApiRequest\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 JsonErrorPayload).message;\n return typeof message === \"string\" && message.length > 0 ? message : null;\n}\n\nfunction getResponseErrorContext(response: Response): ResponseErrorContext {\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: ResponseErrorContext\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 \"@icp-sdk/core/agent\";\nimport { HttpAgent } from \"@icp-sdk/core/agent\";\nimport { resolveHost } from \"../config\";\nimport type { CanisterIds } from \"../types\";\n\nexport interface CanisterContext {\n agent: HttpAgent;\n canisterIds: CanisterIds;\n}\n\ninterface CreateCanisterContextOptions {\n icHost?: string;\n identity?: Identity;\n canisterIds: CanisterIds;\n}\n\nexport function createCanisterContext(\n opts: CreateCanisterContextOptions\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 'ICP' : 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 IcrcAccount = IDL.Record({\n 'owner' : IDL.Principal,\n 'subaccount' : IDL.Opt(IDL.Vec(IDL.Nat8)),\n });\n const AccountType = IDL.Variant({\n 'Icrc' : IcrcAccount,\n 'Native' : IDL.Principal,\n 'AccountIdentifier' : IDL.Text,\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 'ICP' : 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 \"@icp-sdk/core/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\ninterface 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: object): 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; no current SDK flow emits PSBT-signing actions\n */\nexport interface WalletAdapter {\n /** Signs an SDK plaintext message and returns the wallet signature. BTC adapters may return base64 BIP-322 or hex-encoded signature bytes. */\n signMessage?: (request: SignMessageRequest) => Promise<string>;\n /** Reserved for future PSBT-signing flows; no current SDK method calls this. */\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. BTC signatures may be base64 BIP-322 or hex-encoded bytes. */\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/** Request submitted after a BTC PSBT has been signed. */\nexport interface SignPsbtSubmitRequest {\n /** Base64-encoded signed PSBT. */\n signedPsbtBase64: string;\n}\n\n/** Request submitted after an ETH transaction has been sent. */\nexport interface SendEthTransactionSubmitRequest {\n /** EVM transaction hash returned by the wallet. */\n txHash: string;\n}\n\n/** Prepared action that requires message signing before submit. */\nexport interface SignMessageWalletAction<TData, TResult> {\n /** Protocol action kind. */\n kind: WalletActionKind;\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/** Reserved prepared action for future BTC PSBT-signing flows. */\nexport interface SignPsbtWalletAction<TResult> {\n /** Protocol action kind. */\n kind: WalletActionKind;\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: SignPsbtSubmitRequest): 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: WalletActionKind;\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: SendEthTransactionSubmitRequest): 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\ninterface WalletExecutionKindCarrier {\n executionKind?: unknown;\n}\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`: reserved; no current SDK flow emits this action.\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 WalletExecutionKindCarrier).executionKind\n )}`\n );\n }\n };\n}\n","import { base64, base64nopad } from \"@scure/base\";\nimport { bytesToHex as encodeBytesToHex, isHex } from \"viem\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../errors\";\nimport { Chain, type Chain as ChainName } from \"../types\";\n\nconst HEX_PREFIX = \"0x\";\nconst HEX_BYTE_CHAR_LENGTH = 2;\nconst BASE64_PADDING = \"=\";\n\nexport function normalizeWalletSignature(\n signature: string,\n chain: ChainName\n): string {\n switch (chain) {\n case Chain.BTC:\n return normalizeBtcSignature(signature);\n case Chain.ETH:\n return normalizeHexSignature(signature);\n }\n}\n\nexport function normalizeHexSignature(signature: string): string {\n if (!isPrefixedHex(signature)) {\n return signature;\n }\n\n return signature.slice(HEX_PREFIX.length);\n}\n\nfunction normalizeBtcSignature(signature: string): string {\n const signatureWithoutPrefix = signature.startsWith(HEX_PREFIX)\n ? signature.slice(HEX_PREFIX.length)\n : signature;\n\n if (isHexBytes(signatureWithoutPrefix)) {\n return signatureWithoutPrefix;\n }\n\n if (signature.startsWith(HEX_PREFIX)) {\n throw invalidBtcSignatureFormatError();\n }\n\n return bytesToUnprefixedHex(decodeBase64Signature(signature));\n}\n\nfunction isHexBytes(signature: string): boolean {\n return (\n signature.length > 0 &&\n signature.length % HEX_BYTE_CHAR_LENGTH === 0 &&\n isHex(`${HEX_PREFIX}${signature}`)\n );\n}\n\nfunction decodeBase64Signature(signature: string): Uint8Array {\n try {\n const bytes = decodeBase64Bytes(signature);\n\n if (bytes.length === 0) {\n throw invalidBtcSignatureFormatError();\n }\n\n return bytes;\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw invalidBtcSignatureFormatError(error);\n }\n}\n\nfunction bytesToUnprefixedHex(bytes: Uint8Array): string {\n return normalizeHexSignature(encodeBytesToHex(bytes));\n}\n\nfunction isPrefixedHex(signature: string): boolean {\n return signature.length > HEX_PREFIX.length && isHex(signature);\n}\n\nfunction decodeBase64Bytes(signature: string): Uint8Array {\n if (signature.includes(BASE64_PADDING)) {\n return base64.decode(signature);\n }\n\n return base64nopad.decode(signature);\n}\n\nfunction invalidBtcSignatureFormatError(cause?: unknown): LiquidiumError {\n return new LiquidiumError(\n LiquidiumErrorCode.SIGNATURE_ERROR,\n \"BTC signature must be hex or base64-encoded bytes\",\n cause\n );\n}\n","import type { RegisterProfileRequest } from \"../../core/canisters/lending/actor\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport { Chain } from \"../../core/types\";\nimport { normalizeWalletSignature } from \"../../core/utils/signature\";\nimport type { CreateAccountRequest } from \"./types\";\n\ninterface AccountBtcChainVariant {\n BTC: null;\n}\n\ninterface AccountEthChainVariant {\n ETH: null;\n}\n\ntype AccountChainVariant = AccountBtcChainVariant | AccountEthChainVariant;\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: normalizeWalletSignature(\n request.signatureInfo.signature,\n request.signatureInfo.chain\n ),\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 \"@icp-sdk/core/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 WalletExecutionKind,\n} from \"../../core/wallet-actions\";\nimport { executeWith } from \"../../execute\";\nimport { mapCreateAccountRequestToRegisterProfileRequest } from \"./mappers\";\nimport type {\n CreateAccountAction,\n CreateAccountRequest,\n CreateProfileParams,\n PrepareCreateProfileOptions,\n} from \"./types\";\n\n/** Profile lifecycle and linked-wallet helpers. */\nexport class AccountsModule {\n constructor(private 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 { idlLabelToId } from \"@icp-sdk/core/candid\";\n\n// Asset and chain tags supported by this SDK version. Unknown tags returned by\n// the canister are ignored rather than causing the whole call to fail.\nexport const KNOWN_ASSET_TAGS = [\"BTC\", \"USDC\", \"USDT\"] as const;\nexport const KNOWN_CHAIN_TAGS = [\"BTC\", \"ETH\"] as const;\n\nexport type KnownAssetTag = (typeof KNOWN_ASSET_TAGS)[number];\nexport type KnownChainTag = (typeof KNOWN_CHAIN_TAGS)[number];\n\nexport function extractVariantTag(\n variant: object,\n knownTags: readonly string[]\n): string | null {\n const [key] = Object.keys(variant);\n\n if (!key) {\n return null;\n }\n\n // Known variants decoded by a matching IDL already use the tag name.\n if (knownTags.includes(key)) {\n return key;\n }\n\n // IDL.Unknown returns variants with hashed field names: _${hash}_\n const hashMatch = /^_(\\d+)_$/.exec(key);\n if (!hashMatch) {\n return null;\n }\n\n const hash = Number(hashMatch[1]);\n\n for (const tag of knownTags) {\n if (idlLabelToId(tag) === hash) {\n return tag;\n }\n }\n\n return null;\n}\n","import type { ActorMethod } from \"@icp-sdk/core/agent\";\nimport { Actor } from \"@icp-sdk/core/agent\";\nimport type { IDL } from \"@icp-sdk/core/candid\";\nimport type { Principal } from \"@icp-sdk/core/principal\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { CanisterContext } from \"../../transports/canister-context\";\nimport { extractVariantTag, KNOWN_ASSET_TAGS } from \"../../utils/variant-tags\";\nimport type {\n CreateInstantLoanCanisterRequest,\n HeadlessLoanCreatedEventPayload,\n HeadlessLoanEventType,\n HeadlessLoansConfig,\n InstantLoanAccountType,\n InstantLoanAuthorisation,\n InstantLoansCanisterError,\n WarmedProfile,\n} from \"./actor\";\n\ninterface FlexibleInstantLoanAccountIdentifierAccountType {\n AccountIdentifier: string;\n}\n\ninterface FlexibleInstantLoanIcrcAccount {\n owner: Principal;\n subaccount: [] | [Uint8Array];\n}\n\ninterface FlexibleInstantLoanIcrcAccountType {\n Icrc: FlexibleInstantLoanIcrcAccount;\n}\n\ntype FlexibleInstantLoanAccountType =\n | InstantLoanAccountType\n | FlexibleInstantLoanAccountIdentifierAccountType\n | FlexibleInstantLoanIcrcAccountType;\n\nexport interface FlexibleCreateInstantLoanCanisterResponse {\n loan_id: bigint;\n lending_profile: Principal;\n}\n\nexport interface FlexibleHeadlessLoanCreatedEventPayload {\n loan_id: bigint;\n borrow_destination: FlexibleInstantLoanAccountType;\n lend_asset: object;\n borrow_amount: bigint;\n lend_pool_id: Principal;\n refund_destination: FlexibleInstantLoanAccountType;\n ltv_max_bps: bigint;\n ltv_timer_s: bigint;\n lending_profile: Principal;\n borrow_pool_id: Principal;\n borrow_asset: object;\n}\n\nexport interface FlexibleHeadlessLoanCreatedEventType {\n LoanCreated: FlexibleHeadlessLoanCreatedEventPayload;\n}\n\nexport type FlexibleHeadlessLoanEventType =\n | FlexibleHeadlessLoanCreatedEventType\n | HeadlessLoanEventTypeWithoutAssets;\n\ntype HeadlessLoanEventTypeWithoutAssets = Exclude<\n HeadlessLoanEventType,\n { LoanCreated: HeadlessLoanCreatedEventPayload }\n>;\n\nexport interface FlexibleHeadlessLoanEvent {\n id: bigint;\n schema_version: number;\n timestamp: bigint;\n event_type: FlexibleHeadlessLoanEventType;\n}\n\nexport interface FlexibleInstantLoanCanisterRecord {\n id: bigint;\n authorisation: InstantLoanAuthorisation;\n borrow_destination: FlexibleInstantLoanAccountType;\n started: boolean;\n lend_asset: object;\n created_at: bigint;\n schema_version: number;\n borrow_amount: bigint;\n lend_pool_id: Principal;\n refund_destination: FlexibleInstantLoanAccountType;\n ltv_max_bps: bigint;\n ltv_timer_s: bigint;\n lending_profile: Principal;\n borrow_pool_id: Principal;\n borrow_asset: object;\n expires_at: [] | [bigint];\n deposit_detected_ts: [] | [bigint];\n}\n\nexport interface DecodedHeadlessLoanCreatedEventPayload {\n loan_id: bigint;\n borrow_destination: FlexibleInstantLoanAccountType;\n lend_asset: string;\n borrow_amount: bigint;\n lend_pool_id: Principal;\n refund_destination: FlexibleInstantLoanAccountType;\n ltv_max_bps: bigint;\n ltv_timer_s: bigint;\n lending_profile: Principal;\n borrow_pool_id: Principal;\n borrow_asset: string;\n}\n\nexport type DecodedHeadlessLoanEventType =\n | { LoanCreated: DecodedHeadlessLoanCreatedEventPayload }\n | HeadlessLoanEventTypeWithoutAssets;\n\nexport interface DecodedHeadlessLoanEvent {\n id: bigint;\n schema_version: number;\n timestamp: bigint;\n event_type: DecodedHeadlessLoanEventType;\n}\n\nexport interface DecodedInstantLoanCanisterRecord {\n id: bigint;\n authorisation: InstantLoanAuthorisation;\n borrow_destination: FlexibleInstantLoanAccountType;\n started: boolean;\n lend_asset: string;\n created_at: bigint;\n schema_version: number;\n borrow_amount: bigint;\n lend_pool_id: Principal;\n refund_destination: FlexibleInstantLoanAccountType;\n ltv_max_bps: bigint;\n ltv_timer_s: bigint;\n lending_profile: Principal;\n borrow_pool_id: Principal;\n borrow_asset: string;\n expires_at: [] | [bigint];\n deposit_detected_ts: [] | [bigint];\n}\n\ntype FlexibleResult<T> = { Ok: T } | { Err: InstantLoansCanisterError };\n\nexport interface FlexibleInstantLoansActor {\n create_loan: ActorMethod<\n [CreateInstantLoanCanisterRequest],\n FlexibleResult<FlexibleCreateInstantLoanCanisterResponse>\n >;\n count_warmed_profiles: ActorMethod<[], bigint>;\n get_config: ActorMethod<[], HeadlessLoansConfig>;\n get_event: ActorMethod<[bigint], [] | [FlexibleHeadlessLoanEvent]>;\n get_loan: ActorMethod<\n [bigint],\n FlexibleResult<FlexibleInstantLoanCanisterRecord>\n >;\n list_access_list: ActorMethod<[], Principal[]>;\n list_events: ActorMethod<\n [bigint, bigint],\n Array<[bigint, FlexibleHeadlessLoanEvent]>\n >;\n list_warmed_profiles: ActorMethod<[], WarmedProfile[]>;\n}\n\nconst flexibleInstantLoansIdlFactory: IDL.InterfaceFactory = ({ IDL }) => {\n const IcrcAccount = IDL.Record({\n owner: IDL.Principal,\n subaccount: IDL.Opt(IDL.Vec(IDL.Nat8)),\n });\n const AccountType = IDL.Variant({\n Icrc: IcrcAccount,\n Native: IDL.Principal,\n AccountIdentifier: IDL.Text,\n External: IDL.Text,\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: IDL.Unknown,\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: IDL.Unknown,\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: IDL.Unknown,\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: IDL.Unknown,\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: IDL.Unknown,\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: IDL.Unknown,\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 createFlexibleInstantLoansActor(\n canisterContext: CanisterContext\n): FlexibleInstantLoansActor {\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<FlexibleInstantLoansActor>(\n flexibleInstantLoansIdlFactory,\n {\n agent: canisterContext.agent,\n canisterId,\n }\n );\n}\n\nexport function decodeFlexibleInstantLoanRecord(\n record: FlexibleInstantLoanCanisterRecord\n): DecodedInstantLoanCanisterRecord | null {\n const lend_asset = extractVariantTag(record.lend_asset, KNOWN_ASSET_TAGS);\n const borrow_asset = extractVariantTag(record.borrow_asset, KNOWN_ASSET_TAGS);\n\n if (!lend_asset || !borrow_asset) {\n return null;\n }\n\n return {\n id: record.id,\n authorisation: record.authorisation,\n borrow_destination: record.borrow_destination,\n started: record.started,\n lend_asset,\n created_at: record.created_at,\n schema_version: record.schema_version,\n borrow_amount: record.borrow_amount,\n lend_pool_id: record.lend_pool_id,\n refund_destination: record.refund_destination,\n ltv_max_bps: record.ltv_max_bps,\n ltv_timer_s: record.ltv_timer_s,\n lending_profile: record.lending_profile,\n borrow_pool_id: record.borrow_pool_id,\n borrow_asset,\n expires_at: record.expires_at,\n deposit_detected_ts: record.deposit_detected_ts,\n };\n}\n\nexport function decodeFlexibleHeadlessLoanEvent(\n event: FlexibleHeadlessLoanEvent\n): DecodedHeadlessLoanEvent | null {\n if (\"LoanCreated\" in event.event_type) {\n const decoded = decodeLoanCreatedEvent(event.event_type.LoanCreated);\n\n if (!decoded) {\n return null;\n }\n\n return {\n id: event.id,\n schema_version: event.schema_version,\n timestamp: event.timestamp,\n event_type: decoded,\n };\n }\n\n return {\n id: event.id,\n schema_version: event.schema_version,\n timestamp: event.timestamp,\n event_type: event.event_type as DecodedHeadlessLoanEventType,\n };\n}\n\nfunction decodeLoanCreatedEvent(\n payload: FlexibleHeadlessLoanCreatedEventPayload\n): DecodedHeadlessLoanEventType | null {\n const lend_asset = extractVariantTag(payload.lend_asset, KNOWN_ASSET_TAGS);\n const borrow_asset = extractVariantTag(\n payload.borrow_asset,\n KNOWN_ASSET_TAGS\n );\n\n if (!lend_asset || !borrow_asset) {\n return null;\n }\n\n return {\n LoanCreated: {\n loan_id: payload.loan_id,\n borrow_destination: payload.borrow_destination,\n lend_asset,\n borrow_amount: payload.borrow_amount,\n lend_pool_id: payload.lend_pool_id,\n refund_destination: payload.refund_destination,\n ltv_max_bps: payload.ltv_max_bps,\n ltv_timer_s: payload.ltv_timer_s,\n lending_profile: payload.lending_profile,\n borrow_pool_id: payload.borrow_pool_id,\n borrow_asset,\n },\n };\n}\n","/**\n * Path and query key constants for the Liquidium SDK HTTP API.\n */\n\nconst SDK_API_V1_PATH = \"/v1\";\nconst SDK_API_V2_PATH = \"/v2\";\n\nexport const SdkApiQueryParam = {\n cursor: \"cursor\",\n from: \"from\",\n filter: \"filter\",\n limit: \"limit\",\n market: \"market\",\n operations: \"operations\",\n poolId: \"poolId\",\n profileId: \"profileId\",\n states: \"states\",\n to: \"to\",\n} as const;\n\ninterface BuildActivitiesPathRequest {\n profileId: string;\n filter?: string;\n}\n\ninterface BuildActivityStatusPathRequest {\n profileId: string;\n id: string;\n}\n\ninterface BuildInstantLoanFindPathRequest {\n query: string;\n}\n\ninterface BuildInstantLoanCollateralHintPathRequest {\n loanId: bigint;\n}\n\nconst ACTIVITIES = `${SDK_API_V2_PATH}/activities`;\nconst HISTORY_USERS = `${SDK_API_V2_PATH}/history/users`;\nconst INFLOW = `${SDK_API_V2_PATH}/inflow`;\nconst INSTANT_LOANS = `${SDK_API_V1_PATH}/instant-loans`;\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.filter) {\n query.set(SdkApiQueryParam.filter, request.filter);\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 buildInstantLoanFindPath(\n request: BuildInstantLoanFindPathRequest\n): string {\n const query = new URLSearchParams({ query: request.query });\n return `${INSTANT_LOANS}/find?${query.toString()}`;\n}\n\nexport function buildInstantLoanCollateralHintPath(\n request: BuildInstantLoanCollateralHintPathRequest\n): string {\n return `${INSTANT_LOANS}/${encodeURIComponent(\n request.loanId.toString()\n )}/collateral-hint`;\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 { LiquidiumOperation, LiquidiumStatus } from \"../../core/status\";\nimport type { Chain } from \"../../core/types\";\n\n/** Activity list lifecycle filter. */\nexport const ActivityFilter = {\n active: \"active\",\n completed: \"completed\",\n all: \"all\",\n} as const;\n/** Activity list lifecycle filter. */\nexport type ActivityFilter =\n (typeof ActivityFilter)[keyof typeof ActivityFilter];\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/** Operation emitted by deposit or repayment inflows. */\nexport type InflowActivityOperation = Extract<\n LiquidiumOperation,\n \"deposit\" | \"repayment\"\n>;\n/** Operation emitted by borrow or withdrawal outflows. */\nexport type OutflowActivityOperation = Extract<\n LiquidiumOperation,\n \"borrow\" | \"withdrawal\"\n>;\n\nexport type InflowActivityStatus = LiquidiumStatus & {\n operation: InflowActivityOperation;\n};\nexport type OutflowActivityStatus = LiquidiumStatus & {\n operation: OutflowActivityOperation;\n};\n\ninterface BaseActivity {\n id: string;\n poolId: string;\n asset: string | null;\n chain: Chain | null;\n amount: bigint;\n timestampMs: number;\n /** Chain transaction ids associated with the activity when available. */\n txids?: string[];\n}\n\n/** Deposit or repayment activity returned by the activity API. */\nexport interface InflowActivity extends BaseActivity {\n /** Shared 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 withdrawal activity returned by the activity API. */\nexport interface OutflowActivity extends BaseActivity {\n /** Shared 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/** Shared request fields for listing activities. */\nexport interface BaseListActivitiesRequest {\n /** Optional lifecycle filter; defaults to `active`. */\n filter?: ActivityFilter;\n}\n\n/** Activity list request scoped to a Liquidium profile. */\nexport interface ListActivitiesByProfileRequest\n extends BaseListActivitiesRequest {\n /** Profile principal text to list activities for. */\n profileId: string;\n}\n\n/** Activity list request scoped to an instant-loan short reference. */\nexport interface ListActivitiesByShortRefRequest\n extends BaseListActivitiesRequest {\n /** Instant-loan short reference to list activities for. */\n shortRef: string;\n}\n\n/** Request for listing activities by profile id or instant-loan short reference. */\nexport type ListActivitiesRequest =\n | ListActivitiesByProfileRequest\n | ListActivitiesByShortRefRequest;\n\n/** Shared request fields for an activity status lookup. */\nexport interface BaseGetActivityStatusRequest {\n /** Activity or receipt id to look up. */\n id: string;\n}\n\n/** Activity status lookup scoped to a Liquidium profile. */\nexport interface GetActivityStatusByProfileRequest\n extends BaseGetActivityStatusRequest {\n /** Profile principal text that owns the activity. */\n profileId: string;\n}\n\n/** Activity status lookup scoped to an instant-loan short reference. */\nexport interface GetActivityStatusByShortRefRequest\n extends BaseGetActivityStatusRequest {\n /** Instant-loan short reference that owns the activity. */\n shortRef: string;\n}\n\n/** Request for fetching one activity by id and owner identifier. */\nexport type GetActivityStatusRequest =\n | GetActivityStatusByProfileRequest\n | GetActivityStatusByShortRefRequest;\n\n/** Successful activity status lookup result. */\nexport interface ActivityStatusFoundResponse {\n /** Indicates the activity was found. */\n found: true;\n /** Matched activity. */\n activity: Activity;\n}\n\n/** Missing activity status lookup result. */\nexport interface ActivityStatusNotFoundResponse {\n /** Indicates the activity was not found. */\n found: false;\n /** Requested activity or receipt id. */\n id: string;\n}\n\n/** Result of an activity status lookup. */\nexport type GetActivityStatusResponse =\n | ActivityStatusFoundResponse\n | ActivityStatusNotFoundResponse;\n","import type { InstantLoansCanisterError } from \"../../core/canisters/instant-loans/actor\";\nimport { createFlexibleInstantLoansActor } from \"../../core/canisters/instant-loans/flexible-actor\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport {\n buildActivitiesPath,\n buildActivityStatusPath,\n} from \"../../core/sdk-api-paths\";\nimport type { LiquidiumStatus } from \"../../core/status\";\nimport type { ApiClient } from \"../../core/transports/api-client\";\nimport type { CanisterContext } from \"../../core/transports/canister-context\";\nimport type { Chain } from \"../../core/types\";\nimport { parseBigInt } from \"../../core/utils/bigint\";\nimport { intFromPublicId } from \"../instant-loans/ref-code\";\nimport type {\n Activity,\n ActivityTopUp,\n GetActivityStatusRequest,\n GetActivityStatusResponse,\n InflowActivity,\n InflowActivityStatus,\n ListActivitiesRequest,\n OutflowActivity,\n OutflowActivityStatus,\n} from \"./types\";\nimport { ActivityFilter } from \"./types\";\n\ninterface ActivityTopUpWire\n extends Omit<\n ActivityTopUp,\n \"depositedAmount\" | \"feeAmount\" | \"shortfallAmount\"\n > {\n depositedAmount: string;\n feeAmount: string;\n shortfallAmount: string;\n}\n\ninterface ActivityWire {\n id: string;\n poolId: string;\n asset: string | null;\n chain: Chain | null;\n amount: string;\n timestampMs: number;\n txids?: string[];\n status: LiquidiumStatus;\n topUp?: ActivityTopUpWire;\n}\n\ninterface ListActivitiesResponseWire {\n activities: ActivityWire[];\n}\n\ninterface ActivityStatusFoundResponseWire {\n found: true;\n activity: ActivityWire;\n}\n\ninterface ActivityStatusNotFoundResponseWire {\n found: false;\n id: string;\n}\n\ntype ActivityStatusResponseWire =\n | ActivityStatusFoundResponseWire\n | ActivityStatusNotFoundResponseWire;\n\n/** Receipt-oriented activity list and status helpers. */\nexport class ActivitiesModule {\n constructor(\n private readonly apiClient: ApiClient | undefined,\n private readonly canisterContext: CanisterContext\n ) {}\n\n /**\n * Lists profile activities. Defaults to active activities.\n *\n * Uses the Liquidium SDK API.\n *\n * @param request - Profile id or instant-loan short reference plus optional lifecycle 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 filter: request.filter ?? ActivityFilter.active,\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 createFlexibleInstantLoansActor(\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 = parseBigInt(wire.amount, \"activity amount\");\n const activityBase = {\n id: wire.id,\n poolId: wire.poolId,\n asset: wire.asset,\n chain: wire.chain,\n amount,\n timestampMs: wire.timestampMs,\n };\n\n if (isInflowOperation(wire.status.operation)) {\n const activity: InflowActivity = {\n ...activityBase,\n status: wire.status as InflowActivityStatus,\n };\n\n if (wire.txids) {\n activity.txids = wire.txids;\n }\n\n if (wire.topUp) {\n activity.topUp = mapActivityTopUp(wire.topUp);\n }\n\n return activity;\n }\n\n if (isOutflowOperation(wire.status.operation)) {\n const activity: OutflowActivity = {\n ...activityBase,\n status: wire.status as OutflowActivityStatus,\n };\n\n if (wire.txids) {\n activity.txids = wire.txids;\n }\n\n return activity;\n }\n\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Invalid activity operation: ${wire.status.operation}`\n );\n}\n\nfunction isInflowOperation(operation: LiquidiumStatus[\"operation\"]): boolean {\n return operation === \"deposit\" || operation === \"repayment\";\n}\n\nfunction isOutflowOperation(operation: LiquidiumStatus[\"operation\"]): boolean {\n return operation === \"borrow\" || operation === \"withdrawal\";\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","import { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport {\n buildHistoryUserLiquidationsPath,\n buildHistoryUserTransactionsPath,\n SdkApiQueryParam,\n} from \"../../core/sdk-api-paths\";\nimport type { ApiClient } from \"../../core/transports/api-client\";\nimport { parseBigInt } from \"../../core/utils/bigint\";\nimport type {\n PaginatedResponse,\n UserHistoryResponse,\n UserLiquidationHistoryEntry,\n UserLiquidationHistoryFilters,\n UserTransactionHistoryEntry,\n UserTransactionHistoryFilters,\n} from \"./types\";\n\n/** Historical user transaction and liquidation data helpers. */\nexport class HistoryModule {\n constructor(private 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 transaction history for a user.\n *\n * @param user - The Liquidium profile principal text.\n * @param filters - Optional pool, operation, state, 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 const apiClient = this.requireApi();\n const query = new URLSearchParams();\n\n if (filters.cursor) {\n query.set(SdkApiQueryParam.cursor, filters.cursor);\n }\n if (filters.market) {\n query.set(SdkApiQueryParam.market, filters.market);\n }\n if (filters.poolId) {\n query.set(SdkApiQueryParam.poolId, filters.poolId);\n }\n if (filters.operations?.length) {\n query.set(SdkApiQueryParam.operations, filters.operations.join(\",\"));\n }\n if (filters.states?.length) {\n query.set(\n SdkApiQueryParam.states,\n createHistoryStateFilterParam(filters.states)\n );\n }\n if (filters.from) {\n query.set(SdkApiQueryParam.from, filters.from);\n }\n if (filters.to) {\n query.set(SdkApiQueryParam.to, filters.to);\n }\n if (filters.limit !== undefined) {\n query.set(SdkApiQueryParam.limit, String(filters.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 const apiClient = this.requireApi();\n const query = new URLSearchParams();\n if (filters.cursor) {\n query.set(SdkApiQueryParam.cursor, filters.cursor);\n }\n if (filters.market) {\n query.set(SdkApiQueryParam.market, filters.market);\n }\n if (filters.poolId) {\n query.set(SdkApiQueryParam.poolId, filters.poolId);\n }\n if (filters.from) {\n query.set(SdkApiQueryParam.from, filters.from);\n }\n if (filters.to) {\n query.set(SdkApiQueryParam.to, filters.to);\n }\n if (filters.limit !== undefined) {\n query.set(SdkApiQueryParam.limit, String(filters.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 amount: parseBigInt(item.amount, \"history user amount\"),\n poolId: item.poolId,\n timestamp: item.timestamp,\n status: item.status,\n txids: item.txids,\n };\n}\n\nfunction mapUserLiquidationHistoryEntry(\n item: UserHistoryResponse[\"items\"][number]\n): UserLiquidationHistoryEntry {\n if (\n item.status.operation !== \"liquidation\" ||\n item.status.state !== \"completed\"\n ) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INTERNAL,\n `Invalid liquidation history status: ${item.status.state}`\n );\n }\n\n return {\n id: item.id,\n amount: parseBigInt(item.amount, \"history user amount\"),\n poolId: item.poolId,\n timestamp: item.timestamp,\n status: item.status,\n txids: item.txids,\n };\n}\n\nfunction createHistoryStateFilterParam(states: string[]): string {\n for (const state of states) {\n validateHistoryStateFilter(state);\n }\n\n return [...new Set(states)].join(\",\");\n}\n\nfunction validateHistoryStateFilter(state: string): void {\n switch (state) {\n case \"action_required\":\n case \"confirming\":\n case \"processing\":\n case \"completed\":\n case \"failed\":\n return;\n default:\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `History state filter is not supported: ${state}`\n );\n }\n}\n","/** Lifecycle operation represented by a Liquidium status. */\nexport type LiquidiumOperation =\n | \"deposit\"\n | \"borrow\"\n | \"repayment\"\n | \"withdrawal\"\n | \"liquidation\";\n\n/** Lifecycle state represented by a Liquidium status. */\nexport type LiquidiumState =\n | \"action_required\"\n | \"confirming\"\n | \"processing\"\n | \"active\"\n | \"completed\"\n | \"failed\"\n | \"expired\";\n\n/** Shared lifecycle status returned by SDK methods that expose flow state. */\nexport interface LiquidiumStatus {\n /** Operation currently represented by the status. */\n operation: LiquidiumOperation;\n /** Current lifecycle state for the operation. */\n state: LiquidiumState;\n /** Observed chain confirmations, or null when unavailable or not applicable. */\n confirmations: number | null;\n /** Required confirmations, or null when unavailable or not applicable. */\n requiredConfirmations: number | null;\n}\n\ninterface CreateLiquidiumStatusParams {\n operation: LiquidiumOperation;\n state: LiquidiumState;\n confirmations?: number | null;\n requiredConfirmations?: number | null;\n}\n\nexport function createLiquidiumStatus(\n params: CreateLiquidiumStatusParams\n): LiquidiumStatus {\n return {\n operation: params.operation,\n state: params.state,\n confirmations: params.confirmations ?? null,\n requiredConfirmations: params.requiredConfirmations ?? null,\n };\n}\n","import { LiquidiumError, LiquidiumErrorCode } from \"../errors\";\n\nconst MILLISECONDS_PER_SECOND = 1_000;\n\nexport interface ApiResponseFieldContext {\n context: string;\n label: string;\n}\n\nexport function parseNonEmptyApiString(\n value: string | undefined,\n field: ApiResponseFieldContext\n): string {\n if (!value) {\n throwInvalidApiResponseField(field);\n }\n\n return value;\n}\n\nexport function parseUnsignedApiBigint(\n value: string | undefined,\n field: ApiResponseFieldContext\n): bigint {\n if (!value || !/^\\d+$/.test(value)) {\n throwInvalidApiResponseField(field);\n }\n\n return BigInt(value);\n}\n\nexport function parseIsoApiTimestampToUnixSeconds(\n value: string | undefined,\n field: ApiResponseFieldContext\n): bigint {\n const timestamp = parseNonEmptyApiString(value, field);\n const timestampMilliseconds = Date.parse(timestamp);\n\n if (!Number.isFinite(timestampMilliseconds)) {\n throwInvalidApiResponseField(field);\n }\n\n return BigInt(Math.floor(timestampMilliseconds / MILLISECONDS_PER_SECOND));\n}\n\nexport function parseApiStringUnion<const TValue extends string>(\n value: string | undefined,\n allowedValues: readonly TValue[],\n field: ApiResponseFieldContext\n): TValue {\n if (value !== undefined && allowedValues.includes(value as TValue)) {\n return value as TValue;\n }\n\n throwInvalidApiResponseField(field);\n}\n\nfunction throwInvalidApiResponseField(field: ApiResponseFieldContext): never {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Invalid ${field.context} ${field.label}`\n );\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","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 \"@icp-sdk/core/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 \"@icp-sdk/core/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 { Actor } from \"@icp-sdk/core/agent\";\nimport type { IDL } from \"@icp-sdk/core/candid\";\nimport type { Principal } from \"@icp-sdk/core/principal\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { CanisterContext } from \"../../transports/canister-context\";\nimport {\n extractVariantTag,\n KNOWN_ASSET_TAGS,\n KNOWN_CHAIN_TAGS,\n} from \"../../utils/variant-tags\";\n\nconst flexibleLendingIdlFactory: IDL.InterfaceFactory = ({ IDL }) => {\n const PoolRecord = IDL.Record({\n principal: IDL.Principal,\n asset: IDL.Unknown,\n chain: IDL.Unknown,\n total_supply_at_last_sync: IDL.Nat,\n total_debt_at_last_sync: IDL.Nat,\n supply_cap: IDL.Opt(IDL.Nat),\n borrow_cap: IDL.Opt(IDL.Nat),\n max_ltv: IDL.Nat64,\n liquidation_threshold: IDL.Nat64,\n liquidation_bonus: IDL.Nat64,\n protocol_liquidation_fee: IDL.Nat64,\n reserve_factor: IDL.Nat64,\n base_rate: IDL.Nat,\n optimal_utilization_rate: IDL.Nat,\n rate_slope_before: IDL.Nat,\n rate_slope_after: IDL.Nat,\n lending_index: IDL.Nat,\n borrow_index: IDL.Nat,\n same_asset_borrowing: IDL.Opt(IDL.Bool),\n frozen: IDL.Bool,\n last_updated: IDL.Opt(IDL.Nat64),\n });\n\n const BorrowingPowerRecord = IDL.Record({\n max_borrowable_usd: IDL.Nat,\n weighted_max_ltv: IDL.Nat,\n });\n\n const PositionRecord = IDL.Record({\n asset: IDL.Unknown,\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\n const UserStatsRecord = IDL.Record({\n debt: IDL.Nat,\n collateral: IDL.Nat,\n acumulated_interest: IDL.Nat,\n borrowing_power: BorrowingPowerRecord,\n positions: IDL.Vec(PositionRecord),\n weighted_liquidation_threshold: IDL.Nat,\n });\n\n const PositionViewRecord = IDL.Record({\n lending_index_now: IDL.Nat,\n interest_since_snapshot: IDL.Nat,\n asset: IDL.Unknown,\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\n return IDL.Service({\n list_pools: IDL.Func([], [IDL.Vec(PoolRecord)], [\"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_health_factor: IDL.Func(\n [IDL.Principal],\n [IDL.Nat, UserStatsRecord],\n [\"query\"]\n ),\n get_profile_stats: IDL.Func([IDL.Principal], [UserStatsRecord], [\"query\"]),\n get_position: IDL.Func(\n [IDL.Principal, IDL.Principal],\n [IDL.Opt(PositionViewRecord)],\n [\"query\"]\n ),\n });\n};\n\nexport type FlexiblePool = {\n principal: Principal;\n asset: object;\n chain: object;\n total_supply_at_last_sync: bigint;\n total_debt_at_last_sync: bigint;\n supply_cap: [bigint] | [];\n borrow_cap: [bigint] | [];\n max_ltv: bigint;\n liquidation_threshold: bigint;\n liquidation_bonus: bigint;\n protocol_liquidation_fee: bigint;\n reserve_factor: bigint;\n base_rate: bigint;\n optimal_utilization_rate: bigint;\n rate_slope_before: bigint;\n rate_slope_after: bigint;\n lending_index: bigint;\n borrow_index: bigint;\n same_asset_borrowing: [boolean] | [];\n frozen: boolean;\n last_updated: [bigint] | [];\n};\n\nexport type FlexibleBorrowingPower = {\n max_borrowable_usd: bigint;\n weighted_max_ltv: bigint;\n};\n\nexport type FlexiblePosition = {\n asset: object;\n total_debt_interest: bigint;\n borrow_index_snapshot: bigint;\n lending_index_snapshot: bigint;\n debt_scaled: bigint;\n total_earned_interest: bigint;\n deposit_scaled: bigint;\n pool_id: Principal;\n unpaid_debt_interest: bigint;\n last_update: bigint;\n user_profile: Principal;\n};\n\nexport type FlexibleUserStats = {\n debt: bigint;\n collateral: bigint;\n acumulated_interest: bigint;\n borrowing_power: FlexibleBorrowingPower;\n positions: FlexiblePosition[];\n weighted_liquidation_threshold: bigint;\n};\n\nexport type FlexiblePositionView = {\n lending_index_now: bigint;\n interest_since_snapshot: bigint;\n asset: object;\n total_debt_interest: bigint;\n borrow_index_snapshot: bigint;\n debt_native_now: bigint;\n borrow_index_now: bigint;\n lending_index_snapshot: bigint;\n debt_scaled: bigint;\n total_earned_interest: bigint;\n deposit_scaled: bigint;\n earned_since_snapshot: bigint;\n deposited_native_now: bigint;\n pool_id: Principal;\n last_update: bigint;\n user_profile: Principal;\n};\n\nexport interface FlexibleLendingActor {\n list_pools: () => Promise<FlexiblePool[]>;\n get_pool_rate: (\n poolId: Principal\n ) => Promise<[] | [[bigint, bigint, bigint]]>;\n get_health_factor: (\n profileId: Principal\n ) => Promise<[bigint, FlexibleUserStats]>;\n get_profile_stats: (profileId: Principal) => Promise<FlexibleUserStats>;\n get_position: (\n profileId: Principal,\n poolId: Principal\n ) => Promise<[] | [FlexiblePositionView]>;\n}\n\nexport interface DecodedPool {\n principal: Principal;\n asset: string;\n chain: string;\n total_supply_at_last_sync: bigint;\n total_debt_at_last_sync: bigint;\n supply_cap: [bigint] | [];\n borrow_cap: [bigint] | [];\n max_ltv: bigint;\n liquidation_threshold: bigint;\n liquidation_bonus: bigint;\n protocol_liquidation_fee: bigint;\n reserve_factor: bigint;\n base_rate: bigint;\n optimal_utilization_rate: bigint;\n rate_slope_before: bigint;\n rate_slope_after: bigint;\n lending_index: bigint;\n borrow_index: bigint;\n same_asset_borrowing: [boolean] | [];\n frozen: boolean;\n last_updated: [bigint] | [];\n}\n\nexport interface DecodedPosition {\n asset: string;\n total_debt_interest: bigint;\n borrow_index_snapshot: bigint;\n lending_index_snapshot: bigint;\n debt_scaled: bigint;\n total_earned_interest: bigint;\n deposit_scaled: bigint;\n pool_id: Principal;\n unpaid_debt_interest: bigint;\n last_update: bigint;\n user_profile: Principal;\n}\n\nexport interface DecodedUserStats {\n debt: bigint;\n collateral: bigint;\n acumulated_interest: bigint;\n borrowing_power: FlexibleBorrowingPower;\n positions: DecodedPosition[];\n weighted_liquidation_threshold: bigint;\n}\n\nexport interface DecodedPositionView {\n lending_index_now: bigint;\n interest_since_snapshot: bigint;\n asset: string;\n total_debt_interest: bigint;\n borrow_index_snapshot: bigint;\n debt_native_now: bigint;\n borrow_index_now: bigint;\n lending_index_snapshot: bigint;\n debt_scaled: bigint;\n total_earned_interest: bigint;\n deposit_scaled: bigint;\n earned_since_snapshot: bigint;\n deposited_native_now: bigint;\n pool_id: Principal;\n last_update: bigint;\n user_profile: Principal;\n}\n\nexport function createFlexibleLendingActor(\n canisterContext: CanisterContext\n): FlexibleLendingActor {\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(flexibleLendingIdlFactory, {\n agent: canisterContext.agent,\n canisterId,\n }) as FlexibleLendingActor;\n}\n\nexport function decodeFlexiblePool(pool: FlexiblePool): DecodedPool | null {\n const asset = extractVariantTag(pool.asset, KNOWN_ASSET_TAGS);\n const chain = extractVariantTag(pool.chain, KNOWN_CHAIN_TAGS);\n\n if (!asset || !chain) {\n return null;\n }\n\n return {\n principal: pool.principal,\n asset,\n chain,\n total_supply_at_last_sync: pool.total_supply_at_last_sync,\n total_debt_at_last_sync: pool.total_debt_at_last_sync,\n supply_cap: pool.supply_cap,\n borrow_cap: pool.borrow_cap,\n max_ltv: pool.max_ltv,\n liquidation_threshold: pool.liquidation_threshold,\n liquidation_bonus: pool.liquidation_bonus,\n protocol_liquidation_fee: pool.protocol_liquidation_fee,\n reserve_factor: pool.reserve_factor,\n base_rate: pool.base_rate,\n optimal_utilization_rate: pool.optimal_utilization_rate,\n rate_slope_before: pool.rate_slope_before,\n rate_slope_after: pool.rate_slope_after,\n lending_index: pool.lending_index,\n borrow_index: pool.borrow_index,\n same_asset_borrowing: pool.same_asset_borrowing,\n frozen: pool.frozen,\n last_updated: pool.last_updated,\n };\n}\n\nexport function decodeFlexiblePosition(\n position: FlexiblePosition\n): DecodedPosition | null {\n const asset = extractVariantTag(position.asset, KNOWN_ASSET_TAGS);\n\n if (!asset) {\n return null;\n }\n\n return {\n asset,\n total_debt_interest: position.total_debt_interest,\n borrow_index_snapshot: position.borrow_index_snapshot,\n lending_index_snapshot: position.lending_index_snapshot,\n debt_scaled: position.debt_scaled,\n total_earned_interest: position.total_earned_interest,\n deposit_scaled: position.deposit_scaled,\n pool_id: position.pool_id,\n unpaid_debt_interest: position.unpaid_debt_interest,\n last_update: position.last_update,\n user_profile: position.user_profile,\n };\n}\n\nexport function decodeFlexiblePositionView(\n view: FlexiblePositionView\n): DecodedPositionView | null {\n const asset = extractVariantTag(view.asset, KNOWN_ASSET_TAGS);\n\n if (!asset) {\n return null;\n }\n\n return {\n lending_index_now: view.lending_index_now,\n interest_since_snapshot: view.interest_since_snapshot,\n asset,\n total_debt_interest: view.total_debt_interest,\n borrow_index_snapshot: view.borrow_index_snapshot,\n debt_native_now: view.debt_native_now,\n borrow_index_now: view.borrow_index_now,\n lending_index_snapshot: view.lending_index_snapshot,\n debt_scaled: view.debt_scaled,\n total_earned_interest: view.total_earned_interest,\n deposit_scaled: view.deposit_scaled,\n earned_since_snapshot: view.earned_since_snapshot,\n deposited_native_now: view.deposited_native_now,\n pool_id: view.pool_id,\n last_update: view.last_update,\n user_profile: view.user_profile,\n };\n}\n\nexport function decodeFlexibleUserStats(\n stats: FlexibleUserStats\n): DecodedUserStats {\n return {\n debt: stats.debt,\n collateral: stats.collateral,\n acumulated_interest: stats.acumulated_interest,\n borrowing_power: stats.borrowing_power,\n positions: stats.positions\n .map(decodeFlexiblePosition)\n .filter((position): position is DecodedPosition => position !== null),\n weighted_liquidation_threshold: stats.weighted_liquidation_threshold,\n };\n}\n","import type { Principal } from \"@icp-sdk/core/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\ninterface EncodeInflowSubaccountRequest {\n action: SupplyAction;\n principal: Principal;\n}\n\nexport function encodeInflowSubaccount(\n request: EncodeInflowSubaccountRequest\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 { LiquidiumOperation, LiquidiumStatus } from \"../../core/status\";\nimport type {\n Asset,\n Chain,\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/** Wallet execution dependencies for borrow and withdraw convenience methods. */\nexport interface WalletExecutionParams {\n /** Chain used by the signing wallet. */\n signerChain: Chain;\n /** Wallet adapter used to execute the prepared action. */\n signerWalletAdapter: WalletAdapter;\n}\n\n/** EVM transaction payload returned by lending transaction builders. */\nexport interface EvmContractTransaction {\n /** Contract address to call. */\n to: string;\n /** Hex-encoded calldata. */\n data: string;\n}\n\n/** Parameters for an ERC-20 transfer transaction. */\nexport interface CreateTransferErc20TransactionParams {\n /** ERC-20 token contract address. */\n tokenAddress: string;\n /** Destination EVM address. */\n recipientAddress: string;\n /** Transfer amount in token base units. */\n amount: bigint;\n}\n\n/** Destination account for a completed outflow. */\nexport type OutflowReceiver =\n | NativeOutflowReceiver\n | ExternalOutflowReceiver\n | AccountIdentifierOutflowReceiver\n | IcrcOutflowReceiver;\n\n/** IC principal destination for a completed outflow. */\nexport interface NativeOutflowReceiver {\n /** Destination account type reported by the protocol. */\n type: \"Native\";\n /** Destination principal. */\n account: string;\n}\n\n/** External-chain destination for a completed outflow. */\nexport interface ExternalOutflowReceiver {\n /** Destination account type reported by the protocol. */\n type: \"External\";\n /** External-chain destination address. */\n account: string;\n}\n\n/** Legacy ICP ledger account identifier destination for a completed outflow. */\nexport interface AccountIdentifierOutflowReceiver {\n /** Destination account type reported by the protocol. */\n type: \"AccountIdentifier\";\n /** ICP ledger account identifier text, displayed as the destination address. */\n account: string;\n}\n\n/** ICRC account destination for a completed outflow. */\nexport interface IcrcOutflowReceiver {\n /** Destination account type reported by the protocol. */\n type: \"Icrc\";\n /** ICRC account owner principal text. */\n owner: string;\n /** Optional ICRC subaccount bytes. */\n subaccount?: Uint8Array;\n /** Text-encoded ICRC account for display. */\n account: string;\n}\n\n/**\n * Receipt for a borrow or withdrawal outflow 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, withdrawal, 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. */\nexport type BorrowOutflowDetails = OutflowDetails & {\n outflowType: \"borrow\";\n /** Shared lifecycle status for the borrow outflow receipt. */\n status: LiquidiumStatus;\n};\n\n/** Withdraw receipt. */\nexport type WithdrawOutflowDetails = OutflowDetails & {\n outflowType: \"withdrawal\";\n /** Shared lifecycle status for the withdraw outflow receipt. */\n status: LiquidiumStatus;\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. Must match the borrow pool chain. */\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 /** Unix expiry timestamp in seconds, 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. Must match the pool chain. */\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 /** Unix expiry timestamp in seconds, 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 * - If post-broadcast inflow registration fails after the SDK broadcasts the\n * transaction, `txid` is still returned so callers can track the transaction.\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 /** Shared lifecycle status for the supply flow. */\n status: LiquidiumStatus;\n /** Registers a broadcast transaction id when the flow requires an indexing hint. */\n submit(request: SubmitSupplyFlowInflowRequest): Promise<SubmitInflowResponse>;\n}\n\n/** Canonical inflow operation accepted by direct inflow submission. */\nexport type InflowOperation = Extract<\n LiquidiumOperation,\n \"deposit\" | \"repayment\"\n>;\n\n/** Body for `SupplyFlow.submit`. The supply flow supplies the inflow operation. */\nexport interface SubmitSupplyFlowInflowRequest {\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}\n\n/** Body for direct `lending.submitInflow`. */\nexport interface SubmitInflowRequest extends SubmitSupplyFlowInflowRequest {\n /** Deposit or repayment operation represented by the transaction. */\n operation: InflowOperation;\n}\n\n/** Acknowledgement from the SDK API after submitting an inflow hint. */\nexport interface SubmitInflowResponse {\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/** Request for an ETH stablecoin deposit address. */\nexport interface GetDepositAddressRequest {\n /** Liquidium profile principal text. */\n profileId: string;\n /** Pool principal text receiving the inflow. */\n poolId: string;\n /** ETH stablecoin asset. */\n asset: string;\n /** Deposit or repayment action for the inflow. */\n action: SupplyAction;\n}\n\n/** Fee estimate for an inflow target, rounded up to the asset's fee unit. */\nexport interface InflowFeeEstimate {\n /** Estimated total fee rounded up 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 /** 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 \"@icp-sdk/canisters/ledger/icrc\";\nimport { Principal } from \"@icp-sdk/core/principal\";\nimport { createCkBtcMinterActor } from \"../../../core/canisters/ckbtc/minter\";\nimport {\n createDepositAccountsActor,\n type DepositAccountErrors,\n} from \"../../../core/canisters/deposit-accounts/actor\";\nimport {\n createFlexibleLendingActor,\n type DecodedPool,\n decodeFlexiblePool,\n} from \"../../../core/canisters/lending/flexible-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 {\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\ninterface ResolveSupplyMechanismParams {\n asset: string;\n chain: string;\n requestedMechanism?: SupplyMechanism;\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 = selectedPool.asset;\n const chain = 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(\n params: ResolveSupplyMechanismParams\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<DecodedPool> {\n const pools = await createFlexibleLendingActor(canisterContext).list_pools();\n const selectedPool = pools.find((pool) => pool.principal.toText() === poolId);\n\n const decodedPool = selectedPool ? decodeFlexiblePool(selectedPool) : null;\n if (!decodedPool) {\n throw new LiquidiumError(\n LiquidiumErrorCode.POOL_NOT_FOUND,\n `Pool not found: ${poolId}`\n );\n }\n\n return decodedPool;\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: poolPrincipal,\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","/** Minimum borrow amounts in each asset's base units. */\nexport const MIN_BORROW_AMOUNTS_BY_ASSET = {\n BTC: 5_100n, // 5,100 sats = 0.000051 BTC\n USDC: 1_000_000n, // 1 USDC\n USDT: 1_000_000n, // 1 USDT\n} as const;\n\nexport type MinimumBorrowAsset = keyof typeof MIN_BORROW_AMOUNTS_BY_ASSET;\n\nexport interface BorrowAmountMinimumValidationParams {\n amount: bigint;\n asset: string;\n}\n\nexport interface BorrowAmountMinimumValidationError {\n asset: string;\n minimumAmount: bigint;\n message: string;\n}\n\n/**\n * Returns the minimum borrow amount for an asset in base units.\n *\n * Assets without a configured product minimum return `0n`.\n */\nexport function getMinimumBorrowAmount(asset: string): bigint {\n if (!isMinimumBorrowAsset(asset)) {\n return 0n;\n }\n\n return MIN_BORROW_AMOUNTS_BY_ASSET[asset];\n}\n\nexport function getBorrowAmountMinimumValidationError(\n params: BorrowAmountMinimumValidationParams\n): BorrowAmountMinimumValidationError | null {\n const minimumAmount = getMinimumBorrowAmount(params.asset);\n if (minimumAmount <= 0n || params.amount >= minimumAmount) {\n return null;\n }\n\n return {\n asset: params.asset,\n minimumAmount,\n message: formatMinimumBorrowAmountMessage(params.asset, minimumAmount),\n };\n}\n\nexport function formatMinimumBorrowAmountMessage(\n asset: string,\n minimumAmount: bigint\n): string {\n return `Borrow amount must be at least ${minimumAmount} base units for ${asset}`;\n}\n\nfunction isMinimumBorrowAsset(asset: string): asset is MinimumBorrowAsset {\n return Object.hasOwn(MIN_BORROW_AMOUNTS_BY_ASSET, asset);\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 { getBorrowAmountMinimumValidationError } from \"../../core/borrow-minimums\";\nimport { 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 INTERNAL_USD_DECIMAL_PLACES = 8;\nconst PRICE_SCALE_DECIMAL_PLACES = 8;\n\ninterface 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\ninterface CreateLtvCalculationParams {\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}\n\ninterface ComputeUsdInternalFromBaseUnitsParams {\n amountBaseUnits: bigint;\n priceScaled: bigint;\n assetDecimalPlaces: number;\n}\n\ninterface ComputeBaseUnitsFromUsdInternalCeilParams {\n usdInternal: bigint;\n priceScaled: bigint;\n assetDecimalPlaces: number;\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 const borrowAmountError = createBorrowAmountValidationError({\n amount: request.borrowAmount,\n asset: borrowPool.asset,\n });\n if (borrowAmountError) {\n validationErrors.push(borrowAmountError);\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 const borrowAmountError = createBorrowAmountValidationError({\n amount: borrowAmount,\n asset: borrowAsset,\n });\n if (borrowAmountError) {\n validationErrors.push(borrowAmountError);\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(\n params: CreateLtvCalculationParams\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 createBorrowAmountValidationError(params: {\n amount: bigint;\n asset: string;\n}): QuoteValidationError | null {\n if (params.amount <= 0n) {\n return {\n code: QuoteValidationErrorCode.BORROW_AMOUNT_TOO_LOW,\n message: \"Borrow amount must be greater than 0\",\n };\n }\n\n const minimumBorrowAmountError =\n getBorrowAmountMinimumValidationError(params);\n if (!minimumBorrowAmountError) {\n return null;\n }\n\n return {\n code: QuoteValidationErrorCode.BORROW_AMOUNT_TOO_LOW,\n message: minimumBorrowAmountError.message,\n };\n}\n\nfunction computeUsdInternalFromBaseUnits(\n params: ComputeUsdInternalFromBaseUnitsParams\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(\n params: ComputeBaseUnitsFromUsdInternalCeilParams\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 Network as BitcoinAddressNetwork,\n validate as validateBitcoinAddress,\n} from \"bitcoin-address-validation\";\nimport { getAddress, isAddress } from \"viem\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"./errors\";\nimport { Asset, Chain } from \"./types\";\n\nexport type EvmAddress = `0x${string}`;\n\ninterface NormalizeExternalAddressParams {\n address: string;\n asset: string;\n chain: string;\n}\n\nconst BTC_MAINNET_ADDRESS_ERROR = \"Address must be a valid mainnet BTC address\";\nconst EVM_ADDRESS_ERROR = \"Address must be a valid EVM address\";\nconst ADDRESS_CHAIN_MISMATCH_ERROR = \"Address chain must match asset\";\n\nexport function normalizeExternalAddress(\n params: NormalizeExternalAddressParams\n): string {\n if (params.asset === Asset.BTC) {\n if (params.chain !== Chain.BTC) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INVALID_ADDRESS,\n ADDRESS_CHAIN_MISMATCH_ERROR\n );\n }\n\n if (\n !validateBitcoinAddress(params.address, BitcoinAddressNetwork.mainnet)\n ) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INVALID_ADDRESS,\n BTC_MAINNET_ADDRESS_ERROR\n );\n }\n\n return params.address;\n }\n\n if (isEthStablecoin(params.asset)) {\n if (params.chain !== Chain.ETH) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INVALID_ADDRESS,\n ADDRESS_CHAIN_MISMATCH_ERROR\n );\n }\n\n if (!isAddress(params.address)) {\n throw new LiquidiumError(\n LiquidiumErrorCode.INVALID_ADDRESS,\n EVM_ADDRESS_ERROR\n );\n }\n\n return getAddress(params.address);\n }\n\n return params.address;\n}\n\nexport function 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 isEthStablecoin(asset: string): boolean {\n return asset === Asset.USDC || asset === Asset.USDT;\n}\n","import { normalizeExternalAddress } from \"../../../core/address-validation\";\nimport { Asset, Chain } from \"../../../core/types\";\nimport type { InstantLoanAsset } from \"../types\";\n\nexport function validateInstantLoanBorrowDestination(\n address: string,\n asset: InstantLoanAsset\n): string {\n return normalizeExternalAddress({\n address,\n asset,\n chain: getChainForInstantLoanAsset(asset),\n });\n}\n\nexport function validateInstantLoanRefundDestination(\n address: string,\n asset: InstantLoanAsset\n): string {\n return normalizeExternalAddress({\n address,\n asset,\n chain: getChainForInstantLoanAsset(asset),\n });\n}\n\nfunction getChainForInstantLoanAsset(asset: InstantLoanAsset): string {\n if (asset === Asset.BTC) return Chain.BTC;\n if (asset === Asset.USDC || asset === Asset.USDT) return Chain.ETH;\n\n return asset;\n}\n","import { encodeIcrcAccount } from \"@icp-sdk/canisters/ledger/icrc\";\nimport type {\n InstantLoanAuthorisation,\n InstantLoanLeg as InstantLoanCanisterLeg,\n InstantLoansCanisterError,\n WarmedProfile,\n} from \"../../core/canisters/instant-loans/actor\";\nimport {\n createFlexibleInstantLoansActor,\n type DecodedHeadlessLoanEvent,\n type DecodedHeadlessLoanEventType,\n type DecodedInstantLoanCanisterRecord,\n decodeFlexibleHeadlessLoanEvent,\n decodeFlexibleInstantLoanRecord,\n} from \"../../core/canisters/instant-loans/flexible-actor\";\nimport { mapCanisterCallErrorToLiquidiumError } from \"../../core/canisters/lending/error-mappers\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport {\n buildInstantLoanCollateralHintPath,\n buildInstantLoanFindPath,\n SdkApiPath,\n} from \"../../core/sdk-api-paths\";\nimport { createLiquidiumStatus, type LiquidiumStatus } from \"../../core/status\";\nimport type { ApiClient } from \"../../core/transports/api-client\";\nimport type { CanisterContext } from \"../../core/transports/canister-context\";\nimport {\n type Asset,\n type Chain,\n Asset as CoreAsset,\n SupplyAction,\n} from \"../../core/types\";\nimport {\n parseApiStringUnion,\n parseIsoApiTimestampToUnixSeconds,\n parseNonEmptyApiString,\n parseUnsignedApiBigint,\n} from \"../../core/utils/api-response-parsers\";\nimport { getAssetNativeDecimals } from \"../../core/utils/asset-decimals\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport type { ActivitiesModule, Activity } from \"../activities\";\nimport { ActivityFilter } from \"../activities\";\nimport { resolveSupplyTarget } from \"../lending/_internal/supply-targets\";\nimport type { LendingModule } from \"../lending/lending\";\nimport { SupplyPlanType, type SupplyTarget } from \"../lending/types\";\nimport type { PositionsModule } from \"../positions\";\nimport type { Position } from \"../positions/types\";\nimport { QuoteModule } from \"../quote\";\nimport { QuoteValidationErrorCode } from \"../quote/types\";\nimport {\n validateInstantLoanBorrowDestination,\n validateInstantLoanRefundDestination,\n} from \"./_internal/address-validation\";\nimport { intFromPublicId, publicIdFromInt } from \"./ref-code\";\nimport type {\n CreateInstantLoanRequest,\n ExternalAccount,\n InstantLoan,\n InstantLoanAccount,\n InstantLoanAsset,\n InstantLoanAuthorization,\n InstantLoanConfig,\n InstantLoanEvent,\n InstantLoanEventType,\n InstantLoanFindBorrow,\n InstantLoanFindCollateral,\n InstantLoanFindResult,\n InstantLoanGetRequest,\n InstantLoanInitialDeposit,\n InstantLoanLeg,\n InstantLoanListEventsRequest,\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 MILLISECONDS_PER_SECOND = 1_000;\nconst ETH_STABLECOIN_INFLOW_FEE_FALLBACK = 1_500_000n;\nconst INSTANT_LOAN_MIN_SLIPPAGE_BUFFER_BPS = 200n;\nconst INSTANT_LOAN_FIND_QUERY_MAX_LENGTH = 256;\nconst INSTANT_LOAN_WIRE_CONTEXT = \"instant loan\";\nconst INSTANT_LOAN_ASSETS = [\n CoreAsset.BTC,\n CoreAsset.SOL,\n CoreAsset.USDC,\n CoreAsset.USDT,\n] as const satisfies readonly InstantLoanAsset[];\n\ninterface InstantLoanLtvPolicy {\n ltvBps: bigint;\n minLtvMaxBps: bigint;\n maxLtvMaxBps: bigint;\n}\n\ninterface InstantLoanFindCandidateWire {\n loan_id: string;\n short_ref: string;\n created_at: string;\n lend_asset: string;\n borrow_asset: string;\n collateral_amount: string;\n lend_pool_ic_id: string;\n borrow_pool_ic_id: string;\n profile: string;\n}\n\ninterface InstantLoanFindCandidate {\n loanId: bigint;\n ref: string;\n createdAt: bigint;\n collateral: InstantLoanFindCollateral;\n borrow: InstantLoanFindBorrow;\n profileId: string;\n}\n\ninterface 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\ninterface InstantLoanCollateralHintWire {\n collateralAmountHint: string;\n}\n\ninterface V1InstantLoanFindResponseWire {\n success: true;\n candidates: InstantLoanFindCandidateWire[];\n}\n\ninterface LegacyInstantLoanFindResponseWire {\n success: true;\n loans: InstantLoanFindCandidateWire[];\n}\n\ntype InstantLoanFindResponseWire =\n | V1InstantLoanFindResponseWire\n | LegacyInstantLoanFindResponseWire;\n\ninterface V1InstantLoanCollateralHintResponseWire\n extends InstantLoanCollateralHintWire {\n success: true;\n}\n\ninterface V1InstantLoanCreateResponseWire {\n success: true;\n loan: InstantLoanWire;\n}\n\ninterface InstantLoanCreateAccountWire {\n External: string;\n}\n\ninterface InstantLoanWireCollateral {\n amountHint: string;\n}\n\ninterface InstantLoanWire {\n loanId: string;\n collateral: InstantLoanWireCollateral;\n}\n\ninterface InstantLoanHydrationInput {\n loanId: bigint;\n profileId: string;\n ltvMaxBps: bigint;\n depositWindowSeconds: bigint;\n collateralPoolId: string;\n collateralAmount: bigint;\n borrowPoolId: string;\n collateralAsset: string;\n borrowAsset: string;\n borrowAmount: bigint;\n borrowDestination: InstantLoanAccount;\n refundDestination: InstantLoanAccount;\n started: boolean;\n depositDetectedTimestamp: bigint | null;\n expiryTimestamp: bigint | null;\n}\n\ninterface InstantLoanInitialDepositQuoteInput {\n collateralAmount: bigint;\n decimals: bigint;\n asset: string;\n target: SupplyTarget;\n detectedTimestamp: bigint | null;\n expiryTimestamp: bigint | null;\n}\n\ninterface RepaymentInflowFeeEstimate {\n totalFee: bigint;\n estimateAvailable: boolean;\n}\n\ninterface DeriveInstantLoanStatusInput {\n started: boolean;\n depositDetectedTimestamp: bigint | null;\n expiryTimestamp: bigint | null;\n collateralAmount: bigint;\n totalDebtAmount: bigint;\n activeActivities: Activity[];\n}\n\ninterface DeriveDepositExpiryTimestampInput {\n depositDetectedTimestamp: bigint | null;\n depositWindowSeconds: bigint;\n}\n\ninterface LtvCalculationErrorDetails {\n code: QuoteValidationErrorCode;\n message: string;\n}\n\n/** Accountless instant-loan creation, lookup, recovery, and canister query helpers. */\nexport class InstantLoansModule {\n constructor(\n private readonly canisterContext: CanisterContext,\n private readonly apiClient: ApiClient | undefined,\n private readonly activities: ActivitiesModule,\n private readonly lending: LendingModule,\n private readonly positions: PositionsModule\n ) {}\n\n /**\n * Creates a profileless instant loan and returns canonical canister state plus\n * generated initial-deposit and repayment quote targets.\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 initial-deposit and repayment quote targets.\n */\n async create(request: CreateInstantLoanRequest): Promise<InstantLoan> {\n validateCreateRequest(request);\n const borrowDestination = {\n External: validateInstantLoanBorrowDestination(\n addressFromAccountInput(request.borrowDestination),\n request.borrowAsset\n ),\n };\n const refundDestination = {\n External: validateInstantLoanRefundDestination(\n addressFromAccountInput(request.refundDestination),\n request.collateralAsset\n ),\n };\n const apiClient = this.requireApi(\"Instant loan creation\");\n\n await this.validateInstantLoanLtvPolicy(request);\n\n const response = await apiClient.post<\n V1InstantLoanCreateResponseWire,\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,\n refundDestination,\n });\n\n const loanId = parseUnsignedApiBigint(response.loan.loanId, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"loan ID\",\n });\n const collateralAmount = parseUnsignedApiBigint(\n response.loan.collateral.amountHint,\n {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"collateral amount\",\n }\n );\n const record = await this.getLoanRecord(loanId);\n\n return await this.mapLoanRecord(record, collateralAmount);\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 initial-deposit and repayment quote targets.\n */\n async get(request: InstantLoanGetRequest): Promise<InstantLoan> {\n const loanId =\n \"loanId\" in request ? request.loanId : decodeRef(request.ref);\n\n const record = await this.getLoanRecord(loanId);\n const collateralAmount = await this.getCollateralAmountHint(loanId);\n\n return await this.mapLoanRecord(record, collateralAmount);\n }\n\n /**\n * Finds instant loans by short reference, numeric loan id string, address, or transaction id.\n *\n * Search returns lightweight matches. Call `get({ loanId })` or `get({ ref })`\n * when the user selects a match and you need hydrated loan state.\n *\n * @param query - Short reference, address, transaction id/hash, or numeric loan id string.\n * @returns Matching loan ids and references from the search index.\n */\n async find(query: string): Promise<InstantLoanFindResult[]> {\n const validatedQuery = validateInstantLoanFindQuery(query);\n const candidates = await this.findCandidateLoansByQuery(validatedQuery);\n\n return uniqueInstantLoanFindCandidates(candidates).map((candidate) => ({\n loanId: candidate.loanId,\n ref: candidate.ref,\n createdAt: candidate.createdAt,\n collateral: candidate.collateral,\n borrow: candidate.borrow,\n profileId: candidate.profileId,\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 createFlexibleInstantLoansActor(\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 createFlexibleInstantLoansActor(\n this.canisterContext\n ).get_event(eventId);\n\n const decoded = event[0]\n ? decodeFlexibleHeadlessLoanEvent(event[0])\n : null;\n\n return decoded ? mapInstantLoanEvent(decoded) : 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 createFlexibleInstantLoansActor(\n this.canisterContext\n ).list_events(request.start, request.limit);\n\n return events\n .map(([, event]) => decodeFlexibleHeadlessLoanEvent(event))\n .filter((event): event is DecodedHeadlessLoanEvent => event !== null)\n .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 createFlexibleInstantLoansActor(\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 createFlexibleInstantLoansActor(\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 createFlexibleInstantLoansActor(\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 private async findCandidateLoansByQuery(\n query: string\n ): Promise<InstantLoanFindCandidate[]> {\n const apiClient = this.requireApi(\"Instant loan find\");\n const response = await apiClient.get<InstantLoanFindResponseWire>(\n buildInstantLoanFindPath({ query })\n );\n\n const candidates =\n \"candidates\" in response ? response.candidates : response.loans;\n\n return candidates.map(mapCandidateWire);\n }\n\n private async getLoanRecord(\n loanId: bigint\n ): Promise<DecodedInstantLoanCanisterRecord> {\n try {\n const result = await createFlexibleInstantLoansActor(\n this.canisterContext\n ).get_loan(loanId);\n\n if (\"Err\" in result) {\n throw mapInstantLoansErrorToLiquidiumError(result.Err);\n }\n\n const decoded = decodeFlexibleInstantLoanRecord(result.Ok);\n if (!decoded) {\n throw new LiquidiumError(\n LiquidiumErrorCode.POOL_NOT_FOUND,\n `Instant loan ${loanId.toString()} uses an unsupported asset`\n );\n }\n\n return decoded;\n } catch (error) {\n if (error instanceof LiquidiumError) {\n throw error;\n }\n\n throw mapCanisterCallErrorToLiquidiumError(\"get_loan\", error);\n }\n }\n\n private async mapLoanRecord(\n record: DecodedInstantLoanCanisterRecord,\n collateralAmount: bigint\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 collateralAmount,\n borrowPoolId: record.borrow_pool_id.toText(),\n collateralAsset: record.lend_asset,\n borrowAsset: 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 depositDetectedTimestamp: record.deposit_detected_ts[0] ?? null,\n expiryTimestamp:\n record.expires_at[0] ??\n deriveDepositExpiryTimestamp({\n depositDetectedTimestamp: record.deposit_detected_ts[0] ?? null,\n depositWindowSeconds: record.ltv_timer_s,\n }),\n });\n }\n\n private async getCollateralAmountHint(loanId: bigint): Promise<bigint> {\n const apiClient = this.requireApi(\"Instant loan collateral hint\");\n const response =\n await apiClient.get<V1InstantLoanCollateralHintResponseWire>(\n buildInstantLoanCollateralHintPath({ loanId })\n );\n\n return parseUnsignedApiBigint(response.collateralAmountHint, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"collateral amount\",\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 activeActivities,\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 this.activities.list({ profileId, filter: ActivityFilter.active }),\n ]);\n\n const totalDebtAmount = calculateTotalDebtAmount(borrowPosition);\n const interestBufferAmount = calculateInterestBufferAmount(\n borrowPosition,\n borrowPoolRate.borrowRate\n );\n\n const repaymentInflowFee =\n totalDebtAmount > 0n\n ? await this.estimateRepaymentInflowFee(borrowAsset, repayTarget.chain)\n : { totalFee: 0n, estimateAvailable: false };\n\n const repaymentAmount =\n totalDebtAmount + interestBufferAmount + repaymentInflowFee.totalFee;\n\n const currentCollateralAmount = collateralPosition?.deposited ?? 0n;\n\n const collateralAmount = input.collateralAmount;\n const collateralDecimals =\n collateralPosition?.depositedDecimals ??\n getAssetNativeDecimals(collateralAsset);\n const collateralInterestAmount = collateralPosition?.earnedInterest ?? 0n;\n\n const borrowedAmount = borrowPosition?.borrowed ?? 0n;\n const borrowedDecimals =\n borrowPosition?.borrowedDecimals ?? getAssetNativeDecimals(borrowAsset);\n\n const debtInterestAmount = borrowPosition?.debtInterest ?? 0n;\n\n const status = deriveInstantLoanStatus({\n started: input.started,\n depositDetectedTimestamp: input.depositDetectedTimestamp,\n expiryTimestamp: input.expiryTimestamp,\n collateralAmount: currentCollateralAmount,\n totalDebtAmount,\n activeActivities,\n });\n\n const initialDeposit = await this.createInitialDepositQuote({\n collateralAmount,\n decimals: collateralDecimals,\n asset: collateralAsset,\n target: depositTarget,\n detectedTimestamp: input.depositDetectedTimestamp,\n expiryTimestamp: input.expiryTimestamp,\n });\n\n const 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\n return {\n loanId: input.loanId,\n ref: publicIdFromInt(input.loanId),\n status,\n profileId,\n terms: {\n ltvMaxBps: input.ltvMaxBps,\n depositWindowSeconds: input.depositWindowSeconds,\n },\n collateral: {\n poolId: collateralPoolId,\n asset: collateralAsset,\n chain: depositTarget.chain,\n decimals: collateralDecimals,\n amount: collateralAmount,\n },\n borrow: {\n poolId: borrowPoolId,\n asset: borrowAsset,\n chain: repayTarget.chain,\n decimals: borrowedDecimals,\n amount: input.borrowAmount,\n destination: input.borrowDestination,\n },\n refundDestination: input.refundDestination,\n initialDeposit,\n repayment,\n position: {\n collateralAmount: currentCollateralAmount,\n collateralDecimals,\n collateralInterestAmount,\n borrowedAmount,\n borrowedDecimals,\n debtInterestAmount,\n totalDebtAmount,\n },\n };\n }\n\n private async createInitialDepositQuote(\n input: InstantLoanInitialDepositQuoteInput\n ): Promise<InstantLoanInitialDeposit> {\n const inflowFee = await this.lending.estimateInflowFee({\n asset: input.asset as Asset,\n chain: input.target.chain as Chain,\n });\n\n return {\n amount: input.collateralAmount + inflowFee.totalFee,\n decimals: input.decimals,\n collateralAmount: input.collateralAmount,\n inflowFeeAmount: inflowFee.totalFee,\n asset: input.asset,\n chain: input.target.chain,\n target: input.target,\n detectedTimestamp: input.detectedTimestamp,\n expiryTimestamp: input.expiryTimestamp,\n };\n }\n\n private async estimateRepaymentInflowFee(\n asset: string,\n chain: string\n ): Promise<RepaymentInflowFeeEstimate> {\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(\n input: DeriveInstantLoanStatusInput\n): LiquidiumStatus {\n const activeActivityStatus = deriveActiveInstantLoanActivityStatus(input);\n if (activeActivityStatus) {\n return activeActivityStatus;\n }\n\n if (input.totalDebtAmount > 0n) {\n return createLiquidiumStatus({\n operation: \"repayment\",\n state: \"active\",\n });\n }\n\n if (input.started) {\n return createLiquidiumStatus({\n operation: \"repayment\",\n state: \"completed\",\n });\n }\n\n if (isInstantLoanDepositExpired(input)) {\n return createLiquidiumStatus({\n operation: \"deposit\",\n state: \"expired\",\n });\n }\n\n if (input.collateralAmount > 0n) {\n return createLiquidiumStatus({\n operation: \"deposit\",\n state: \"processing\",\n });\n }\n\n if (input.depositDetectedTimestamp !== null) {\n return createLiquidiumStatus({\n operation: \"deposit\",\n state: \"confirming\",\n });\n }\n\n return createLiquidiumStatus({\n operation: \"deposit\",\n state: \"action_required\",\n });\n}\n\nfunction deriveActiveInstantLoanActivityStatus(\n input: DeriveInstantLoanStatusInput\n): LiquidiumStatus | null {\n if (!input.started) {\n return findActiveActivityStatus(input.activeActivities, \"deposit\");\n }\n\n const borrowStatus = findActiveActivityStatus(\n input.activeActivities,\n \"borrow\"\n );\n if (borrowStatus) {\n return borrowStatus;\n }\n\n return findActiveActivityStatus(input.activeActivities, \"repayment\");\n}\n\nfunction findActiveActivityStatus(\n activities: Activity[],\n operation: LiquidiumStatus[\"operation\"]\n): LiquidiumStatus | null {\n const activity = activities.find(\n (candidate) => candidate.status.operation === operation\n );\n\n return activity?.status ?? null;\n}\n\nfunction isInstantLoanDepositExpired(\n input: DeriveInstantLoanStatusInput\n): boolean {\n if (input.started || input.depositDetectedTimestamp === null) {\n return false;\n }\n\n if (input.expiryTimestamp === null) {\n return false;\n }\n\n return input.expiryTimestamp <= getCurrentUnixTimestampSeconds();\n}\n\nfunction getCurrentUnixTimestampSeconds(): bigint {\n return BigInt(Math.floor(Date.now() / MILLISECONDS_PER_SECOND));\n}\n\nfunction deriveDepositExpiryTimestamp(\n input: DeriveDepositExpiryTimestampInput\n): bigint | null {\n if (input.depositDetectedTimestamp === null) {\n return null;\n }\n\n return input.depositDetectedTimestamp + input.depositWindowSeconds;\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: LtvCalculationErrorDetails | 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 addressFromAccountInput(account: string | ExternalAccount): string {\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 address;\n}\n\nfunction accountFromCanister(\n account: DecodedInstantLoanCanisterRecord[\"borrow_destination\"]\n): InstantLoanAccount {\n if (\"Native\" in account) {\n return { type: \"Native\", principal: account.Native.toText() };\n }\n if (\"AccountIdentifier\" in account) {\n return {\n type: \"AccountIdentifier\",\n address: account.AccountIdentifier,\n };\n }\n if (\"Icrc\" in account) {\n const subaccount = normalizeOptionalSubaccount(account.Icrc.subaccount[0]);\n\n return {\n type: \"Icrc\",\n owner: account.Icrc.owner.toText(),\n subaccount,\n address: encodeIcrcAccount({\n owner: account.Icrc.owner,\n subaccount,\n }),\n };\n }\n\n return { type: \"External\", address: account.External };\n}\n\nfunction normalizeOptionalSubaccount(\n subaccount: Uint8Array | number[] | undefined\n): Uint8Array | undefined {\n if (!subaccount) {\n return undefined;\n }\n\n return subaccount instanceof Uint8Array\n ? subaccount\n : Uint8Array.from(subaccount);\n}\n\nfunction mapInstantLoanEvent(\n event: DecodedHeadlessLoanEvent\n): 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: DecodedHeadlessLoanEventType\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: event.lend_asset as InstantLoanAsset,\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: event.borrow_asset as InstantLoanAsset,\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 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 validateInstantLoanFindQuery(query: unknown): string {\n if (typeof query !== \"string\") {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Instant loan find query must be a string\"\n );\n }\n\n const trimmedQuery = query.trim();\n if (!trimmedQuery) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Instant loan find query must be non-empty\"\n );\n }\n if (trimmedQuery.length > INSTANT_LOAN_FIND_QUERY_MAX_LENGTH) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n `Instant loan find query must be at most ${INSTANT_LOAN_FIND_QUERY_MAX_LENGTH.toString()} characters`\n );\n }\n\n return trimmedQuery;\n}\n\nfunction uniqueInstantLoanFindCandidates(\n candidates: InstantLoanFindCandidate[]\n): InstantLoanFindCandidate[] {\n const candidatesByLoanId = new Map<bigint, InstantLoanFindCandidate>();\n\n for (const candidate of candidates) {\n if (!candidatesByLoanId.has(candidate.loanId)) {\n candidatesByLoanId.set(candidate.loanId, candidate);\n }\n }\n\n return [...candidatesByLoanId.values()];\n}\n\nfunction mapCandidateWire(\n wire: InstantLoanFindCandidateWire\n): InstantLoanFindCandidate {\n return {\n loanId: parseUnsignedApiBigint(wire.loan_id, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"loan ID\",\n }),\n ref: parseNonEmptyApiString(wire.short_ref, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"short reference\",\n }),\n createdAt: parseIsoApiTimestampToUnixSeconds(wire.created_at, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"creation timestamp\",\n }),\n collateral: {\n poolId: parseNonEmptyApiString(wire.lend_pool_ic_id, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"lend pool ID\",\n }),\n asset: parseApiStringUnion(wire.lend_asset, INSTANT_LOAN_ASSETS, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"lend asset\",\n }),\n amount: parseUnsignedApiBigint(wire.collateral_amount, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"collateral amount\",\n }),\n },\n borrow: {\n poolId: parseNonEmptyApiString(wire.borrow_pool_ic_id, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"borrow pool ID\",\n }),\n asset: parseApiStringUnion(wire.borrow_asset, INSTANT_LOAN_ASSETS, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"borrow asset\",\n }),\n },\n profileId: parseNonEmptyApiString(wire.profile, {\n context: INSTANT_LOAN_WIRE_CONTEXT,\n label: \"profile ID\",\n }),\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 { encodeIcrcAccount } from \"@icp-sdk/canisters/ledger/icrc\";\nimport { Principal } from \"@icp-sdk/core/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\";\nimport type {\n CreateTransferErc20TransactionParams,\n EvmContractTransaction,\n} from \"./types\";\n\n/** Parameters for an ERC-20 approve transaction. */\nexport interface CreateApproveTransactionParams {\n /** ERC-20 token contract address. */\n tokenAddress: string;\n /** Contract address approved to spend tokens. */\n spenderAddress: string;\n /** Approval amount in token base units. */\n amount: bigint;\n}\n\n/** Parameters for an ERC-20 deposit-helper transaction. */\nexport interface CreateDepositErc20TransactionParams {\n /** Deposit helper contract address. */\n depositContractAddress: string;\n /** ERC-20 token contract address. */\n tokenAddress: string;\n /** Deposit amount in token base units. */\n amount: bigint;\n /** Pool principal text receiving the inflow. */\n poolId: string;\n /** Liquidium profile principal text. */\n profileId: string;\n /** Expected ICRC destination account text. */\n destinationAccount: string;\n /** Deposit or repayment action for the inflow. */\n action: SupplyAction;\n}\n\n/** Builds calldata for an ERC-20 `approve(spender, amount)` transaction. */\nexport function createApproveTransaction(\n params: CreateApproveTransactionParams\n): EvmContractTransaction {\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(\n params: CreateTransferErc20TransactionParams\n): EvmContractTransaction {\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(\n params: CreateDepositErc20TransactionParams\n): EvmContractTransaction {\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","import { Actor, type ActorMethod } from \"@icp-sdk/core/agent\";\nimport type { IDL } from \"@icp-sdk/core/candid\";\nimport { CK_CANISTER_IDS } from \"../../config\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../errors\";\nimport type { CanisterContext } from \"../../transports/canister-context\";\n\nexport interface CkBtcLedgerActor {\n icrc1_fee: ActorMethod<[], bigint>;\n}\n\nconst idlFactory: IDL.InterfaceFactory = ({ IDL }) =>\n IDL.Service({\n icrc1_fee: IDL.Func([], [IDL.Nat], [\"query\"]),\n });\n\nexport function createCkBtcLedgerActor(\n canisterContext: CanisterContext\n): CkBtcLedgerActor {\n const canisterId = CK_CANISTER_IDS.btcLedger;\n\n if (!canisterId) {\n throw new LiquidiumError(\n LiquidiumErrorCode.SERVICE_UNAVAILABLE,\n \"ckBTC ledger canister ID is not configured\"\n );\n }\n\n return Actor.createActor<CkBtcLedgerActor>(idlFactory, {\n agent: canisterContext.agent,\n canisterId,\n });\n}\n","interface MessageAccount {\n type: \"Native\" | \"External\";\n data: string;\n}\n\ninterface 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 { Asset, Chain } from \"../../../core/types\";\nimport { ceilDivBigint } from \"../../../core/utils/bigint\";\nimport type { EstimateInflowFeeRequest } from \"../types\";\nimport { isEthStablecoin } from \"./supply-targets\";\n\nconst ETH_STABLECOIN_INFLOW_FEE_ROUND_UP_TO_NEAREST_10_CENTS = 100_000n;\nconst BTC_INFLOW_FEE_ROUND_UP_TO_NEAREST_SATS = 500n;\n\n/**\n * Rounds an inflow fee estimate up to the configured unit for its asset.\n *\n * ETH stablecoin fees use 6 decimals, so 100_000 base units is $0.10.\n * BTC fees use sats, so the fee is rounded up to the nearest 500 sats.\n */\nexport function roundInflowFeeEstimate(\n request: EstimateInflowFeeRequest,\n totalFee: bigint\n): bigint {\n if (totalFee <= 0n) {\n return 0n;\n }\n\n if (isEthStablecoin(request.asset, request.chain)) {\n return roundUpToNearest(\n totalFee,\n ETH_STABLECOIN_INFLOW_FEE_ROUND_UP_TO_NEAREST_10_CENTS\n );\n }\n\n if (request.asset === Asset.BTC && request.chain === Chain.BTC) {\n return roundUpToNearest(totalFee, BTC_INFLOW_FEE_ROUND_UP_TO_NEAREST_SATS);\n }\n\n return totalFee;\n}\n\n/** Rounds a positive bigint up to the nearest multiple of the rounding unit. */\nfunction roundUpToNearest(amount: bigint, roundingUnit: bigint): bigint {\n return ceilDivBigint(amount, roundingUnit) * roundingUnit;\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 {\n type EvmAddress,\n normalizeAndValidateEvmAddress,\n} from \"../../../core/address-validation\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../../core/errors\";\nimport {\n CK_ETH_DEPOSIT_CONTRACT_ADDRESS,\n ERC20_ABI,\n MAX_UINT256,\n} from \"../../../core/evm\";\nimport { createLiquidiumStatus } from \"../../../core/status\";\nimport type { CanisterContext } from \"../../../core/transports/canister-context\";\nimport {\n type Asset,\n Chain,\n type EvmReadClient,\n SupplyAction,\n} from \"../../../core/types\";\nimport { retryWithBackoff } from \"../../../core/utils/retry\";\nimport {\n type EthTransactionRequest,\n TransferMode,\n type WalletAdapter,\n} from \"../../../core/wallet-actions\";\nimport {\n createApproveTransaction,\n createDepositErc20Transaction,\n createTransferErc20Transaction,\n} from \"../evm-transactions\";\nimport type {\n EvmSupplyApprovalStrategy,\n EvmSupplyContext,\n GetEvmSupplyContextRequest,\n InflowOperation,\n SubmitInflowRequest,\n SubmitInflowResponse,\n SubmitSupplyFlowInflowRequest,\n SupplyFlow,\n SupplyFlowRequest,\n SupplyPlanType,\n SupplyTarget,\n} from \"../types\";\nimport {\n EvmSupplyApprovalStrategy as ApprovalStrategy,\n SupplyPlanType as PlanType,\n} from \"../types\";\nimport {\n getEthStablecoinContractAddress,\n isEthStablecoin,\n resolveSupplyMechanism,\n resolveSupplyTarget,\n} from \"./supply-targets\";\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 SubmitInflowDefaults = Omit<SubmitInflowRequest, \"txid\">;\ntype AllowanceExpectation = \"zero\" | \"sufficient\";\n\ninterface PoolAssetAndChain {\n asset: string;\n chain: string;\n}\n\ninterface SupplyFlowExecutorParams {\n canisterContext: CanisterContext;\n evmReadClient: EvmReadClient | undefined;\n getPoolById(poolId: string): Promise<PoolAssetAndChain>;\n requireApi(): void;\n submitInflow(request: SubmitInflowRequest): Promise<SubmitInflowResponse>;\n}\n\ninterface SupplyInstruction {\n poolId: string;\n asset: string;\n chain: string;\n action: SupplyAction;\n target: SupplyTarget;\n}\n\ninterface GetEvmSupplyContextForPoolParams {\n request: GetEvmSupplyContextRequest;\n asset: string;\n chain: string;\n}\n\ninterface SendAndSubmitNativeSupplyInflowParams {\n request: SupplyFlowRequest;\n instruction: SupplyInstruction;\n defaultSubmitInflowRequest?: SubmitInflowDefaults;\n}\n\ninterface SubmitSupplyFlowInflowParams {\n instruction: SupplyInstruction;\n mechanism: SupplyPlanType;\n defaultSubmitInflowRequest?: SubmitInflowDefaults;\n submitRequest: SubmitSupplyFlowInflowRequest;\n}\n\ninterface ExecuteContractSupplyParams {\n request: SupplyFlowRequest;\n instruction: SupplyInstruction;\n defaultSubmitInflowRequest?: SubmitInflowDefaults;\n}\n\ninterface SendNativeSupplyTransactionParams {\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}\n\ninterface WaitForExpectedAllowanceParams {\n walletAddress: string;\n tokenAddress: string;\n spenderAddress: string;\n amount: bigint;\n expectation: AllowanceExpectation;\n}\n\ninterface ReadErc20AllowanceParams {\n evmReadClient: EvmReadClient;\n tokenAddress: string;\n ownerAddress: string;\n spenderAddress: string;\n}\n\ninterface ReadErc20BalanceParams {\n evmReadClient: EvmReadClient;\n tokenAddress: string;\n ownerAddress: string;\n}\n\ninterface ApprovalStrategyParams {\n allowance: bigint;\n amount: bigint;\n}\n\ninterface DefaultSubmitInflowRequestParams {\n action: SupplyAction;\n chain: string;\n}\n\ninterface ShouldSubmitInflowParams {\n instruction: SupplyInstruction;\n mechanism: SupplyPlanType;\n}\n\nexport class SupplyFlowExecutor {\n constructor(private readonly params: SupplyFlowExecutorParams) {}\n\n async create(request: SupplyFlowRequest): Promise<SupplyFlow> {\n const target = await resolveSupplyTarget(\n this.params.canisterContext,\n request\n );\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 === PlanType.contractInteraction\n ? Chain.ETH\n : instruction.chain,\n });\n\n let txid: string | undefined;\n switch (mechanism) {\n case PlanType.transfer:\n if (request.walletAdapter) {\n txid = await this.sendAndSubmitNativeSupplyInflow({\n request,\n instruction,\n defaultSubmitInflowRequest,\n });\n }\n break;\n case PlanType.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 status: createLiquidiumStatus({\n operation: mapSupplyActionToStatusOperation(request.action),\n state: txid ? \"confirming\" : \"action_required\",\n }),\n submit: async (submitRequest) => {\n return await this.submitSupplyFlowInflow({\n instruction,\n mechanism,\n defaultSubmitInflowRequest,\n submitRequest,\n });\n },\n };\n }\n\n async getEvmSupplyContext(\n request: GetEvmSupplyContextRequest\n ): Promise<EvmSupplyContext> {\n const selectedPool = await this.params.getPoolById(request.poolId);\n\n return await this.getEvmSupplyContextForPool({\n request,\n asset: selectedPool.asset,\n chain: selectedPool.chain,\n });\n }\n\n private async getEvmSupplyContextForPool(\n params: GetEvmSupplyContextForPoolParams\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 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 !== ApprovalStrategy.none,\n approvalStrategy,\n };\n }\n\n private async sendAndSubmitNativeSupplyInflow(\n params: SendAndSubmitNativeSupplyInflowParams\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 (shouldSubmitInflow({ instruction, mechanism: PlanType.transfer })) {\n try {\n await this.submitInflowWithRetry(txid, defaultSubmitInflowRequest);\n } catch {\n // The transfer 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\n return txid;\n }\n\n private async submitSupplyFlowInflow(\n params: SubmitSupplyFlowInflowParams\n ): Promise<SubmitInflowResponse> {\n if (!shouldSubmitInflow(params)) {\n return {\n txid: params.submitRequest.txid,\n };\n }\n\n const defaultSubmitInflowRequest = params.defaultSubmitInflowRequest;\n if (!defaultSubmitInflowRequest) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Supply flow submit requires an inflow operation\"\n );\n }\n\n return await this.params.submitInflow({\n ...defaultSubmitInflowRequest,\n ...params.submitRequest,\n });\n }\n\n private async executeContractSupply(\n params: ExecuteContractSupplyParams\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.params.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 === ApprovalStrategy.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 !== ApprovalStrategy.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(\n params: SendNativeSupplyTransactionParams\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?: SubmitInflowDefaults\n ): Promise<void> {\n if (!extraRequest) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Inflow submission requires an operation\"\n );\n }\n\n await retryWithBackoff({\n execute: async () => {\n await this.params.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 private async sendEthContractTransaction(\n walletAdapter: Pick<WalletAdapter, \"sendEthTransaction\">,\n walletAddress: string,\n request: EthTransactionRequest,\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(\n params: WaitForExpectedAllowanceParams\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 private requireEvmReadClient(message: string): EvmReadClient {\n if (!this.params.evmReadClient) {\n throw new LiquidiumError(LiquidiumErrorCode.VALIDATION_ERROR, message);\n }\n\n return this.params.evmReadClient;\n }\n}\n\nasync function readErc20Allowance(\n params: ReadErc20AllowanceParams\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(\n params: ReadErc20BalanceParams\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(\n params: ApprovalStrategyParams\n): EvmSupplyApprovalStrategy {\n if (params.allowance >= params.amount) {\n return ApprovalStrategy.none;\n }\n\n if (params.allowance === 0n) {\n return ApprovalStrategy.approveMax;\n }\n\n return ApprovalStrategy.resetThenApproveMax;\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(\n params: DefaultSubmitInflowRequestParams\n): SubmitInflowDefaults | undefined {\n if (params.chain !== Chain.BTC && params.chain !== Chain.ETH) {\n return undefined;\n }\n\n return {\n chain: params.chain,\n operation: mapSupplyActionToStatusOperation(params.action),\n };\n}\n\nfunction mapSupplyActionToStatusOperation(\n action: SupplyAction\n): InflowOperation {\n return action === SupplyAction.repayment ? \"repayment\" : \"deposit\";\n}\n\nfunction shouldSubmitInflow(params: ShouldSubmitInflowParams): boolean {\n if (params.mechanism !== PlanType.transfer) {\n return true;\n }\n\n return !isEthStablecoin(params.instruction.asset, params.instruction.chain);\n}\n","import { encodeIcrcAccount } from \"@icp-sdk/canisters/ledger/icrc\";\nimport type { Principal } from \"@icp-sdk/core/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 interface LendingBtcChainVariant {\n BTC: null;\n}\n\nexport interface LendingEthChainVariant {\n ETH: null;\n}\n\nexport type LendingChainVariant =\n | LendingBtcChainVariant\n | LendingEthChainVariant;\n\nexport interface CanisterNativeOutflowReceiver {\n Native: Principal;\n}\n\nexport interface CanisterExternalOutflowReceiver {\n External: string;\n}\n\nexport interface CanisterAccountIdentifierOutflowReceiver {\n AccountIdentifier: string;\n}\n\nexport interface CanisterIcrcOutflowReceiver {\n Icrc: {\n owner: Principal;\n subaccount: [] | [Uint8Array | number[]];\n };\n}\n\nexport type CanisterOutflowReceiver =\n | CanisterNativeOutflowReceiver\n | CanisterExternalOutflowReceiver\n | CanisterAccountIdentifierOutflowReceiver\n | CanisterIcrcOutflowReceiver;\n\nexport interface 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 if (\"AccountIdentifier\" in receiver) {\n return {\n type: \"AccountIdentifier\",\n account: receiver.AccountIdentifier,\n };\n }\n if (\"Icrc\" in receiver) {\n const subaccount = normalizeOptionalSubaccount(receiver.Icrc.subaccount[0]);\n\n return {\n type: \"Icrc\",\n owner: receiver.Icrc.owner.toText(),\n subaccount,\n account: encodeIcrcAccount({\n owner: receiver.Icrc.owner,\n subaccount,\n }),\n };\n }\n\n return {\n type: \"External\",\n account: receiver.External,\n };\n}\n\nfunction normalizeOptionalSubaccount(\n subaccount: Uint8Array | number[] | undefined\n): Uint8Array | undefined {\n if (!subaccount) {\n return undefined;\n }\n\n return subaccount instanceof Uint8Array\n ? subaccount\n : Uint8Array.from(subaccount);\n}\n\nexport function normalizeOutflowType(\n rawOutflowType: string\n): OutflowDetails[\"outflowType\"] {\n switch (rawOutflowType) {\n case \"Withdraw\":\n return OutflowType.withdrawal;\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 \"@icp-sdk/core/principal\";\nimport { normalizeExternalAddress } from \"../../core/address-validation\";\nimport { getBorrowAmountMinimumValidationError } from \"../../core/borrow-minimums\";\nimport { createCkBtcLedgerActor } from \"../../core/canisters/ckbtc/ledger\";\nimport { createCkBtcMinterActor } from \"../../core/canisters/ckbtc/minter\";\nimport { createDepositAccountsActor } from \"../../core/canisters/deposit-accounts/actor\";\nimport { createLendingActor } from \"../../core/canisters/lending/actor\";\nimport {\n mapCanisterCallErrorToLiquidiumError,\n mapLendingProtocolErrorToLiquidiumError,\n} from \"../../core/canisters/lending/error-mappers\";\nimport {\n createFlexibleLendingActor,\n type DecodedPool,\n decodeFlexiblePool,\n} from \"../../core/canisters/lending/flexible-actor\";\nimport {\n createBorrowAssetMessage,\n createWithdrawAssetMessage,\n} from \"../../core/canisters/lending/messages\";\nimport { LiquidiumError, LiquidiumErrorCode } from \"../../core/errors\";\nimport { normalizeEvmAddress } from \"../../core/evm\";\nimport { SdkApiPath } from \"../../core/sdk-api-paths\";\nimport {\n createLiquidiumStatus,\n type LiquidiumOperation,\n} from \"../../core/status\";\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 OutflowType,\n} from \"../../core/types\";\nimport { encodeInflowSubaccount } from \"../../core/utils/inflow-subaccount\";\nimport { normalizeWalletSignature } from \"../../core/utils/signature\";\nimport { computeExpiryTimestampFromNow } from \"../../core/utils/time\";\nimport {\n TransferMode,\n WalletActionKind,\n WalletExecutionKind,\n} from \"../../core/wallet-actions\";\nimport { executeWith } from \"../../execute\";\nimport { roundInflowFeeEstimate } from \"./_internal/inflow-fee-rounding\";\nimport { SupplyFlowExecutor } from \"./_internal/supply-flow\";\nimport {\n getEthStablecoinContractAddress,\n isEthStablecoin,\n mapDepositAccountErrorToLiquidiumError,\n} from \"./_internal/supply-targets\";\nimport {\n mapCanisterOutflowDetails,\n mapWalletChainToLendingChain,\n} from \"./mappers\";\nimport type {\n BorrowAction,\n BorrowOutflowDetails,\n BorrowSubmitSignatureInfo,\n CreateBorrowRequest,\n CreateWithdrawRequest,\n EstimateInflowFeeRequest,\n EvmSupplyContext,\n GetDepositAddressRequest,\n GetEvmSupplyContextRequest,\n InflowFeeEstimate,\n OutflowDetails,\n SubmitInflowRequest,\n SubmitInflowResponse,\n SupplyFlow,\n SupplyFlowRequest,\n WalletExecutionParams,\n WithdrawAction,\n WithdrawOutflowDetails,\n WithdrawSubmitSignatureInfo,\n} from \"./types\";\n\ninterface OutflowRequestData {\n profileId: string;\n poolId: string;\n amount: bigint;\n receiverAddress: string;\n signerWalletAddress: string;\n expiryTimestamp: bigint;\n}\n\ninterface NormalizeOutflowReceiverAddressParams {\n poolId: string;\n receiverAddress: string;\n}\n\n/** Borrow, withdraw, supply, inflow reporting, and fee-estimation helpers. */\nexport class LendingModule {\n constructor(\n private readonly canisterContext: CanisterContext,\n private readonly apiClient: ApiClient | undefined,\n private 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 const receiverAddress = await this.normalizeOutflowReceiverAddress({\n poolId: request.poolId,\n receiverAddress: destinationAccount,\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,\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: receiverAddress },\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: normalizeWalletSignature(\n signatureInfo.signature,\n signatureInfo.chain\n ),\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.withdrawal,\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 if (request.amount <= 0n) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n \"Borrow amount must be greater than 0\"\n );\n }\n const selectedPool = await this.getPoolById(request.poolId);\n const selectedAsset = selectedPool.asset;\n const minimumBorrowAmountError = getBorrowAmountMinimumValidationError({\n amount: request.amount,\n asset: selectedAsset,\n });\n if (minimumBorrowAmountError) {\n throw new LiquidiumError(\n LiquidiumErrorCode.VALIDATION_ERROR,\n minimumBorrowAmountError.message\n );\n }\n const receiverAddress = normalizeExternalAddress({\n address: destinationAccount,\n asset: selectedAsset,\n chain: selectedPool.chain,\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,\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: receiverAddress },\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: normalizeWalletSignature(\n signatureInfo.signature,\n signatureInfo.chain\n ),\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 return await this.createSupplyFlowExecutor().create(request);\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 return await this.createSupplyFlowExecutor().getEvmSupplyContext(request);\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: GetDepositAddressRequest): 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 include the ckBTC minter deposit fee and ledger fee.\n *\n * @param request - Asset and chain pair to estimate for.\n * @returns Total fee estimate rounded up 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 {\n totalFee: roundInflowFeeEstimate(request, result.Ok),\n };\n }\n\n if (request.asset === Asset.BTC && request.chain === Chain.BTC) {\n const estimate = await this.estimateBtcInflowFee();\n return {\n totalFee: roundInflowFeeEstimate(request, estimate.totalFee),\n };\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 estimateBtcInflowFee(): Promise<InflowFeeEstimate> {\n const [minterFee, ledgerFee] = await Promise.all([\n createCkBtcMinterActor(this.canisterContext).get_deposit_fee(),\n createCkBtcLedgerActor(this.canisterContext).icrc1_fee(),\n ]);\n\n return { totalFee: minterFee + ledgerFee };\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 inflow `operation` and optional `chain`.\n * @returns Acknowledgement including the submitted `txid`.\n */\n async submitInflow(\n request: SubmitInflowRequest\n ): Promise<SubmitInflowResponse> {\n const apiClient = this.requireApi();\n\n const response = await apiClient.post<\n SubmitInflowResponse,\n SubmitInflowRequest\n >(SdkApiPath.inflow, request);\n\n return {\n txid: response.txid,\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 createSupplyFlowExecutor(): SupplyFlowExecutor {\n return new SupplyFlowExecutor({\n canisterContext: this.canisterContext,\n evmReadClient: this.evmReadClient,\n getPoolById: async (poolId) => await this.getPoolById(poolId),\n requireApi: () => {\n this.requireApi();\n },\n submitInflow: async (request) => await this.submitInflow(request),\n });\n }\n\n private async getPoolById(poolId: string): Promise<DecodedPool> {\n const pools = await createFlexibleLendingActor(\n this.canisterContext\n ).list_pools();\n const selectedPool = pools.find(\n (pool) => pool.principal.toText() === poolId\n );\n\n const decodedPool = selectedPool ? decodeFlexiblePool(selectedPool) : null;\n if (!decodedPool) {\n throw new LiquidiumError(\n LiquidiumErrorCode.POOL_NOT_FOUND,\n `Pool not found: ${poolId}`\n );\n }\n\n return decodedPool;\n }\n\n private async normalizeOutflowReceiverAddress(\n params: NormalizeOutflowReceiverAddressParams\n ): Promise<string> {\n const selectedPool = await this.getPoolById(params.poolId);\n\n return normalizeExternalAddress({\n address: params.receiverAddress,\n asset: selectedPool.asset,\n chain: selectedPool.chain,\n });\n }\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.withdrawal,\n operation: string\n): WithdrawOutflowDetails;\nfunction mapExpectedOutflowDetails(\n details: OutflowDetails,\n expectedOutflowType:\n | typeof OutflowType.borrow\n | typeof OutflowType.withdrawal,\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 return {\n ...details,\n status: createLiquidiumStatus({\n operation: mapOutflowTypeToStatusOperation(expectedOutflowType),\n state: details.txid ? \"confirming\" : \"processing\",\n }),\n } as BorrowOutflowDetails | WithdrawOutflowDetails;\n}\n\nfunction mapOutflowTypeToStatusOperation(\n outflowType: typeof OutflowType.borrow | typeof OutflowType.withdrawal\n): LiquidiumOperation {\n return outflowType;\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","import type {\n LendingPoolRecord,\n PoolRateTuple,\n PriceRecord,\n} from \"../../core/canisters/lending/actor\";\nimport type { DecodedPool } from \"../../core/canisters/lending/flexible-actor\";\nimport { RATE_DECIMALS } from \"../../core/rates\";\nimport { getAssetNativeDecimals } from \"../../core/utils/asset-decimals\";\nimport { getVariantKey } from \"../../core/utils/variant\";\nimport type { AssetPrices, Pool, PoolRate } 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 return mapDecodedPoolToPool(\n {\n ...pool,\n asset: getVariantKey(pool.asset),\n chain: getVariantKey(pool.chain),\n },\n rate\n );\n}\n\nexport function mapDecodedPoolToPool(\n pool: DecodedPool,\n rate: PoolRateTuple\n): Pool {\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: pool.asset,\n chain: pool.chain,\n decimals: getAssetNativeDecimals(pool.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(\n rate: PoolRateTuple\n): PoolRate {\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 \"@icp-sdk/core/principal\";\nimport {\n createLendingActor,\n type PoolRateTuple,\n} from \"../../core/canisters/lending/actor\";\nimport {\n createFlexibleLendingActor,\n type DecodedPool,\n decodeFlexiblePool,\n type FlexiblePool,\n} from \"../../core/canisters/lending/flexible-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 mapDecodedPoolToPool,\n mapGetPoolRateResponseToPoolRate,\n mapGetPricesResponseToAssetPrices,\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 private readonly canisterContext: CanisterContext,\n private readonly apiClient: ApiClient | undefined\n ) {}\n\n /**\n * Lists SDK-supported pools with their current rates.\n *\n * Unsupported asset or chain variants returned by the canister are omitted.\n *\n * @returns Supported lending pools enriched with their current rate data.\n */\n async listPools(): Promise<Pool[]> {\n void this.apiClient;\n\n try {\n const flexibleActor = createFlexibleLendingActor(this.canisterContext);\n const rawPools = await flexibleActor.list_pools();\n\n const decodedPools = decodeSupportedFlexiblePools(rawPools);\n\n return await Promise.all(\n decodedPools.map(async (pool) => {\n const poolRate = await flexibleActor.get_pool_rate(pool.principal);\n const resolvedPoolRate = poolRate[0] ?? ZERO_POOL_RATE;\n\n return mapDecodedPoolToPool(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\nfunction decodeSupportedFlexiblePools(rawPools: FlexiblePool[]): DecodedPool[] {\n const decodedPools: DecodedPool[] = [];\n\n for (const rawPool of rawPools) {\n const decodedPool = decodeFlexiblePool(rawPool);\n\n // The canister may expose assets/chains before the SDK supports their flows.\n // Keep market.listPools() scoped to pools this SDK can safely map and use.\n if (!decodedPool) {\n continue;\n }\n\n decodedPools.push(decodedPool);\n }\n\n return decodedPools;\n}\n","import type {\n BorrowingPowerRecord,\n UserStatsRecord,\n} from \"../../core/canisters/lending/actor\";\nimport type {\n DecodedPositionView,\n DecodedUserStats,\n} from \"../../core/canisters/lending/flexible-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\ninterface UserStatsLike {\n debt: bigint;\n collateral: bigint;\n weighted_liquidation_threshold: bigint;\n borrowing_power: BorrowingPowerRecord;\n}\n\nexport function mapPositionViewToPosition(view: PositionView): Position {\n return mapDecodedPositionViewToPosition({\n ...view,\n asset: getVariantKey(view.asset),\n });\n}\n\nexport function mapDecodedPositionViewToPosition(\n view: DecodedPositionView\n): Position {\n const nativeDecimals = getAssetNativeDecimals(view.asset);\n\n return {\n poolId: view.pool_id.toText(),\n asset: view.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 mapUserStatsLikeToUserStats(record);\n}\n\nexport function mapDecodedUserStatsToUserStats(\n stats: DecodedUserStats\n): UserStats {\n return mapUserStatsLikeToUserStats(stats);\n}\n\nfunction mapUserStatsLikeToUserStats(stats: UserStatsLike): UserStats {\n return {\n debt: stats.debt,\n debtDecimals: USD_VALUE_SCALE_DECIMALS,\n collateral: stats.collateral,\n collateralDecimals: USD_VALUE_SCALE_DECIMALS,\n weightedLiquidationThreshold: stats.weighted_liquidation_threshold,\n borrowingPower: mapBorrowingPowerRecordToBorrowingPower(\n stats.borrowing_power\n ),\n };\n}\n","import { Principal } from \"@icp-sdk/core/principal\";\nimport { mapCanisterCallErrorToLiquidiumError } from \"../../core/canisters/lending/error-mappers\";\nimport {\n createFlexibleLendingActor,\n decodeFlexiblePositionView,\n decodeFlexibleUserStats,\n} from \"../../core/canisters/lending/flexible-actor\";\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 mapDecodedPositionViewToPosition,\n mapDecodedUserStatsToUserStats,\n USD_VALUE_SCALE_DECIMALS,\n} from \"./mappers\";\nimport type {\n FullWithdrawAmount,\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 private 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 createFlexibleLendingActor(\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 const decodedView = decodeFlexiblePositionView(view);\n if (!decodedView) {\n return null;\n }\n\n return mapDecodedPositionViewToPosition(decodedView);\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 = createFlexibleLendingActor(this.canisterContext);\n const profilePrincipal = Principal.fromText(profileId);\n const stats = await actor.get_profile_stats(profilePrincipal);\n const decodedStats = decodeFlexibleUserStats(stats);\n\n const positionViews = await Promise.all(\n decodedStats.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(decodeFlexiblePositionView)\n .filter((view): view is NonNullable<typeof view> => view !== null)\n .map(mapDecodedPositionViewToPosition);\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 createFlexibleLendingActor(\n this.canisterContext\n ).get_health_factor(Principal.fromText(profileId));\n\n return {\n healthFactor,\n userStats: mapDecodedUserStatsToUserStats(\n decodeFlexibleUserStats(userStatsRecord)\n ),\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 createFlexibleLendingActor(\n this.canisterContext\n ).get_profile_stats(Principal.fromText(profileId));\n\n return mapDecodedUserStatsToUserStats(decodeFlexibleUserStats(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 27 decimals.\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,\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 /**\n * Returns the current full withdraw amount for a position.\n *\n * `Position.deposited` already reflects the current supplied balance at the\n * latest lending index; do not add `earnedInterest` to this amount.\n * Pass `amount` to withdraw calls and use `decimals` for display formatting.\n *\n * @param profileId - The Liquidium profile principal text.\n * @param poolId - The pool principal text.\n * @returns Full withdraw amount in the supplied asset's base units.\n */\n async getFullWithdrawAmount(\n profileId: string,\n poolId: string\n ): Promise<FullWithdrawAmount> {\n const position = await this.getPosition(profileId, poolId);\n if (!position) {\n return { amount: 0n, decimals: 0n };\n }\n\n return { amount: position.deposited, decimals: position.depositedDecimals };\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.activities,\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"]}