UNPKG

@frak-labs/core-sdk

Version:

Core SDK of the Frak wallet, low level library to interact directly with the frak ecosystem.

646 lines (645 loc) 25.2 kB
import { A as ModalRpcStepsResultType, D as DisplayModalParamsType, G as FinalModalStepType, H as PrepareSsoReturnType, I as SiweAuthenticateReturnType, L as SiweAuthenticationParams, M as SendTransactionModalStepType, N as SendTransactionReturnType, O as ModalRpcMetadata, R as LoginModalStepType, T as DisplaySharingPageResultType, V as PrepareSsoParamsType, W as FinalActionType, _ as SendInteractionParamsType, d as WalletStatusReturnType, f as UserReferralStatusType, i as FrakContext, j as ModalStepTypes, m as GetMerchantInformationReturnType, s as FrakClient, v as DisplayEmbeddedWalletParamsType, w as DisplaySharingPageParamsType, y as DisplayEmbeddedWalletResultType } from "./openSso-BErs7_Bg.cjs"; //#region src/actions/displayEmbeddedWallet.d.ts /** * Function used to display the Frak embedded wallet popup * @param client - The current Frak Client * @param params - The parameter used to customise the embedded wallet * @param placement - Optional placement ID to associate with this display request * @returns The embedded wallet display result */ declare function displayEmbeddedWallet(client: FrakClient, params: DisplayEmbeddedWalletParamsType, placement?: string): Promise<DisplayEmbeddedWalletResultType>; //#endregion //#region src/actions/displayModal.d.ts /** * Function used to display a modal * @param client - The current Frak Client * @param args * @param args.steps - The different steps of the modal * @param args.metadata - The metadata for the modal (customization, etc) * @param placement - Optional placement ID to associate with this modal display * @returns The result of each modal steps * * @description This function will display a modal to the user with the provided steps and metadata. * * @remarks * - The UI of the displayed modal can be configured with the `customCss` property in the `customizations.css` field of the top-level config. * - The `login` step will be automatically skipped if the user is already logged in. It's safe to include this step in all cases to ensure proper user state. * - Steps are automatically reordered in the following sequence: * 1. `login` (if needed) * 2. All other steps in the order specified * 3. `success` (if included, always last) * * @example * Simple sharing modal with steps: * 1. Login (Skipped if already logged in) * 2. Display a success message with sharing link option * * ```ts * const results = await displayModal(frakConfig, { * steps: { * // Simple login with no SSO, nor customization * login: { allowSso: false }, * // Success message * final: { * action: { key: "reward" }, * // Skip this step, it will be only displayed in the stepper within the modal * autoSkip: true, * }, * }, * }); * * console.log("Login step - wallet", results.login.wallet); * ``` * * @example * A full modal example, with a few customization options, with the steps: * 1. Login (Skipped if already logged in) * 2. Authenticate via SIWE * 3. Send a transaction * 4. Display a success message with sharing link options * * ```ts * const results = await displayModal(frakConfig, { * steps: { * // Login step * login: { * allowSso: true, * ssoMetadata: { * logoUrl: "https://my-app.com/logo.png", * homepageLink: "https://my-app.com", * }, * }, * // Siwe authentication * siweAuthenticate: { * siwe: { * domain: "my-app.com", * uri: "https://my-app.com/", * nonce: generateSiweNonce(), * version: "1", * }, * }, * // Send batched transaction * sendTransaction: { * tx: [ * { to: "0xdeadbeef", data: "0xdeadbeef" }, * { to: "0xdeadbeef", data: "0xdeadbeef" }, * ], * }, * // Success message with sharing options * final: { * action: { * key: "sharing", * options: { * popupTitle: "Share the app", * text: "Discover my super app website", * link: "https://my-app.com", * }, * }, * dismissedMetadata: { * title: "Dismiss", * description: "You won't be rewarded for this sharing action", * }, * }, * }, * metadata: { * // Header of desktop modals * header: { * title: "My-App", * icon: "https://my-app.com/logo.png", * }, * // Context that will be present in every modal steps * context: "My-app overkill flow", * }, * }); * ``` */ declare function displayModal<T extends ModalStepTypes[] = ModalStepTypes[]>(client: FrakClient, { steps, metadata }: DisplayModalParamsType<T>, placement?: string): Promise<ModalRpcStepsResultType<T>>; //#endregion //#region src/actions/displaySharingPage.d.ts /** * Function used to display a sharing page * @param client - The current Frak Client * @param params - The parameters to customize the sharing page (products, link override, metadata) * @param placement - Optional placement ID to associate with this display request * @returns The result indicating the user's action (shared, copied, or dismissed) * * @description This function will display a full-page sharing UI to the user, * showing product info, estimated rewards, sharing steps, FAQ, and share/copy buttons. * The sharing link is generated from the user's wallet context + merchant info. * * @remarks * - The promise resolves on the first user action (share or copy) but the page stays visible * - The user can continue to share/copy multiple times after the initial resolution * - Dismissing the page after a share/copy action is a no-op (promise already resolved) * - If the user dismisses without any action, the promise resolves with `{ action: "dismissed" }` * * @example * ```ts * const result = await displaySharingPage(frakClient, { * products: [ * { * title: "Babies camel cuir velours bout carré", * imageUrl: "https://example.com/product.jpg", * }, * ], * }); * * console.log("User action:", result.action); // "shared" | "copied" | "dismissed" * ``` */ declare function displaySharingPage(client: FrakClient, params: DisplaySharingPageParamsType, placement?: string): Promise<DisplaySharingPageResultType>; //#endregion //#region src/actions/ensureIdentity.d.ts /** * Ensure the current wallet ↔ clientId link exists on the backend. * * Called automatically by {@link watchWalletStatus} when a connected wallet * status is received. Acts as a failsafe: if the primary merge (SSO, pairing, * login/register) missed or silently failed, this ensures the link is * eventually established. * * The call is: * - **Idempotent** — if already linked, backend returns immediately * - **Deduplicated** — only fires once per browser session per merchant * - **Fire-and-forget** — errors are logged but never thrown * * @param interactionToken - The SDK JWT from wallet status (x-wallet-sdk-auth) * * @example * ```ts * // Usually called automatically via watchWalletStatus side effect. * // Can also be called manually if needed: * await ensureIdentity("eyJhbGciOi..."); * ``` */ declare function ensureIdentity(interactionToken: string): Promise<void>; //#endregion //#region src/actions/getMerchantInformation.d.ts /** * Fetch the current merchant information (name, rewards, tiers) from the wallet iframe. * * Results are cached in memory for 30 seconds by default. Concurrent calls * while a request is in-flight are deduplicated automatically. * * @param client - The current Frak Client * @param options - Optional cache configuration * @param options.cacheTime - Time in ms to cache the result. Default: 30_000 (30s). Set to 0 to disable. * @returns The merchant information including available reward tiers * * @see {@link @frak-labs/core-sdk!index.GetMerchantInformationReturnType | `GetMerchantInformationReturnType`} for the return type shape */ declare function getMerchantInformation(client: FrakClient, options?: { cacheTime?: number; }): Promise<GetMerchantInformationReturnType>; //#endregion //#region src/actions/getMergeToken.d.ts /** * Fetch a merge token for the current anonymous identity. * * Used by in-app browser redirect flows to preserve identity * when switching from a WebView to the system browser. * The token is appended as `?fmt=` to the redirect URL. * * Results are cached in memory for 30 seconds by default. Concurrent calls * while a request is in-flight are deduplicated automatically. * * @param client - The current Frak Client * @param options - Optional cache configuration * @param options.cacheTime - Time in ms to cache the result. Default: 30_000 (30s). Set to 0 to disable. * @returns The merge token string, or null if unavailable */ declare function getMergeToken(client: FrakClient, options?: { cacheTime?: number; }): Promise<string | null>; //#endregion //#region src/actions/getUserReferralStatus.d.ts /** * Fetch the current user's referral status on the current merchant. * * The listener resolves the user's identity (via clientId or wallet session) * and checks whether a referral link exists where the user is the referee. * * Results are cached in memory for 30 seconds by default. Concurrent calls * while a request is in-flight are deduplicated automatically. * * Returns `null` when the user's identity cannot be resolved. * * @param client - The current Frak Client * @param options - Optional cache configuration * @param options.cacheTime - Time in ms to cache the result. Default: 30_000 (30s). Set to 0 to disable. * @returns The user's referral status, or `null` if identity cannot be resolved * * @example * ```ts * const status = await getUserReferralStatus(client); * if (status?.isReferred) { * console.log("User was referred to this merchant"); * } * ``` */ declare function getUserReferralStatus(client: FrakClient, options?: { cacheTime?: number; }): Promise<UserReferralStatusType | null>; //#endregion //#region src/actions/prepareSso.d.ts /** * Generate SSO URL without opening popup * * This is a **synchronous**, client-side function that generates the SSO URL * without any RPC calls to the wallet iframe. Use this when you need: * - Custom URL modifications before opening popup * - Pre-generation for advanced popup strategies * - URL inspection/logging before SSO flow * * @param client - The current Frak Client * @param args - The SSO parameters * @returns Object containing the generated ssoUrl * * @example * ```ts * // Generate URL for inspection * const { ssoUrl } = prepareSso(client, { * metadata: { logoUrl: "..." }, * directExit: true * }); * console.log("Opening SSO:", ssoUrl); * * // Add custom params * const customUrl = `${ssoUrl}&tracking=abc123`; * await openSso(client, { metadata, ssoPopupUrl: customUrl }); * ``` * * @remarks * For most use cases, just use `openSso()` which handles URL generation automatically. * Only use `prepareSso()` when you need explicit control over the URL. */ declare function prepareSso(client: FrakClient, args: PrepareSsoParamsType): Promise<PrepareSsoReturnType>; //#endregion //#region src/actions/referral/processReferral.d.ts /** * Options for the referral auto-interaction process. */ type ProcessReferralOptions = { /** * If true, always replace the URL with the current user's referral context * so the next visitor gets referred by this user. * @defaultValue false */ alwaysAppendUrl?: boolean; /** * Merchant ID for building the current user's referral context. * Required when `alwaysAppendUrl` is true and the incoming context is V1. * For V2 contexts, the merchantId is already embedded in the context. */ merchantId?: string; }; /** * The different states of the referral process. * @inline */ type ReferralState = "idle" | "processing" | "success" | "no-referrer" | "self-referral"; /** * Handle the full referral interaction flow: * * 1. Check if the user has been referred (if not, early exit) * 2. Preflight self-referral check (if yes, early exit) * 3. Track the arrival event * 4. Replace the current URL with the user's own referral context * 5. Return the resulting referral state * * @param client - The current Frak Client * @param args * @param args.walletStatus - The current user wallet status * @param args.frakContext - The referral context parsed from the URL * @param args.options - Options for URL replacement and merchant context * @returns The referral state * * @see {@link @frak-labs/core-sdk!ModalStepTypes} for modal step types */ declare function processReferral(client: FrakClient, { walletStatus, frakContext, options }: { walletStatus?: WalletStatusReturnType; frakContext?: FrakContext | null; options?: ProcessReferralOptions; }): ReferralState; //#endregion //#region src/actions/referral/referralInteraction.d.ts /** * Function used to handle referral interactions * @param client - The current Frak Client * @param args * @param args.options - Some options for the referral interaction * * @returns A promise with the resulting referral state, or undefined in case of an error * * @description This function will automatically handle the referral interaction process * * @see {@link processReferral} for more details on the automatic referral handling process */ declare function referralInteraction(client: FrakClient, { options }?: { options?: ProcessReferralOptions; }): Promise<("idle" | "processing" | "success" | "no-referrer" | "self-referral") | undefined>; //#endregion //#region src/actions/referral/setupReferral.d.ts /** * Custom event name dispatched on successful referral processing. * * Fired once per page load when a valid referral context is found in the URL * and successfully tracked. Consumers (e.g. `<frak-banner>`) listen for this * to display a referral success message. */ declare const REFERRAL_SUCCESS_EVENT = "frak:referral-success"; /** * Process referral context and emit a DOM event on success. * * - Calls {@link referralInteraction} to detect and track any referral in the URL * - On `"success"`, dispatches a bare {@link REFERRAL_SUCCESS_EVENT} on `window` * - Silently swallows errors (fire-and-forget during SDK init) * * @param client - The initialized Frak client */ declare function setupReferral(client: FrakClient): Promise<void>; //#endregion //#region src/actions/sendInteraction.d.ts /** * Send an interaction to the backend via the listener RPC. * Fire-and-forget: errors are caught and logged, not thrown. * * @param client - The Frak client instance * @param params - The interaction parameters * * @description Sends a user interaction event through the wallet iframe RPC. Supports three interaction types: arrival tracking, sharing events, and custom interactions. * * @example * Track a user arrival with referral attribution: * ```ts * await sendInteraction(client, { * type: "arrival", * referrerWallet: "0x1234...abcd", * landingUrl: window.location.href, * utmSource: "twitter", * utmMedium: "social", * utmCampaign: "launch-2026", * }); * ``` * * @example * Track a sharing event: * ```ts * await sendInteraction(client, { type: "sharing" }); * ``` * * @example * Send a custom interaction: * ```ts * await sendInteraction(client, { * type: "custom", * customType: "newsletter_signup", * data: { email: "user@example.com" }, * }); * ``` */ declare function sendInteraction(client: FrakClient, params: SendInteractionParamsType): Promise<void>; //#endregion //#region src/actions/trackPurchaseStatus.d.ts /** * Function used to track the status of a purchase * when a purchase is tracked, the `purchaseCompleted` interactions will be automatically send for the user when we receive the purchase confirmation via webhook. * * @param args.customerId - The customer id that made the purchase (on your side) * @param args.orderId - The order id of the purchase (on your side) * @param args.token - The token of the purchase * @param args.merchantId - Optional explicit merchant id to use for the tracking request * * @description This function will send a request to the backend to listen for the purchase status. * * @example * async function trackPurchase(checkout) { * const payload = { * customerId: checkout.order.customer.id, * orderId: checkout.order.id, * token: checkout.token, * merchantId: "your-merchant-id", * }; * * await trackPurchaseStatus(payload); * } * * @remarks * - Merchant id is resolved in this order: explicit `args.merchantId`, then `sdkConfigStore.resolveMerchantId()` (config store → sessionStorage → backend fetch). * - This function supports anonymous users and will use the `x-frak-client-id` header when available. * - At least one identity source must exist (`frak-wallet-interaction-token` or `x-frak-client-id`), otherwise the tracking request is skipped. * - This function will print a warning if used in a non-browser environment or if no identity / merchant id can be resolved. */ declare function trackPurchaseStatus(args: { customerId: string | number; orderId: string | number; token: string; merchantId?: string; }): Promise<void>; //#endregion //#region src/actions/watchWalletStatus.d.ts /** * Function used to watch the current frak wallet status * @param client - The current Frak Client * @param callback - The callback that will receive any wallet status change * @returns A promise resolving with the initial wallet status * * @description This function will return the current wallet status, and will listen to any change in the wallet status. * * @example * await watchWalletStatus(frakConfig, (status: WalletStatusReturnType) => { * if (status.key === "connected") { * console.log("Wallet connected:", status.wallet); * } else { * console.log("Wallet not connected"); * } * }); */ declare function watchWalletStatus(client: FrakClient, callback?: (status: WalletStatusReturnType) => void): Promise<WalletStatusReturnType>; //#endregion //#region src/actions/wrapper/modalBuilder.d.ts /** * Represent the type of the modal step builder */ type ModalStepBuilder<Steps extends ModalStepTypes[] = ModalStepTypes[]> = { /** * The current modal params */ params: DisplayModalParamsType<Steps>; /** * Add a send transaction step to the modal */ sendTx: (options: SendTransactionModalStepType["params"]) => ModalStepBuilder<[...Steps, SendTransactionModalStepType]>; /** * Add a final step of type reward to the modal */ reward: (options?: Omit<FinalModalStepType["params"], "action">) => ModalStepBuilder<[...Steps, FinalModalStepType]>; /** * Add a final step of type sharing to the modal */ sharing: (sharingOptions?: Extract<FinalActionType, { key: "sharing"; }>["options"], options?: Omit<FinalModalStepType["params"], "action">) => ModalStepBuilder<[...Steps, FinalModalStepType]>; /** * Display the modal * @param metadataOverride - Function returning optional metadata to override the current modal metadata * @param placement - Optional placement ID to associate with this modal display */ display: (metadataOverride?: (current?: ModalRpcMetadata) => ModalRpcMetadata | undefined, placement?: string) => Promise<ModalRpcStepsResultType<Steps>>; }; /** * Represent the output type of the modal builder */ type ModalBuilder = ModalStepBuilder<[LoginModalStepType]>; /** * Helper to craft Frak modal, and share a base initial config * @param client - The current Frak Client * @param args * @param args.metadata - Common modal metadata (customisation, language etc) * @param args.login - Login step parameters * * @description This function will create a modal builder with the provided metadata and login parameters. * * @example * Here is an example of how to use the `modalBuilder` to create and display a sharing modal: * * ```js * // Create the modal builder * const modalBuilder = window.FrakSDK.modalBuilder(frakClient, baseModalConfig); * * // Configure the information to be shared via the sharing link * const sharingConfig = { * popupTitle: "Share this with your friends", * text: "Discover our product!", * link: window.location.href, * }; * * // Display the sharing modal * function modalShare() { * modalBuilder.sharing(sharingConfig).display(); * } * ``` * * @see {@link ModalStepTypes} for more info about each modal step types and their parameters * @see {@link ModalRpcMetadata} for more info about the metadata that can be passed to the modal * @see {@link ModalRpcStepsResultType} for more info about the result of each modal steps * @see {@link displayModal} for more info about how the modal is displayed */ declare function modalBuilder(client: FrakClient, { metadata, login }: { metadata?: ModalRpcMetadata; login?: LoginModalStepType["params"]; }): ModalBuilder; //#endregion //#region src/actions/wrapper/sendTransaction.d.ts /** * Parameters to directly show a modal used to send a transaction * @inline */ type SendTransactionParams = { /** * The transaction to be sent (either a single tx or multiple ones) */ tx: SendTransactionModalStepType["params"]["tx"]; /** * Custom metadata to be passed to the modal */ metadata?: ModalRpcMetadata; }; /** * Function used to send a user transaction, simple wrapper around the displayModal function to ease the send transaction process * @param client - The current Frak Client * @param args - The parameters * @returns The hash of the transaction that was sent in a promise * * @description This function will display a modal to the user with the provided transaction and metadata. * * @example * const { hash } = await sendTransaction(frakConfig, { * tx: { * to: "0xdeadbeef", * value: toHex(100n), * }, * metadata: { * header: { * title: "Sending eth", * }, * context: "Send 100wei to 0xdeadbeef", * }, * }); * console.log("Transaction hash:", hash); */ declare function sendTransaction(client: FrakClient, { tx, metadata }: SendTransactionParams): Promise<SendTransactionReturnType>; //#endregion //#region src/actions/wrapper/siweAuthenticate.d.ts /** * Parameter used to directly show a modal used to authenticate with SIWE * @inline */ type SiweAuthenticateModalParams = { /** * Partial SIWE params, since we can rebuild them from the SDK if they are empty * * If no parameters provider, some fields will be recomputed from the current configuration and environment. * - `statement` will be set to a default value * - `nonce` will be generated * - `uri` will be set to the current domain * - `version` will be set to "1" * - `domain` will be set to the current window domain * * @default {} */ siwe?: Partial<SiweAuthenticationParams>; /** * Custom metadata to be passed to the modal */ metadata?: ModalRpcMetadata; }; /** * Function used to launch a siwe authentication * @param client - The current Frak Client * @param args - The parameters * @returns The SIWE authentication result (message + signature) in a promise * * @description This function will display a modal to the user with the provided SIWE parameters and metadata. * * @example * import { siweAuthenticate } from "@frak-labs/core-sdk/actions"; * import { parseSiweMessage } from "viem/siwe"; * * const { signature, message } = await siweAuthenticate(frakConfig, { * siwe: { * statement: "Sign in to My App", * domain: "my-app.com", * expirationTimeTimestamp: Date.now() + 1000 * 60 * 5, * }, * metadata: { * header: { * title: "Sign in", * }, * context: "Sign in to My App", * }, * }); * console.log("Parsed final message:", parseSiweMessage(message)); * console.log("Siwe signature:", signature); */ declare function siweAuthenticate(client: FrakClient, { siwe, metadata }: SiweAuthenticateModalParams): Promise<SiweAuthenticateReturnType>; //#endregion export { displayEmbeddedWallet as C, displayModal as S, getUserReferralStatus as _, ModalBuilder as a, ensureIdentity as b, watchWalletStatus as c, REFERRAL_SUCCESS_EVENT as d, setupReferral as f, prepareSso as g, processReferral as h, sendTransaction as i, trackPurchaseStatus as l, ProcessReferralOptions as m, siweAuthenticate as n, ModalStepBuilder as o, referralInteraction as p, SendTransactionParams as r, modalBuilder as s, SiweAuthenticateModalParams as t, sendInteraction as u, getMergeToken as v, displaySharingPage as x, getMerchantInformation as y };