import type { FunAddress } from '@funkit/api-base'; import type { LighterRouteType } from '@funkit/connect-core/clients/lighter'; import type { ApiCheckoutClientMetadata, ApiFunkitCheckoutActionParams, ApiFunkitCheckoutConfig } from '@funkit/utils'; import type { ReactNode } from 'react'; import type { Address } from 'viem'; import type { NadoWithdrawalCustomerConfig, NadoWithdrawalCustomerData } from '@funkit/connect-core/clients/nado'; import type { PaymentMethodInfo } from '../../domains/paymentMethods'; import type { CheckoutBlockedReason } from '../../modals/CheckoutModal/CheckoutBlockedReason'; import type { FunCheckoutStep } from '../../modals/CheckoutModal/FunCheckoutStep'; import type { WithdrawalClient, WithdrawalTransaction } from '../../wallets/Wallet'; import type { FunkitCheckoutQuoteResult } from '../FunkitHistoryContext'; export type FunkitCheckoutActionParams = ApiFunkitCheckoutActionParams; import type { AssetClass, DynamicTargetAssetCandidate as CoreDynamicTargetAssetCandidate, TokenInfo } from '@funkit/connect-core'; export type { AssetClass, TokenInfo } from '@funkit/connect-core'; export interface DynamicTargetAssetCandidate extends CoreDynamicTargetAssetCandidate { } /** * Argument passed to a dynamic {@link FunkitCheckoutConfig.modalTitle} resolver. * Extends {@link TokenInfo} with the active dynamic routing id so titles can be * keyed by route/action — not just token address — which matters when two * routes share a target token (e.g. Lighter USDC perps vs spot both deposit * mainnet USDC). */ export interface ModalTitleContext extends TokenInfo { dynamicRoutingId?: string; } export interface DestinationAccount { /** Integrator-defined identity matched by a candidate's destinationAccountId. */ id: string; /** Account label supplied already translated by the integrator. */ label: string; /** Defaults to the SDK account icon when omitted. Not persisted in checkout history. */ icon?: ReactNode; } /** * A token to offer adding to the user's wallet (EIP-747 `wallet_watchAsset`) on * the post-checkout success screen. * * Set this when the token the user ends up holding differs from the checkout's * destination token — e.g. a vault receipt token (Aave's aUSDT) minted by a * post-swap supply action, where the checkout's `toTokenAddress` is the * intermediate underlying (USDT), not the token the wallet should track. * * Purely a post-checkout UX affordance: nothing in quoting, routing, or amount * display reads this field, so setting it cannot perturb a checkout's quote. */ export interface AddToWalletToken extends TokenInfo { /** Symbol shown in the wallet prompt (e.g. "aUSDT"). */ tokenSymbol: string; /** Token decimals. If omitted, the button reads `decimals()` on-chain. */ decimals?: number; /** Optional token icon, passed to the wallet as `image`. */ iconSrc?: string; } export declare enum FunCheckoutStartingStep { SOURCE_CHANGE = "source_change", CONFIRMATION = "confirmation", SELECT_ASSET = "select_asset", /** * Open directly on the Polymarket perps ⇄ predictions transfer step. * Requires {@link FunkitCheckoutConfig.polymarketPerpsTransfer} handles * (set by `createPolymarketDepositConfig`) — without them the step renders * but cannot transfer. */ PERPS_TRANSFER = "perps_transfer" } /** Token a Polymarket account can be topped up with. */ export type PolymarketTopupToken = 'pUSD'; /** * What a transfer rail returns once it accepts. `id` is whatever identifies the * transfer on the venue's side and can later be joined against it — an on-chain * transaction hash, a relayer id, or a perps API withdraw id, depending on how * the integrator implements that direction. */ export interface PolymarketTransferResult { id: string; } /** * Geo eligibility per Polymarket product. Only location restrictions belong * here: an unavailable destination is shown with "Unavailable in your * location", so gating on entitlement or session state would mislabel the * cause. */ export interface DepositAccess { perps: boolean; predictions: boolean; } /** * A Polymarket account in the transfer step. Both accounts share the same shape * so each direction is symmetrical and integrator-owned. */ export interface PolymarketTransferAccount { /** Account address (the transfer target when funds move *into* it). */ address: Address; /** Minimum amount (USD) to top this account up with `token` (0 = none). */ getMinTopupAmount: (token: PolymarketTopupToken) => number; /** * Transfers funds *from* this account to `toAddress`. Implemented by the * integrator (keeps their perps API auth in-house); the SDK invokes the * source account's transfer when the user confirms. `amountUsd` is the exact * string the user entered (validated numeric, ≤6 decimals) — never a parsed * number — so no float precision is lost before the integrator scales it. * * Returning {@link PolymarketTransferResult} is optional and recommended: the * rail's own id becomes the tracking record's key, which is the only thing * that can later join a Fun record to the venue's side of the same transfer. * Returning nothing still records the transfer under a locally minted id. * * To show a specific message on failure, throw a `FunError` (exported from * `@funkit/connect`). Any other rejection shows the generic error notice. */ transfer: (params: { toAddress: Address; amountUsd: string; }) => Promise; /** * Fetches this account's live balance (USD). The transfer step polls this and * displays the result as-is — it never adjusts balances client-side — and * refetches right after a transfer. Integrator-owned. */ getBalanceUsd: () => Promise; } /** * Integrator-reported in-flight perps transfers. While either flag is set the * transfer step disables Transfer and shows a pending state: both balances are * about to move, so a new transfer would be sized against numbers that are * about to change. Supplied initially through `createPolymarketDepositConfig` * (`pendingTransfers`) and updated live through * `useUpdateActiveFunkitCheckout().updatePolymarketPerpsTransferPending`. */ export interface PolymarketPerpsTransferPending { /** A predictions → perps deposit was submitted and is not yet credited. */ isPerpsDepositPending: boolean; /** A perps → predictions withdrawal was submitted and has not yet landed. */ isPerpsWithdrawalPending: boolean; } /** Which way funds move on the transfer step; the name is the destination. */ export type PerpsTransferDirection = 'toPerps' | 'toPredictions'; /** The two accounts the perps transfer step moves funds between. */ export interface PolymarketPerpsTransferHandles { predictions: PolymarketTransferAccount; perps: PolymarketTransferAccount; /** Integrator-reported in-flight transfers; absent means none pending. */ pending?: PolymarketPerpsTransferPending; access?: DepositAccess; /** * Direction the transfer step opens with. Defaults to Predictions → Perps; * a single-product `access` still wins and locks the direction. */ initialDirection?: PerpsTransferDirection; /** * Amount the transfer step opens with: a plain USD string, up to 2 decimals, * no commas/separators (`'12.50'`, `'25'`, `'1000.00'`). Invalid or zero * values are ignored; empty by default. */ initialAmountUsd?: string; } /** * Screens a header tab can open. `SOURCE_CHANGE` is the deposit screen; the * others are steps that need no extra modal state, since a tab opens its step * with `{ ...modalState, step }`. */ export type CheckoutHeaderTabStep = FunCheckoutStep.SOURCE_CHANGE | FunCheckoutStep.PERPS_TRANSFER | FunCheckoutStep.CONVERT; export interface CheckoutHeaderTab { /** Stable id; used for the active-tab highlight and logs. */ id: string; /** Tab text, already translated (or a customer-supplied string shown as-is). */ label: string; /** Shown but not clickable. */ disabled?: boolean; /** Tooltip on a disabled tab. */ disabledTooltip?: string; /** Screen this tab opens. */ step: CheckoutHeaderTabStep; /** * Deposit destination (token, chain, recipient, route) applied on click, * before the screen opens. Omit to keep the current one. Has no bearing on * which tab is active; see `CheckoutHeaderTabs.resolveSharedTab`. */ dynamicTargetAsset?: DynamicTargetAssetCandidate; /** * Fills the header behind the tabs with the theme's `offBackground` while * this tab is active. The active pill takes the other color, so it always * contrasts. Omit for the plain modal background. */ headerBackground?: 'offBackground'; } export interface CheckoutHeaderTabs { tabs: CheckoutHeaderTab[]; /** * Picks the active tab when several tabs open the same screen (e.g. predictions & perps for the deposit screen). * Fn receives those tabs and returns the id of whichever matches the live config. * Not called for a tab that has a unique screen. */ resolveSharedTab?: (screenTabs: CheckoutHeaderTab[]) => string; } export interface FunkitCheckoutConfig extends Omit { /** List of contract action params **/ generateActionsParams?: (targetAssetAmount: number, config?: { targetAsset: Address; targetChain: string; }) => Promise; /** Custom recipient address of the checkout. If specified, a different checkout flow will be executed. It is not recommended to set this unless the Fun.xyz team advises it. **/ customRecipient?: FunAddress; /** **************************************** * Checkout ModalUI-related configurations * *******************************************/ /** Title to show in the checkout modal. Defaults to "Checkout". * The resolver receives the target token plus the active `dynamicRoutingId`, * so titles can disambiguate routes that share a target token. **/ modalTitle?: string | ((asset: ModalTitleContext) => string); /** Additional information to show in the title of the checkout modal. Blank by default **/ modalTitleMeta?: string; /** * Whether the fiat on-ramp shows the destination token (ticker + icon) under * the amount, e.g. "100 USD of DOGE". Defaults to `true`. The SDK picks the * token from the checkout target; set `false` to hide the row, e.g. for a * stablecoin deposit where it adds nothing. */ showFiatDestinationToken?: boolean; /** * Integrator-provided, display-only yield metadata for the destination * (e.g. an Aave/Felix/Benqi supply). The SDK never computes these — the * integrator resolves them from their own data source and passes a snapshot * at checkout-init time. When present, the confirmation screen renders it as * Supply APY / Collateralization rows (`DestinationYieldRows`). Omitted * segments are simply not rendered. */ destinationYieldInfo?: { /** Supply APY as a display string without the % sign (e.g. "2.79"). */ supplyApy?: string; /** Whether the supply is/will be enabled as collateral for the user. */ collateralizationEnabled?: boolean; }; /** * Integrator-provided health-factor resolver for a lending supply (e.g. Aave). * The SDK never computes health factor — the integrator owns the math (run * against live position data with the protocol's own library, e.g. * `@aave/math-utils`) so it matches the protocol app exactly. The SDK calls * this at the confirmation step with the live supply amount (the target * asset, human units) and renders the result as a Health factor (before → * after) row. Return `null` when the position data isn't ready, or for an * infinite/no-debt health factor return `"-1"` (rendered as ∞). */ resolveHealthFactor?: (targetAssetHumanAmount: string) => { before: string | null; after: string | null; } | null; /** * Additional rows rendered last in the confirmation screen's payment method * summary. Called synchronously whenever live amounts or the selected target * change. Read your own live data here and set a row's `isLoading` while its * data is stale. Text is displayed as provided, without translation. * Return `null` or `[]` to omit rows; only the first 4 are shown. * * @example * resolveDestinationLineItems: ({ targetAssetAmount, targetAsset }) => [ * { * id: 'initial-margin-usage', * label: { text: 'Initial Margin Usage', tooltip: 'Collateral required to open positions.' }, * value: { text: projectInitialMargin(targetAssetAmount), color: 'success' }, * }, * { * id: 'margin-balance', * component: , * }, * ] */ resolveDestinationLineItems?: (ctx: DestinationLineItemContext) => DestinationLineItem[] | null; /** Icon to show in the checkout modal (50px x 50px). If not specified, no icon will be shown. **/ iconSrc?: null | string; /** Title of the item being checked out. e.g. Staked Ether, XYZ Option, Solar Bond ABC **/ checkoutItemTitle: string; /** amount of source token. it is not baseUnit **/ withdrawalSourceTokenBalance?: (params: WithdrawalSourceTokenBalanceParams) => string | number; /** @deprecated isDefiMode has been removed. This field is ignored. */ isDefiMode?: boolean; /** The step at which the checkout process should start */ startingStep?: FunCheckoutStartingStep; /** Symbol of the source token. Required if startingStep is set to FunCheckoutStartingStep.CONFIRMATION. */ sourceTokenSymbol?: string; /** ID of the source chain. Required if startingStep is set to FunCheckoutStartingStep.CONFIRMATION. */ sourceChain?: string; /** Address of the source token on the source chain. Required if startingStep is set to FunCheckoutStartingStep.CONFIRMATION. */ sourceTokenAddress?: Address; /** Address list of the tokens that cannot be used as source. e.g. tokens for staking vault */ disabledSourceTokens?: TokenInfo[]; /** ***************************** * Miscellaneous configurations * ********************************/ /** a list of candidate assets to be chosen dynamically */ dynamicTargetAssetCandidates?: DynamicTargetAssetCandidate[]; /** * Minimal USD needed to deposit. Receives the active `dynamicRoutingId` (like * {@link modalTitle}) so the minimum can vary by route when two routes share a * target token (e.g. Polymarket predictions vs perps). */ getMinDepositUSD?: (asset: ModalTitleContext) => number; /** For Checkout with Custom Action, QRCode needs special action type * to specify the onchain action to execute after deposit */ qrcodeActionType?: string; /** * Polymarket-specific handles for the perps ⇄ predictions transfer step. Set * by `createPolymarketDepositConfig` and read by the perps transfer step. * Lets Polymarket keep their perps API auth in-house (they implement the * withdrawal) instead of handing the SDK an API key. */ polymarketPerpsTransfer?: PolymarketPerpsTransferHandles; /** * For dynamic routing, the id of the dynamic route to use */ dynamicRoutingId?: string; /** * Force a specific bridge provider for the checkout quote. * Set via dynamic routing rules. */ bridgeOverride?: 'across' | 'relay'; /** * Token to offer adding to the user's wallet on the post-checkout success * screen via EIP-747 `wallet_watchAsset`. Set when the held token differs * from the checkout's destination token (e.g. an Aave aUSDT receipt). See * {@link AddToWalletToken}. */ addToWalletToken?: AddToWalletToken; } /** One entry in the withdrawal source-token dropdown. */ export interface SourceTokenOption { /** Selection key. May be a pseudo-symbol where one token has variants. */ symbol: string; /** Display label (may differ from symbol, e.g. "USDC (Perps)") */ label: string; iconSrc?: string; /** * This option's own asset identity, passed to * {@link WithdrawalConfigBase.withdrawalSourceTokenBalance} when selected. * Omit only when every option shares the config's source token — otherwise the * balance is requested for the wrong asset. `decimals` is required by flows * that scale a signed amount from this option. */ asset?: TokenInfo & { decimals?: number; }; /** * Flow-specific identity for this option, forwarded to * {@link WithdrawalConfigBase.withdrawalSourceTokenBalance} when selected. * Carries the venue's own key for the asset where {@link asset} can't express * it — Nado addresses balances by product id, not by token address. */ customData?: WithdrawalSourceCustomData; /** Token class metadata, when this option isn't an ordinary ERC-20. */ assetClass?: AssetClass; } export interface WithdrawalConfigBase { /** Title to show in the checkout modal. Defaults to "Checkout" **/ modalTitle: string; /** Additional information to show in the title of the checkout modal. Blank by default **/ modalTitleMeta?: string; /** Icon to show in the checkout modal (50px x 50px). If not specified, no icon will be shown. **/ iconSrc?: null | string; sourceTokenSymbol: string; /** * Selectable source tokens, when the flow has more than one. Omit for * single-source flows — {@link sourceTokenSymbol} is then the only option. * {@link withdrawalSourceTokenBalance} is called with whichever is selected. */ sourceTokens?: SourceTokenOption[]; /** source chain id to withdraw **/ sourceChainId: string; /** source token id to withdraw **/ sourceTokenAddress: Address; /** Disable connected option for email login user */ disableConnectedWallet?: boolean; /** Default token to select in the receive token dropdown. Falls back to sourceTokenSymbol if not set. */ defaultReceiveToken?: string; /** minimal USD needed to withdraw */ getMinWithdrawalUSD?: (asset: TokenInfo) => number; /** * Returns the minimum withdrawal amount in token units for the given symbol. * Used when the source token can vary (e.g. Lighter Secure withdrawal). */ getMinWithdrawalAmount?: (symbol: string) => number; /** * Maximum USD value allowed for a single withdrawal. Amounts above this block * the CTA (which switches to "Max amount exceeded"). Omit for no upper bound. * Mirrors {@link getMinWithdrawalUSD}. */ getMaxWithdrawalUSD?: (asset: TokenInfo) => number; /** * Returns the current withdrawable balance for `sourceAsset`. Takes precedence * over any balance the SDK derives itself, so it must account for whatever the * SDK cannot see (margin requirements, locked collateral). * Called on every render — use a ref-backed stable callback so the value * stays live without triggering unnecessary re-renders. */ withdrawalSourceTokenBalance?: (params: WithdrawalSourceTokenBalanceParams) => string | number; /** * Optional async hook fired when the user commits to the withdrawal — after * the withdraw CTA, but before any nonce fetch, wallet signature, or tx * submission. Awaited, so async work completes before signing begins. * * Throw to abort: the error message is surfaced to the user verbatim and no * nonce is consumed. Runs on every withdrawal method, before * {@link WalletWithdrawalConfig.preWithdrawalAction}. */ onBeforeSign?: () => Promise | void; /** * Additional rows rendered first in the withdrawal screen's transaction * breakdown. Called synchronously whenever live amounts change. * Text is displayed as provided, without translation, and never changes the total. * Return `null` or `[]` to omit rows; only the first 3 are shown. * * @example * resolveWithdrawalFeeItems: ({ sourceAmount }) => [ * { id: 'margin-after', label: 'Margin after withdrawal', value: projectMargin(sourceAmount) }, * ] */ resolveWithdrawalFeeItems?: (ctx: WithdrawalFeeItemContext) => WithdrawalFeeItem[] | null; } /** Display-only row rendered in the withdrawal transaction breakdown. See `resolveWithdrawalFeeItems`. */ export interface WithdrawalFeeItem { id: string; label: string; value: string; tooltip?: string; } /** Live withdrawal amounts handed to `resolveWithdrawalFeeItems`. */ export interface WithdrawalFeeItemContext { /** Amount being quoted, in source-token units, after any fee the SDK deducts before quoting. */ sourceAmount: string; sourceTokenSymbol: string; sourceChainId: string; receiveAmount: string | null; receiveTokenSymbol: string | null; destinationChainId: string | null; } export interface WalletWithdrawalConfig extends WithdrawalConfigBase { /** Wallet instance used to execute the quote */ wallet: WithdrawalClient; /** * Optional async hook that runs **before** the SDK executes the wallet-based * withdrawal quote. Return any transactions that must execute as part of the * withdrawal flow *prior* to the SDK's withdrawal transaction (e.g. an * `approve` and a custom-collateral `unwrap` that produces the source token). * * The SDK atomically prepends the returned array to the withdrawal txn(s) * via the integrator's `wallet.sendTransactions` primitive, so the * approve/unwrap and the withdrawal land in a single user signature. * * Return `[]` if no extra transactions are required — the hook is then * purely a side-effect / preflight step. * * Throw to abort the withdrawal — the thrown error message is surfaced to * the user in the standard error UI. * * Mutually exclusive with {@link CustomWithdrawalConfig['withdrawCallback']} * by virtue of living on a different config variant. */ preWithdrawalAction?: (param: WithdrawalParam) => Promise; /** * Token that Swapped accepts for fiat withdrawal. When set and differs from * {@link WithdrawalConfigBase.sourceTokenAddress}, the Swapped controller * fetches a Relay quote to swap the source token into this token before * sending to Swapped's deposit address. */ swappedTargetTokenAddress?: Address; /** * Chain ID for the Swapped target token. Defaults to * {@link WithdrawalConfigBase.sourceChainId} when omitted. */ swappedTargetChainId?: string; /** * Symbol of the Swapped target token (e.g. 'USDC'). Recorded against the * on-chain movement, which is denominated in the target — not the source — * token. Defaults to {@link WithdrawalConfigBase.sourceTokenSymbol}. */ swappedTargetTokenSymbol?: string; } export interface CustomWithdrawalConfig extends WithdrawalConfigBase { /** * @returns Optionally return a transaction hash string. When provided, the * success screen can display and link to the transaction. */ withdrawCallback: (param: WithdrawalParam) => Promise; /** * Config-level customer-specific data, discriminated by `customerName`. * Populated by a client hook (e.g. `use{Customer}WithdrawalConfig`), not hand-set — * the `customerConfig` counterpart to the per-submission {@link WithdrawalCustomerData}. */ customerConfig?: WithdrawalCustomerConfig; } /** Lighter L2 route type: 0 = perps (USDC collateral), 1 = spot. */ export type { LighterRouteType }; /** * Lighter-specific data for quoteless Secure withdrawal. `assetIndex` selects * the L2 asset (avoids overloading targetChainId); `routeType` disambiguates * USDC, whose perps and spot balances share asset index 3. */ export interface LighterWithdrawalCustomerData { customerName: 'lighter'; assetIndex: number; routeType: LighterRouteType; } /** * Customer-specific data threaded through withdrawal callbacks, discriminated * by `customerName` so future customers extend the union instead of adding * top-level params. */ export type WithdrawalCustomerData = LighterWithdrawalCustomerData | NadoWithdrawalCustomerData; /** * Config-level customer-specific data, discriminated by `customerName`. The * `customerConfig` counterpart to {@link WithdrawalCustomerData}. */ export type WithdrawalCustomerConfig = NadoWithdrawalCustomerConfig; /** * Flow-specific descriptor for the selected source token, discriminated by * `type`. Needed where {@link TokenInfo} alone can't name the balance: * - Lighter exposes USDC twice, as perps collateral and as a spot asset, and * both bridge to the same mainnet address (`routeType` matches * {@link LighterWithdrawalCustomerData.routeType}). * - Nado keys every subaccount query on a product id, not a token address. */ export type WithdrawalSourceCustomData = { type: 'lighter'; routeType: LighterRouteType; } | { type: 'nado'; /** Nado's own key for the asset — every subaccount query is keyed on it. */ productId: number; }; /** Argument of {@link WithdrawalConfigBase.withdrawalSourceTokenBalance}. */ export interface WithdrawalSourceTokenBalanceParams { sourceAsset: TokenInfo; /** Absent for flows whose source token needs no further disambiguation. */ customData?: WithdrawalSourceCustomData; } export interface WithdrawalParam { quoteId: string; funQuote: unknown; targetAssetAddress: Address; targetChainId: number; destinationAddress: Address; /** Customer-specific data for quoteless flows (e.g. Lighter Secure). */ customerData?: WithdrawalCustomerData; /** User-entered amount in token units for quoteless flows (avoids overloading quoteId). */ userInputAmount?: string; /** * USD value of the withdrawal as computed by the modal (token amount × live * spot price). Provided so quoteless flows (e.g. Lighter Secure) don't need * a separate price round-trip to compute `estTotalUsd` for tracking. */ withdrawalUSD?: string; } /** * Form data for an in-flight withdrawal, passed as the second argument of * `onWithdrawalConfirmation` (see {@link UseFunkitCheckoutProps}). * `chainId` / `tokenAddress` / `tokenSymbol` describe the destination * (receive) side the user selected in the modal. */ export type WithdrawalFormData = { destinationAddress: Address; withdrawalUSD: string; tokenSymbol: string; tokenAddress: Address; chainId: number; quote?: FunkitCheckoutQuoteResult; /** Customer-specific data for quoteless flows (e.g. Lighter Secure). */ customerData?: WithdrawalCustomerData; userInputAmount: string; }; /** * A single entry in a {@link MultiMethodWithdrawalConfig}. * * Each option represents a distinct withdrawal method (e.g. "Fast" vs "Secure") * that the user can pick from a selection screen before entering amounts. */ export interface WithdrawalMethodOption { /** Stable id used for tracking/analytics. */ id: string; /** Primary label (e.g. "Fast"). */ keyText: string; /** Optional subtitle (e.g. "USDC Perps only · Multiple chains · Instant"). */ subtitleText?: string; /** Optional leading icon. */ icon?: ReactNode; /** Optional trailing badge/icon rendered to the right of the label. */ valueIcon?: ReactNode; /** * The actual withdrawal config that drives the flow once the user selects * this option. Must be a single concrete (non-multi) config. */ config: SingleWithdrawalConfig; } /** * Withdrawal config that presents the user with a selection screen before * entering the standard withdrawal flow. Once a method is picked, the modal * delegates to that method's inner config. */ export interface MultiMethodWithdrawalConfig { /** Title shown in the modal header. */ modalTitle: string; /** Optional meta under the title. */ modalTitleMeta?: string; /** Optional section label above the options list (e.g. "Crypto"). */ sectionTitle?: string; /** The methods the user can choose between. Order is preserved in the UI. */ methods: WithdrawalMethodOption[]; disableConnectedWallet?: boolean; } /** A config that drives the flow directly: one chain, one token, one wallet. */ export type SingleWithdrawalConfig = WalletWithdrawalConfig | CustomWithdrawalConfig; /** One entry in a {@link MultiSourceWithdrawalConfig} dropdown. */ export interface WithdrawalSourceOption { /** Unique key (e.g. `ETH_BASE`); two sources may share a ticker. Used for selection and analytics. */ id: string; /** Dropdown label. Defaults to the config's `sourceTokenSymbol`. */ label?: string; iconSrc?: string; /** * Drives the whole flow while selected: chain, token, wallet, balance and * limits (`getMinWithdrawalAmount`, `getMinWithdrawalUSD`, ...). Its own * `sourceTokens` list is ignored. */ config: SingleWithdrawalConfig; } /** * Withdrawal config whose source is picked from the amount screen's dropdown. * Sources may sit on different chains and wallets; each is a complete config, * so balances and limits are per source. See `createMultiSourceWithdrawalConfig`. * Crypto only: cash (Swapped) withdrawal is picked before a source, so it is * not offered for this config. */ export interface MultiSourceWithdrawalConfig { /** Title shown in the modal header. */ modalTitle: string; /** Optional meta under the title. */ modalTitleMeta?: string; disableConnectedWallet?: boolean; /** Dropdown order. Each entry is a whole config; not a config's `sourceTokens`. */ sources: WithdrawalSourceOption[]; /** Initially selected source. Defaults to the first. */ defaultSourceId?: string; } export type FunkitWithdrawalConfig = WalletWithdrawalConfig | CustomWithdrawalConfig | MultiMethodWithdrawalConfig | MultiSourceWithdrawalConfig; export interface FunkitCheckoutValidationResult { isValid: boolean; message: string; } export interface FunkitCheckoutOnCloseResult { isNewDeposit: boolean; /** True if the modal was soft-hidden (state preserved) instead of hard-closed */ isSoftHidden?: boolean; } /** * Conflict resolution options when beginCheckout is called while a soft-hidden checkout exists */ export interface CheckoutConflictResolution { /** The ID of the hidden checkout */ hiddenCheckoutId: string; /** Resume the hidden checkout (reshow the modal without starting new checkout) */ resume: () => void; /** Replace the hidden checkout with a new one (discard hidden state, proceed with new checkout) */ replace: () => void; } export type FunkitCheckoutResult = { type: 'error' | 'success'; message: string; metadata: object | Error; }; /** Props common to every checkout, regardless of form factor. */ interface UseFunkitCheckoutBaseProps { /** @optional the checkout config object **/ config?: FunkitCheckoutConfig; /** @optional fires when the checkout modal is opened **/ onOpen?: () => void; /** @optional fires when the checkout modal is closed **/ onClose?: (result: FunkitCheckoutOnCloseResult) => void; /** @optional fires when checkout config is done validating **/ onValidation?: (result: FunkitCheckoutValidationResult) => void; /** @optional fires when a checkout quote is received **/ onEstimation?: (result: FunkitCheckoutQuoteResult) => void; /** @optional fires when a checkout is confirmed with the funkit server. Returns the newly created checkoutId. **/ onConfirmation?: (checkoutId: string) => void; /** @optional fires if the checkout fails at any point **/ onError?: (result: FunkitCheckoutResult) => void; /** @optional fires after the checkout steps are completed **/ onSuccess?: (result: FunkitCheckoutResult) => void; /** * @optional * fires if the checkout requires an active wallet connection. If not specified, defaults to funkit wallet connection. * Call the provided `onLoginFinished()` callback once login is completed to resume the checkout flow (and unhide the soft-hidden modal). * It is strongly recommended to call `onLoginFinished()` after login is completed. If not called, the checkout modal may remain hidden. */ onLoginRequired?: ({ onLoginFinished, }: { onLoginFinished?: () => void; }) => void; /** @optional fires when checkout is blocked (e.g. geo-restriction, security hold, or missing wallet connection). **/ onCheckoutBlocked?: (params: { blockedReason: CheckoutBlockedReason; }) => void; /** @deprecated The PayPal source row has been removed, so this callback never fires. This field is ignored. */ onPolymarketPayPalSwitch?: () => void; /** * @optional fires once the withdrawal has been submitted — after the wallet * transaction is sent or the custom withdrawCallback resolves. `formData` * carries the resolved destination chain/token * ({@link WithdrawalFormData}) so integrators can track cross-chain * withdrawals (e.g. security flows). The first argument is kept for * backwards compatibility: the destination address on wallet flows, the * quoteId on custom-callback flows. Fires for both `beginWithdrawal` and the * cashier withdraw tab. */ onWithdrawalConfirmation?: (withdrawalId: string, formData: WithdrawalFormData) => void; /** @optional fires if the withdrawal fails at any point **/ onWithdrawalError?: (result: FunkitCheckoutResult) => void; } /** * Cashier form factor: the withdraw tab is explicitly requested. The coupling * is compile-time — `withdrawalConfig` is required, so cashier intent can never * be confused with a dropped config. `beginWithdrawal` takes its config as an * argument and needs neither. */ interface CashierFormFactorProps { formFactor: 'cashier'; withdrawalConfig: FunkitWithdrawalConfig; } /** Default checkout form factor: no withdraw tab, so no tab config. */ interface CheckoutFormFactorProps { formFactor?: 'checkout'; withdrawalConfig?: never; } export type UseFunkitCheckoutProps = UseFunkitCheckoutBaseProps & (CashierFormFactorProps | CheckoutFormFactorProps); /** * Resolved settings stored on the checkout item (config guaranteed). This is a * structural superset of both public-prop union members — the `never`-typed * `withdrawalConfig` is relaxed — so internal rebuilds of `initSettings` don't * fight the discriminant. The compile-time cashier↔withdrawalConfig coupling * lives on the public `UseFunkitCheckoutProps` surface, which flows in here. */ export interface UseFunkitCheckoutPropsWithFullConfig extends UseFunkitCheckoutBaseProps { config: FunkitCheckoutConfig; formFactor?: 'cashier' | 'checkout'; withdrawalConfig?: FunkitWithdrawalConfig; } /** * Checkout Item for frontend use */ export interface FunkitActiveCheckoutItem extends Omit { /** The deposit address provided by server after the checkout is confirmed. If `null`, it is not confirmed yet. **/ depositAddress: null | Address; /** Final settings the checkout was init-ed with **/ initSettings: UseFunkitCheckoutPropsWithFullConfig; /** User's selected payment method information */ selectedPaymentMethodInfo: PaymentMethodInfo | null; /** User's choice of source asset to fund the checkout operation **/ selectedSourceAssetInfo: { address: Address | null; symbol: string | null; chainId: string; iconSrc: string | null; /** Source token decimals, when known — lets later screens reconstruct * base-unit amounts. */ decimals?: number; }; /** Time of completion of the active checkout item. For frontend use only. **/ completedTimestampMs: number | null; sourceAssetAmount: string | null; /** In EXACT_IN mode, the fiat value the user entered on InputAmount. * Stored alongside targetAssetAmount so the confirmation screen can display * the same dollar value without recomputing from the token amount. */ inputFiatAmount: number | null; /** Canonical token amount in base units (e.g. 328257705848429095n). * Avoids precision loss from bigint→number round-trips for EXACT_IN quotes. */ inputTokenAmountBaseUnits: bigint | null; } export interface FunkitActiveWithdrawalItem { /** Unique identifier for frontend use only. */ id: string; /** Final settings the withdrawal was init-ed with **/ initSettings: Partial; /** Absent when the integrator wired no callback — never defaulted to `0`, so * the flow can tell "unknown" from "nothing withdrawable". */ withdrawalSourceTokenBalance?: (params: WithdrawalSourceTokenBalanceParams) => string | number; } /** Semantic color for a summary line item's value. The SDK owns the actual colors per theme. */ export type LineItemValueColor = 'default' | 'success' | 'caution' | 'danger'; /** One side of a summary line item. */ export interface LineItemSlot { text: string; /** Renders an info icon with this tooltip after the text. */ tooltip?: string; } export interface LineItemValue extends LineItemSlot { color?: LineItemValueColor; } /** * Display-only row rendered in the payment method summary. See `resolveDestinationLineItems`. * * Either text styled by the SDK (`label` and `value`), or your own `component` * for the whole row, which you style. A component row sits in the same row box, * which lays out its top-level children like a label and a value. Shadow DOM mode * keeps your page's CSS out of the modal, so style it inline or with the theme's * CSS variables (e.g. `var(--rk-colors-secondaryText)`). */ export type DestinationLineItem = { /** Stable identifier — the React key, and the row's `data-testid` as `rk-`. */ id: string; label: LineItemSlot; value: LineItemValue; /** Skeletons the value, e.g. while the data behind it is still loading. */ isLoading?: boolean; component?: never; } | { /** Stable identifier — the React key, and the row's `data-testid` as `rk-`. */ id: string; component: ReactNode; /** Skeletons the whole row, e.g. while the data behind it is still loading. */ isLoading?: boolean; label?: never; value?: never; }; /** Live checkout amounts and the selected target, handed to `resolveDestinationLineItems`. */ export interface DestinationLineItemContext { /** Target asset amount in token units (e.g. "1.5" for 1.5 USDC), matching the "You receive" row. */ targetAssetAmount: string; /** Token the checkout delivers, following the user's pick among dynamic target assets. */ targetAsset: { address: Address; chainId: string; symbol: string; }; /** ID of the destination account the checkout deposits into, when the checkout offers destination accounts. */ destinationAccountId?: string; /** Token the user is paying with. `null` fields when no source is selected yet. */ sourceTokenSymbol: string | null; sourceTokenAddress: Address | null; sourceChainId: string | null; }