@funkit/connect
Version:
Funkit Connect SDK elevates DeFi apps via web2 sign-ins and one-click checkouts.
212 lines (211 loc) • 10.7 kB
TypeScript
import { type FunAddress } from '@funkit/api-base';
import type { ApiCheckoutClientMetadata, ApiFunkitCheckoutActionParams, ApiFunkitCheckoutConfig } from '@funkit/utils';
import React, { type ReactNode } from 'react';
import type { Address } from 'viem';
import { type PaymentMethodInfo } from '../domains/paymentMethods';
import type { AssetHoldingsItem } from '../utils/assets';
import type { WithdrawalClient } from '../wallets/Wallet';
import { type FunkitCheckoutQuoteResult } from './FunkitHistoryContext';
export type FunkitCheckoutActionParams = ApiFunkitCheckoutActionParams;
export interface DynamicTargetAssetCandidate {
tokenAddress: Address;
tokenChainId: string;
iconSrc: string;
tokenSymbol: string;
isDefault?: boolean;
badgeText?: string;
targetAssetMinAmount?: number;
}
export declare enum FunCheckoutStartingStep {
SOURCE_CHANGE = "source_change",
CONFIRMATION = "confirmation",
SELECT_ASSET = "select_asset"
}
export interface FunkitCheckoutConfig extends Omit<ApiFunkitCheckoutConfig, 'generateActionsParams' | 'customRecipient' | 'modalTitle' | 'iconSrc' | 'modalTitleMeta' | 'externalCheckoutUserId'> {
/** List of contract action params **/
generateActionsParams?: (targetAssetAmount: number, config?: {
targetAsset: Address;
targetChain: string;
}) => Promise<FunkitCheckoutActionParams[]>;
/** 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" **/
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;
/** Title of the item being checked out. e.g. Staked Ether, XYZ Option, Solar Bond ABC **/
checkoutItemTitle: string;
/** @deprecated use targetAssetAmount **/
checkoutItemAmount?: number;
/** amount of source token. it is not baseUnit **/
withdrawalSourceTokenBalance?: () => number;
/** Whether checkout should be started in Defi mode, which has various flow implications (most importantly targetAssetAmount must be set and is not editable throughout the checkout) */
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;
/** *****************************
* Miscellaneous configurations *
********************************/
/** User identification within customer's app for logging and customer dashboard purposes (future). **/
externalCheckoutUserId?: string;
/** a list of candidate assets to be chosen dynamically */
dynamicTargetAssetCandidates?: DynamicTargetAssetCandidate[];
/** minimal toAmount needed to proceed checkout. Checked after quote */
targetAssetMinAmount?: number;
/** For Checkout with Custom Action, QRCode needs special action type
* to specify the onchain action to execute after deposit */
qrcodeActionType?: string;
}
export interface FunkitWithdrawalConfig {
/** 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;
/** source chain id to withdraw **/
sourceChainId: string;
/** source token id to withdraw **/
sourceTokenAddress: Address;
/** whether to show connected as preferred withdrawal destination*/
showConnectedWalletAsPreferredRecipient?: boolean;
/** Wallet instance used to execute the quote */
wallet: WithdrawalClient;
}
export interface FunkitCheckoutValidationResult {
isValid: boolean;
message: string;
}
export interface FunkitCheckoutOnCloseResult {
isNewDeposit: boolean;
}
export type FunkitCheckoutResult = {
type: 'error' | 'success';
message: string;
metadata: object | Error;
};
export interface UseFunkitCheckoutProps {
/** @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 a withdrawal is confirmed with the funkit server. Returns the newly created withdrawalId. **/
onWithdrawalConfirmation?: (withdrawalId: string) => void;
/** @optional fires if the withdrawal fails at any point **/
onWithdrawalError?: (result: FunkitCheckoutResult) => void;
}
/** Ensures that config is defined */
export interface UseFunkitCheckoutPropsWithFullConfig extends UseFunkitCheckoutProps {
config: FunkitCheckoutConfig;
}
/**
* Checkout Item for frontend use
*/
export interface FunkitActiveCheckoutItem extends Omit<ApiCheckoutClientMetadata, 'selectedPaymentMethodInfo' | 'initSettings'> {
/** 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;
};
/** Time of completion of the active checkout item. For frontend use only. **/
completedTimestampMs: number | null;
sourceAssetAmount: number | null;
}
export interface FunkitActiveWithdrawalItem {
/** Unique identifier for frontend use only. */
id: string;
/** Final settings the withdrawal was init-ed with **/
initSettings: Partial<UseFunkitCheckoutPropsWithFullConfig>;
withdrawalSourceTokenBalance: () => number;
}
interface FunkitCheckoutContextInterface {
checkoutItem: FunkitActiveCheckoutItem | null;
getCheckoutProgress(checkoutId: string): CheckoutProgress | undefined;
setCheckoutProgress(checkoutId: string, progress: CheckoutProgress): void;
initNewCheckout(initSettings: UseFunkitCheckoutPropsWithFullConfig): string;
updateModalTitleMeta(newMeta: string): void;
updateSourceAsset(selectedSource: Omit<AssetHoldingsItem, 'amount' | 'usdAmount' | 'chainSymbolKey'>): void;
updateTargetAssetAmount(newTargetAssetAmount: number): void;
updateTargetAsset(asset: {
targetAsset: Address;
targetChain: string;
targetAssetTicker: string;
targetAssetMinAmount: number | undefined;
iconSrc: string | undefined;
}): void;
updateSelectedPaymentMethodInfo(newPaymentMethodInfo: PaymentMethodInfo): void;
updateCustomRecipient: (recipient: Address) => void;
confirmCheckout(shouldBatchOpBypassInit: boolean, quote: FunkitCheckoutQuoteResult, stepMessageSetter: (m: string) => void, withdrawalClient?: WithdrawalClient): Promise<Address>;
cancelCheckout(depositAddress: Address): Promise<boolean>;
/** @deprecated to be removed after quote migration is finished (historically named setCheckoutQuote) */
setCheckout: (checkout: FunkitActiveCheckoutItem) => void;
setCompletedTimestamp(timestampMs: number): void;
withdrawalItem: FunkitActiveWithdrawalItem | null;
initNewWithdrawal(initSettings: Partial<UseFunkitCheckoutPropsWithFullConfig>): string;
updateWithdrawalSourceAssetAmount(newSourceAmount: number): void;
}
export type CheckoutProgressStep = 1 | 2;
export type CheckoutProgress = {
step: CheckoutProgressStep;
};
export declare function FunkitCheckoutProvider({ children }: {
children: ReactNode;
}): React.JSX.Element;
export declare function useCheckoutContext(): FunkitCheckoutContextInterface;
/**
* External hook for user to kickstart a checkout in their app
*/
export declare function useFunkitCheckout(props: UseFunkitCheckoutPropsWithFullConfig): {
beginCheckout: (config?: Partial<FunkitCheckoutConfig>) => Promise<{
isActivated: boolean;
}>;
beginWithdrawal: (config: FunkitWithdrawalConfig) => void;
};
export declare function useFunkitCheckout(props: UseFunkitCheckoutProps): {
beginCheckout: (config: FunkitCheckoutConfig) => Promise<{
isActivated: boolean;
}>;
beginWithdrawal: (config: FunkitWithdrawalConfig) => void;
};
export {};