UNPKG

@yuyin/pay

Version:

Seamless crypto payments. Onboard users from any chain, any coin into your app with one click.

650 lines (621 loc) 24.7 kB
import React$1, { ReactNode, ReactElement } from 'react'; export { version } from '../package.json'; import { CreateConfigParameters } from '@wagmi/core'; import { CreateConnectorFn } from 'wagmi'; import { CoinbaseWalletParameters } from 'wagmi/connectors'; import * as react_jsx_runtime from 'react/jsx-runtime'; import { DaimoPayOrderView, PaymentStartedEvent, PaymentCompletedEvent, PaymentBouncedEvent, ExternalPaymentOptionsString, DaimoPayUserMetadata, DaimoPayOrderWithOrg, DaimoPayHydratedOrderWithOrg, DaimoPayOrder, DaimoPayOrderID, SolanaPublicKey, DaimoPayIntentStatus, DaimoPayOrderMode, DepositAddressPaymentOptionMetadata, PlatformType, ExternalPaymentOptionMetadata, WalletPaymentOption, ExternalPaymentOptions, DepositAddressPaymentOptions, DepositAddressPaymentOptionData } from '@daimo/pay-common'; import { Address, Hex } from 'viem'; import { AppRouter } from '@daimo/pay-api'; import { CreateTRPCClient } from '@trpc/client'; import { WalletName } from '@solana/wallet-adapter-base'; type Hash = `0x${string}`; type CustomAvatarProps = { address?: Hash | undefined; ensName?: string | undefined; ensImage?: string; size: number; radius: number; }; /** Icon for an Ethereum address. Supports ENS names and avatars. */ declare const Avatar: React$1.FC<{ address?: Hash | undefined; name?: string | undefined; size?: number; radius?: number; }>; type Languages$1 = "ar-AE" | "en-US" | "ee-EE" | "es-ES" | "fa-IR" | "fr-FR" | "ja-JP" | "pt-BR" | "zh-CN" | "ca-AD" | "ru-RU" | "zh-CN" | "tr-TR" | "vi-VN"; type Languages = Languages$1; type Theme = "auto" | "web95" | "retro" | "soft" | "midnight" | "minimal" | "rounded" | "nouns"; type Mode = "light" | "dark" | "auto"; type CustomTheme = any; type All = { theme?: Theme; mode?: Mode; customTheme?: CustomTheme; lang?: Languages; }; /** Global options, across all pay buttons and payments. */ type DaimoPayContextOptions = { language?: Languages; hideBalance?: boolean; hideTooltips?: boolean; hideQuestionMarkCTA?: boolean; hideNoWalletCTA?: boolean; hideRecentBadge?: boolean; walletConnectCTA?: "link" | "modal" | "both"; /** Avoids layout shift when the DaimoPay modal is open by adding padding to the body */ avoidLayoutShift?: boolean; /** Automatically embeds Google Font of the current theme. Does not work with custom themes */ embedGoogleFonts?: boolean; truncateLongENSAddress?: boolean; walletConnectName?: string; reducedMotion?: boolean; disclaimer?: ReactNode | string; bufferPolyfill?: boolean; customAvatar?: React.FC<CustomAvatarProps>; initialChainId?: number; enforceSupportedChains?: boolean; ethereumOnboardingUrl?: string; walletOnboardingUrl?: string; /** Blur the background when the modal is open */ overlayBlur?: number; }; /** Modal UI options, set on the pay button triggering that modal. */ type DaimoPayModalOptions = { closeOnSuccess?: boolean; resetOnSuccess?: boolean; connectedWalletOnly?: boolean; }; type types_All = All; type types_CustomAvatarProps = CustomAvatarProps; type types_CustomTheme = CustomTheme; type types_DaimoPayContextOptions = DaimoPayContextOptions; type types_DaimoPayModalOptions = DaimoPayModalOptions; type types_Languages = Languages; type types_Mode = Mode; type types_Theme = Theme; declare namespace types { export type { types_All as All, types_CustomAvatarProps as CustomAvatarProps, types_CustomTheme as CustomTheme, types_DaimoPayContextOptions as DaimoPayContextOptions, types_DaimoPayModalOptions as DaimoPayModalOptions, types_Languages as Languages, types_Mode as Mode, types_Theme as Theme }; } type DefaultConfigProps = { appName: string; appIcon?: string; appDescription?: string; appUrl?: string; /** * WC 2.0 Project ID (get one here: https://cloud.walletconnect.com/sign-in), * it doesn't do much besides tracking. If not provided, use Daimo's * WalletConnect project ID by default. */ walletConnectProjectId?: string; coinbaseWalletPreference?: CoinbaseWalletParameters<"4">["preference"]; additionalConnectors?: CreateConnectorFn[]; } & Partial<CreateConfigParameters>; /** Daimo Pay recommended config, for use with wagmi's createConfig(). */ declare const defaultConfig: ({ appName, appIcon, appDescription, appUrl, walletConnectProjectId, coinbaseWalletPreference, additionalConnectors, chains, client, ...props }: DefaultConfigProps) => CreateConfigParameters; type useConnectCallbackProps = { onConnect?: ({ address, connectorId, }: { address?: string; connectorId?: string; }) => void; onDisconnect?: () => void; }; type DaimoPayProviderProps = { children?: React$1.ReactNode; theme?: Theme; mode?: Mode; customTheme?: CustomTheme; options?: DaimoPayContextOptions; debugMode?: boolean; /** * Be careful with this endpoint, some endpoints (incl. Alchemy) don't support * `signatureSubscribe` which leads to txes behaving erratically * (ex. successful txes take minutes to confirm instead of seconds) */ solanaRpcUrl?: string; /** Custom Pay API, useful for test and staging. */ payApiUrl?: string; } & useConnectCallbackProps; /** * Provides context for DaimoPayButton and hooks. Place in app root or layout. */ declare const DaimoPayProvider: (props: DaimoPayProviderProps) => react_jsx_runtime.JSX.Element; /** Payment details and status. */ type DaimoPayment = DaimoPayOrderView; /** Props for DaimoPayButton. */ type PayButtonPaymentProps = { /** * Your public app ID. Specify either (payId) or (appId + parameters). */ appId: string; /** * Destination chain ID. */ toChain: number; /** * The destination token to send, completing payment. Must be an ERC-20 * token or the zero address, indicating the native token / ETH. */ toToken: Address; /** * The amount of destination token to send (transfer or approve). * If not provided, the user will be prompted to enter an amount. */ toUnits?: string; /** * The destination address to transfer to, or contract to call. */ toAddress: Address; /** * Optional calldata to call an arbitrary function on `toAddress`. */ toCallData?: Hex; /** * The intent verb, such as "Pay", "Deposit", or "Purchase". */ intent?: string; /** * Payment options. By default, all are enabled. */ paymentOptions?: ExternalPaymentOptionsString[]; /** * Preferred chain IDs. Assets on these chains will appear first. */ preferredChains?: number[]; /** * Preferred tokens. These appear first in the token list. */ preferredTokens?: { chain: number; address: Address; }[]; /** * Only allow payments on these EVM chains. */ evmChains?: number[]; /** * External ID. E.g. a correlation ID. */ externalId?: string; /** * Developer metadata. E.g. correlation ID. * */ metadata?: DaimoPayUserMetadata; /** * The address to refund to if the payment bounces or a refund is requested. */ refundAddress?: Address; } | { /** The payment ID, generated via the Daimo Pay API. Replaces params above. */ payId: string; /** Payment options. By default, all are enabled. */ paymentOptions?: ExternalPaymentOptionsString[]; }; type PayButtonCommonProps = PayButtonPaymentProps & { /** Called when user sends payment and transaction is seen on chain */ onPaymentStarted?: (event: PaymentStartedEvent) => void; /** Called when destination transfer or call completes successfully */ onPaymentCompleted?: (event: PaymentCompletedEvent) => void; /** Called when destination call reverts and funds are refunded */ onPaymentBounced?: (event: PaymentBouncedEvent) => void; /** Called when the modal is opened. */ onOpen?: () => void; /** Called when the modal is closed. */ onClose?: () => void; /** Open the modal by default. */ defaultOpen?: boolean; /** Automatically close the modal after a successful payment. */ closeOnSuccess?: boolean; /** Reset the payment after a successful payment. */ resetOnSuccess?: boolean; /** Go directly to tokens in already-connected Ethereum and Solana wallet(s). * Don't let the user pick any other payment method. Used in embedded flows.*/ connectedWalletOnly?: boolean; /** Custom message to display on confirmation page. */ confirmationMessage?: string; /** Redirect URL to return to the app. E.g. after Coinbase, Binance, RampNetwork. */ redirectReturnUrl?: string; }; type DaimoPayButtonProps = PayButtonCommonProps & { /** Light mode, dark mode, or auto. */ mode?: Mode; /** Named theme. See docs for options. */ theme?: Theme; /** Custom theme. See docs for options. */ customTheme?: CustomTheme; /** Disable interaction. */ disabled?: boolean; }; type DaimoPayButtonCustomProps = PayButtonCommonProps & { /** Custom renderer */ children: (renderProps: { show: () => void; hide: () => void; }) => ReactElement; }; /** * A button that shows the Daimo Pay checkout. Replaces the traditional * Connect Wallet » approve » execute sequence with a single action. */ declare function DaimoPayButton(props: DaimoPayButtonProps): JSX.Element; declare namespace DaimoPayButton { var Custom: typeof DaimoPayButtonCustom; } /** Like DaimoPayButton, but with custom styling. */ declare function DaimoPayButtonCustom(props: DaimoPayButtonCustomProps): JSX.Element; declare namespace DaimoPayButtonCustom { var displayName: string; } /** Payment parameters. The payment is created only after user taps pay. */ interface PayParams { /** App ID, for authentication. */ appId: string; /** Destination chain ID. */ toChain: number; /** The destination token to send. */ toToken: Address; /** * The amount of the token to send. * If not provided, the user will be prompted to enter an amount. */ toUnits?: string; /** The final address to transfer to or contract to call. */ toAddress: Address; /** Calldata for final call, or empty data for transfer. */ toCallData?: Hex; /** The intent verb, such as Pay, Deposit, or Purchase. Default: Pay */ intent?: string; /** Payment options. By default, all are enabled. */ paymentOptions?: ExternalPaymentOptionsString[]; /** Preferred chain IDs. */ preferredChains?: number[]; /** Preferred tokens. These appear first in the token list. */ preferredTokens?: { chain: number; address: Address; }[]; /** Only allow payments on these EVM chains. */ evmChains?: number[]; /** External ID. E.g. a correlation ID. */ externalId?: string; /** Developer metadata. E.g. correlation ID. */ metadata?: DaimoPayUserMetadata; /** The address to refund to if the payment bounces or a refund is requested. */ refundAddress?: Address; } type PaymentState$1 = { type: "idle"; } | { type: "preview"; order: DaimoPayOrderWithOrg; payParamsData: PayParamsData; } | { type: "unhydrated"; order: DaimoPayOrderWithOrg; } | { type: "payment_unpaid"; order: DaimoPayHydratedOrderWithOrg; } | { type: "payment_started"; order: DaimoPayHydratedOrderWithOrg; } | { type: "payment_completed"; order: DaimoPayHydratedOrderWithOrg; } | { type: "payment_bounced"; order: DaimoPayHydratedOrderWithOrg; } | { type: "error"; order: DaimoPayOrder | undefined; message: string; }; type PayParamsData = { appId: string; }; type DaimoPayFunctions = { /** * Create a new Daimo Pay order preview with the given parameters. * Call this to start a new payment flow. * * @param params - Parameters describing the payment to be created. */ createPreviewOrder: (params: PayParams) => Promise<Extract<PaymentState$1, { type: "preview"; }>>; /** * Set the order ID to fetch and manage an existing Daimo Pay order. * Useful for resuming or referencing a previously created order. * * @param id - The Daimo Pay order ID to set. */ setPayId: (id: DaimoPayOrderID) => Promise<Extract<PaymentState$1, { type: "unhydrated" | "payment_unpaid" | "payment_started" | "payment_completed" | "payment_bounced"; }>>; /** * Hydrate the current order, locking in the payment intent details and * token swap prices. */ hydrateOrder: (refundAddress?: Address) => Promise<Extract<PaymentState$1, { type: "payment_unpaid"; }>>; /** * Register an Ethereum payment source for the current order. * Call this after the user has submitted an Ethereum payment transaction. * * @param args - Details about the Ethereum payment transaction. */ payEthSource: (args: { paymentTxHash: Hex; sourceChainId: number; payerAddress: Address; sourceToken: Address; sourceAmount: bigint; }) => void; /** * Register a Solana payment source for the current order. * Call this after the user has submitted a Solana payment transaction. * * @param args - Details about the Solana payment transaction. */ paySolanaSource: (args: { paymentTxHash: string; sourceToken: SolanaPublicKey; }) => void; /** * Reset the current payment state and clear the active order. * Call this to start a new payment flow. */ reset: () => void; /** * Update the user's chosen amount in USD. Applies only to deposit flow. * * @deprecated */ setChosenUsd: (usd: number) => void; }; type DaimoPayState = { [S in PaymentState$1 as S["type"]]: { paymentState: S["type"]; order: S extends { order: infer O; } ? O : null; }; }[PaymentState$1["type"]]; type UseDaimoPay = DaimoPayFunctions & DaimoPayState; /** * React hook for interacting with Daimo Pay orders and payments. Use this hook * to manage the lifecycle of a Daimo Pay payment in your application. * * This hook provides a simple interface to create, hydrate, pay, and reset * Daimo Pay orders. * * @returns {UseDaimoPay} An object with current payment state and methods to * manage Daimo Pay orders and payments. */ declare function useDaimoPay(): UseDaimoPay; /** Returns the current payment, or undefined if there is none. * * Status values: * - `payment_unpaid` - the user has not paid yet * - `payment_started` - the user has paid & payment is in progress. This status * typically lasts a few seconds. * - `payment_completed` - the final call or transfer succeeded * - `payment_bounced` - the final call or transfer reverted. Funds were sent * to the payment's configured refund address on the destination chain. */ declare function useDaimoPayStatus(): { paymentId: string; status: DaimoPayIntentStatus; } | undefined; type UseDaimoPayUI = { resetPayment: (payParams?: Partial<PayParams>) => Promise<void>; }; declare function useDaimoPayUI(): UseDaimoPayUI; /** Icon for an EVM chain, given chain ID. No ID shows a loading spinner. */ declare const Chain: React$1.FC<{ id?: number; unsupported?: boolean; radius?: number | string; size?: number | string; }>; /** Ethereum wallets, by name. */ declare const wallets: { [key: string]: CreateConnectorFn; }; declare const daimoPayVersion: string; declare enum ROUTES { SELECT_METHOD = "daimoPaySelectMethod", SELECT_TOKEN = "daimoPaySelectToken", SELECT_AMOUNT = "daimoPaySelectAmount", SELECT_EXTERNAL_AMOUNT = "daimoPaySelectExternalAmount", SELECT_DEPOSIT_ADDRESS_AMOUNT = "daimoPaySelectDepositAddressAmount", SELECT_WALLET_AMOUNT = "daimoPaySelectWalletAmount", SELECT_ZKP2P = "daimoPaySelectZKP2P", WAITING_EXTERNAL = "daimoPayWaitingExternal", WAITING_WALLET = "daimoPayWaitingWallet", SELECT_DEPOSIT_ADDRESS_CHAIN = "daimoPaySelectDepositAddressChain", WAITING_DEPOSIT_ADDRESS = "daimoPayWaitingDepositAddress", PAY_WITH_TOKEN = "daimoPayPayWithToken", CONFIRMATION = "daimoPayConfirmation", SOLANA_CONNECT = "daimoPaySolanaConnect", SOLANA_CONNECTOR = "daimoPaySolanaConnector", SOLANA_SELECT_AMOUNT = "daimoPaySolanaSelectAmount", SOLANA_PAY_WITH_TOKEN = "daimoPaySolanaPayWithToken", ONBOARDING = "onboarding", ABOUT = "about", CONNECTORS = "connectors", MOBILECONNECTORS = "mobileConnectors", CONNECT = "connect", DOWNLOAD = "download", SWITCHNETWORKS = "switchNetworks" } type TrpcClient = CreateTRPCClient<AppRouter>; type WalletConfigProps = { name?: string; shortName?: string; icon?: string | React.ReactNode; iconConnector?: React.ReactNode; iconShape?: "squircle" | "circle" | "square"; iconShouldShrink?: boolean; downloadUrls?: { download?: string; website?: string; desktop?: string; android?: string; ios?: string; chrome?: string; firefox?: string; brave?: string; edge?: string; safari?: string; }; getWalletConnectDeeplink?: (uri: string) => string; deeplinkScheme?: string; getDaimoPayDeeplink?: (payId: string) => string; shouldDeeplinkDesktop?: boolean; showInMobileConnectors?: boolean; isWcMobileConnector?: boolean; isSolanaOnly?: boolean; }; declare function useDepositAddressOptions({ trpc, usdRequired, mode, }: { trpc: TrpcClient; usdRequired: number | undefined; mode: DaimoPayOrderMode | undefined; }): { options: DepositAddressPaymentOptionMetadata[]; loading: boolean; }; declare function useExternalPaymentOptions({ trpc, filterIds, platform, usdRequired, mode, }: { trpc: TrpcClient; filterIds: string[] | undefined; platform: PlatformType | undefined; usdRequired: number | undefined; mode: DaimoPayOrderMode | undefined; }): { options: Map<"external" | "zkp2p", ExternalPaymentOptionMetadata[]>; loading: boolean; }; /** Wallet payment options. User picks one. */ declare function useSolanaPaymentOptions({ trpc, address, usdRequired, isDepositFlow, }: { trpc: TrpcClient; address: string | undefined; usdRequired: number | undefined; isDepositFlow: boolean; }): { options: WalletPaymentOption[] | null; isLoading: boolean; }; /** Wallet payment options. User picks one. */ declare function useWalletPaymentOptions({ trpc, address, usdRequired, destChainId, preferredChains, preferredTokens, evmChains, isDepositFlow, log, }: { trpc: TrpcClient; address: string | undefined; usdRequired: number | undefined; destChainId: number | undefined; preferredChains: number[] | undefined; preferredTokens: { chain: number; address: string; }[] | undefined; evmChains: number[] | undefined; isDepositFlow: boolean; log: (msg: string) => void; }): { options: WalletPaymentOption[] | null; isLoading: boolean; }; /** Creates (or loads) a payment and manages the corresponding modal. */ interface PaymentState { generatePreviewOrder: () => void; resetOrder: (payParams?: Partial<PayParams>) => Promise<void>; buttonProps: PayButtonPaymentProps | undefined; setButtonProps: (props: PayButtonPaymentProps | undefined) => void; setPayId: (id: string | undefined) => void; setPayParams: (payParams: PayParams | undefined) => Promise<void>; isDepositFlow: boolean; paymentWaitingMessage: string | undefined; externalPaymentOptions: ReturnType<typeof useExternalPaymentOptions>; selectedWallet: WalletConfigProps | undefined; selectedWalletDeepLink: string | undefined; showSolanaPaymentMethod: boolean; walletPaymentOptions: ReturnType<typeof useWalletPaymentOptions>; solanaPaymentOptions: ReturnType<typeof useSolanaPaymentOptions>; depositAddressOptions: ReturnType<typeof useDepositAddressOptions>; selectedExternalOption: ExternalPaymentOptionMetadata | undefined; selectedTokenOption: WalletPaymentOption | undefined; selectedSolanaTokenOption: WalletPaymentOption | undefined; selectedDepositAddressOption: DepositAddressPaymentOptionMetadata | undefined; getOrderUsdLimit: () => number; setPaymentWaitingMessage: (message: string | undefined) => void; tokenMode: "evm" | "solana" | "all"; setTokenMode: (mode: "evm" | "solana" | "all") => void; setSelectedWallet: (wallet: WalletConfigProps | undefined) => void; setSelectedWalletDeepLink: (deepLink: string | undefined) => void; setSelectedExternalOption: (option: ExternalPaymentOptionMetadata | undefined) => void; setSelectedTokenOption: (option: WalletPaymentOption | undefined) => void; setSelectedSolanaTokenOption: (option: WalletPaymentOption | undefined) => void; setSelectedDepositAddressOption: (option: DepositAddressPaymentOptionMetadata | undefined) => void; setChosenUsd: (usd: number) => void; payWithToken: (walletOption: WalletPaymentOption) => Promise<void>; payWithExternal: (option: ExternalPaymentOptions) => Promise<string>; payWithDepositAddress: (option: DepositAddressPaymentOptions) => Promise<DepositAddressPaymentOptionData | null>; payWithSolanaToken: (inputToken: SolanaPublicKey) => Promise<string | undefined>; openInWalletBrowser: (wallet: WalletConfigProps, amountUsd?: number) => void; senderEnsName: string | undefined; } type SolanaWalletName = WalletName<string>; /** Meant for internal use. This will be non-exported in a future SDK version. */ declare const PayContext: React$1.Context<PayContextValue | null>; type PayLogFn = (message: string, ...props: any[]) => void; /** Daimo Pay internal context. */ type PayContextValue = { theme: Theme; setTheme: React$1.Dispatch<React$1.SetStateAction<Theme>>; mode: Mode; setMode: React$1.Dispatch<React$1.SetStateAction<Mode>>; customTheme: CustomTheme | undefined; setCustomTheme: React$1.Dispatch<React$1.SetStateAction<CustomTheme | undefined>>; lang: Languages; setLang: React$1.Dispatch<React$1.SetStateAction<Languages>>; setOnOpen: (fn?: () => void) => void; setOnClose: (fn?: () => void) => void; open: boolean; setOpen: (open: boolean, meta?: Record<string, any>) => void; route: string; setRoute: (route: ROUTES, data?: Record<string, any>) => void; errorMessage: string | React$1.ReactNode | null; debugMode?: boolean; log: PayLogFn; displayError: (message: string | React$1.ReactNode | null, code?: any) => void; resize: number; triggerResize: () => void; /** Session ID. */ sessionId: string; /** EVM mobile connector */ wcWallet: WalletConfigProps | undefined; /** EVM pending connector */ pendingConnectorId: string | undefined; setPendingConnectorId: (id: string) => void; /** Chosen Solana wallet, eg Phantom.*/ solanaConnector: SolanaWalletName | undefined; setSolanaConnector: React$1.Dispatch<React$1.SetStateAction<SolanaWalletName | undefined>>; /** Global options, across all pay buttons and payments. */ options?: DaimoPayContextOptions; /** Loads a payment, then shows the modal to complete payment. */ showPayment: (modalOptions: DaimoPayModalOptions) => Promise<void>; /** Payment status & callbacks. */ paymentState: PaymentState; /** TRPC API client. Internal use only. */ trpc: any; /** Callback to call when the payment is successful. */ onSuccess: () => void; /** Custom message to display on confirmation page. */ confirmationMessage?: string; setConfirmationMessage: React$1.Dispatch<React$1.SetStateAction<string | undefined>>; /** Redirect URL to return to the app. E.g. after Coinbase, Binance, RampNetwork. */ redirectReturnUrl?: string; setRedirectReturnUrl: React$1.Dispatch<React$1.SetStateAction<string | undefined>>; } & useConnectCallbackProps; /** Daimo Pay internal context. */ declare const usePayContext: () => PayContextValue; export { Avatar, Chain as ChainIcon, DaimoPayButton, PayContext as DaimoPayContext, DaimoPayProvider, types as Types, daimoPayVersion, defaultConfig as getDefaultConfig, useDaimoPay, useDaimoPayStatus, useDaimoPayUI, usePayContext, wallets }; export type { All, CustomAvatarProps, CustomTheme, DaimoPayButtonCustomProps, DaimoPayButtonProps, DaimoPayContextOptions, DaimoPayModalOptions, DaimoPayment, Languages, Mode, Theme };