@keyban/sdk-react
Version:
Keyban SDK React simplifies the integration of Keyban's MPC wallet in React apps with TypeScript support, flexible storage, and Ethereum blockchain integration.
967 lines (958 loc) • 38.8 kB
text/typescript
import * as _keyban_sdk_base from '@keyban/sdk-base';
import { KeybanAccount, PaginationArgs, KeybanTokenBalance, Address, KeybanNftBalance, KeybanAssetTransfer, KeybanOrder, KeybanUser, AuthConnection, Balance, KeybanToken, KeybanClientConfig, KeybanClient } from '@keyban/sdk-base';
export * from '@keyban/sdk-base';
import * as react_jsx_runtime from 'react/jsx-runtime';
import { PasswordLoginInput, PasswordlessStartInput, PasswordlessLoginInput } from '@keyban/sdk-base/rpc';
import React from 'react';
/**
* A tuple representing the result of an API call to the Keyban servers.
*
* Since all Keyban hooks use the [React Suspense API](https://react.dev/reference/react/Suspense),
* there are only two possible states for the tuple: success and error.
*
* The tuple contains the following data:
* - On **success**:
* - The data result of the API call (of type `T`).
* - `null` for the error.
* - An optional extra object (of type `Extra`) allowing for additional interactions.
* - On **error**:
* - `null` for the data.
* - An `Error` object representing the error.
* - An optional extra object (of type `Extra`) allowing for additional interactions.
* @template T - The type of the data returned on success.
* @template Extra - The type of the optional extra object for additional interactions.
* @remarks
* The `ApiResult` type is designed to simplify handling asynchronous API responses in Keyban hooks.
* It adheres to the pattern `[data, error, extra]`, where:
* - `data`: The result of the API call if successful, or `null` if there was an error.
* - `error`: `null` if the call was successful, or an `Error` object if there was an error.
* - `extra`: An optional object providing additional information or methods, defaulting to `undefined` if not used.
*
* **Example Usage:**
* ```typescript
* const [data, error, extra] = useKeybanSomeHook();
* if (error) {
* // Handle the error
* console.error(error);
* } else {
* // Use the data
* console.log(data);
* // Optionally use extra interactions
* extra?.someMethod();
* }
* ```
*/
type ApiResult<T, Extra = undefined> = readonly [T, null, Extra] | readonly [null, Error, Extra];
/**
* An object representing a paginated data API result.
* @template T - The data type being paginated
*/
type PaginatedData<T> = {
/** A boolean indicating wether the paginated data has a previous page or not. */
hasPrevPage: boolean;
/** A boolean indicating wether the paginated data has a next page or not. */
hasNextPage: boolean;
/** The number of total results. */
totalCount: number;
/** An array of the data. */
nodes: T[];
};
/**
* An object allowing extra interactions with the Keyban API.
*/
type PaginationExtra = {
/** A boolean indicating if the data is currently being fetched. */
loading: boolean;
/** A function to fetch more data when the result is a paginated data type. */
fetchMore?: () => void;
};
/**
* Retrieves the current `KeybanAccount` associated with the Keyban client.
*
* This React hook allows you to access the user's Keyban account within a functional component.
* It returns an `ApiResult` tuple containing the account data or an error if one occurred during retrieval.
* @returns - An array containing the account data, error, and an undefined value.
* @example
* ```tsx
* import { useKeybanAccount } from "@keyban/sdk-react";
*
* const MyComponent: React.FC = () => {
* const [account, accountError] = useKeybanAccount();
* if (accountError) throw accountError;
*
* return (
* <div>
* <p>Your wallet address: {account.address}</p>
* </div>
* );
* };
* ```
* @remarks
* - Ensure that your component is wrapped within a `KeybanProvider` to have access to the Keyban client context.
* - The hook internally uses React Suspense and may throw a promise if the data is not yet available.
* - Handle errors appropriately to ensure a good user experience.
* @see {@link KeybanAccount}
*/
declare function useKeybanAccount(): ApiResult<KeybanAccount>;
/**
* Hook to retrieve and subscribe to the balance of a Keyban account.
*
* This React hook allows you to fetch the native balance of a Keyban account and automatically updates when the balance changes.
* It returns an `ApiResult` tuple containing the balance or an error if one occurred during retrieval.
* @param account - The `KeybanAccount` object representing the user account.
* @returns - An `ApiResult<string>` tuple containing:
* - **First element (`balance`)**: A `string` representing the account's native token balance in the smallest unit (e.g., wei for Ethereum). This value automatically updates when the balance changes.
* - **Second element (`error`)**: An `Error` object if an error occurred during retrieval, or `null` if the balance was fetched successfully.
*
* **Return Structure:**
* ```typescript
* [balance: string, error: Error | null]
* ```
* - `balance`: The current balance of the Keyban account as a string.
* - `error`: An `Error` object if there was an error fetching the balance, otherwise `null`.
* @example
* ```tsx
* import { useKeybanAccount, useKeybanAccountBalance } from "@keyban/sdk-react";
*
* const AccountBalance: React.FC = () => {
* const [account, accountError] = useKeybanAccount();
* if (accountError) throw accountError;
*
* const [balance, balanceError] = useKeybanAccountBalance(account);
* if (balanceError) throw balanceError;
*
* return <div>Balance: {balance}</div>;
* };
* ```
* @remarks
* - **Balance Format:** The balance is returned as a string representing the amount in the smallest denomination (e.g., wei). You may need to format it to a human-readable format (e.g., Ether) using utility functions.
* - **Real-Time Updates:** The hook subscribes to balance changes, so your component will re-render automatically when the balance updates.
* - **Error Handling:** Always check the `error` element to handle any issues that might occur during balance retrieval.
* - Ensure that your component is wrapped within a `KeybanProvider` to have access to the Keyban client context.
* @throws Will throw an error if used outside of a `KeybanProvider` or if there's an issue retrieving the balance.
* @see {@link useKeybanAccount}
* @see {@link KeybanAccount}
*/
declare function useKeybanAccountBalance(account: KeybanAccount): ApiResult<string>;
/**
* Returns an {@link ApiResult} of the ERC20 tokens of an account.
*
* The `useKeybanAccountTokenBalances` React hook enables you to fetch and monitor the list of ERC20 token balances owned by a specific Keyban account. It supports pagination, allowing efficient handling of large token collections by fetching data in manageable segments. This hook returns an `ApiResult` tuple containing the paginated token balance data, any potential errors, and additional pagination controls.
* @param account - The Keyban account object containing the address.
* @param [options] - Optional pagination arguments for fetching the token balances.
* @returns - The result containing paginated ERC20 token balances or an error, along with pagination controls.
* @throws {SdkError} If the provided account has an invalid address (`SdkErrorTypes.AddressInvalid`).
* @throws {SdkError} If no ERC20 token balances are found for the provided account (`SdkErrorTypes.TokenBalancesNotFound`).
* @example
* ```tsx
* import React from 'react';
* import { useKeybanAccount, useKeybanAccountTokenBalances } from "@keyban/sdk-react";
*
* const TokenBalancesList: React.FC = () => {
* const [account, accountError] = useKeybanAccount();
*
* if (accountError) {
* return <div>Error fetching account: {accountError.message}</div>;
* }
*
* const [balances, balancesError, { fetchMore, loading }] = useKeybanAccountTokenBalances(account, { first: 5 });
*
* if (balancesError) {
* return <div>Error fetching token balances: {balancesError.message}</div>;
* }
*
* if (!balances) {
* return <div>Loading token balances...</div>;
* }
*
* return (
* <div>
* <h3>Your ERC20 Token Balances</h3>
* <ul>
* {balances.nodes.map((balance) => (
* <li key={balance.id}>
* <p>Token: {balance.token?.symbol || "Unknown"}</p>
* <p>Balance: {balance.balance}</p>
* {balance.token && (
* <>
* <p>Name: {balance.token.name || "N/A"}</p>
* <p>Decimals: {balance.token.decimals !== null ? balance.token.decimals : "N/A"}</p>
* <img src={balance.token.iconUrl || ""} alt={`${balance.token.symbol} icon`} width={24} height={24} />
* </>
* )}
* </li>
* ))}
* </ul>
* {balances.hasNextPage && (
* <button onClick={fetchMore} disabled={loading}>
* {loading ? 'Loading...' : 'Load More'}
* </button>
* )}
* </div>
* );
* };
*
* export default TokenBalancesList;
* ```
* @remarks
* - **Pagination Support:** Utilize the {@link PaginationArgs} to control the number of ERC20 token balances fetched per request and to navigate through pages using cursors.
* - **Real-Time Updates:** The hook subscribes to changes in the ERC20 token balances, ensuring that your UI reflects the latest data without manual refreshes.
* - **Error Handling:** Always check for errors returned by the hook to provide informative feedback to the user and handle different error scenarios gracefully.
* - **Context Requirement:** Ensure that your component is wrapped within a `KeybanProvider` to provide the necessary context for the hooks to function correctly.
* @see {@link KeybanAccount}
* @see {@link PaginationArgs}
* @see {@link PaginationExtra}
*/
declare function useKeybanAccountTokenBalances(account: KeybanAccount, options?: PaginationArgs): ApiResult<PaginatedData<KeybanTokenBalance>, PaginationExtra>;
/**
* The `useKeybanAccountTokenBalance` React hook allows you to fetch the balance of a specific token (ERC20) owned by a Keyban account.
* It provides detailed information about the token, including metadata and collection details, offering a reactive and easy-to-use interface within functional components.
* @param account - The Keyban account object containing the address.
* @param tokenAddress - The address of the token contract.
* @returns - The result containing the token balance or an error.
*/
declare function useKeybanAccountTokenBalance(account: KeybanAccount, tokenAddress: Address): ApiResult<KeybanTokenBalance>;
/**
* Returns an {@link ApiResult} of the NFTs of an account.
*
* The `useKeybanAccountNfts` React hook allows you to fetch and subscribe to the list of all NFTs (both ERC721 and ERC1155) owned by a specific Keyban account. It supports pagination, enabling efficient retrieval of large NFT collections by fetching data in manageable chunks. This hook returns an `ApiResult` tuple containing the paginated NFT data, any potential errors, and additional pagination controls.
* @param account - A Keyban account object.
* @param [options] - Optional pagination arguments for fetching the NFTs.
* @returns - The result containing paginated NFT balances or an error, along with pagination controls.
* @throws {SdkError} If the provided account has an invalid address (`SdkErrorTypes.AddressInvalid`).
* @throws {SdkError} If no NFTs are found for the provided account (`SdkErrorTypes.NftNotFound`).
* @example
* ```tsx
* import React from 'react';
* import { useKeybanAccount, useKeybanAccountNfts } from "@keyban/sdk-react";
*
* const NftsList: React.FC = () => {
* const [account, accountError] = useKeybanAccount();
*
* if (accountError) {
* return <div>Error fetching account: {accountError.message}</div>;
* }
*
* const [nfts, nftsError, { fetchMore, loading }] = useKeybanAccountNfts(account, { first: 5 });
*
* if (nftsError) {
* return <div>Error fetching NFTs: {nftsError.message}</div>;
* }
*
* if (!nfts) {
* return <div>Loading NFTs...</div>;
* }
*
* return (
* <div>
* <h3>Your NFTs</h3>
* <ul>
* {nfts.nodes.map((nft) => (
* <li key={nft.id}>
* <p>NFT ID: {nft.id}</p>
* {nft.nft && (
* <>
* <p>Collection: {nft.nft.collection?.name || "Unknown"}</p>
* <p>Symbol: {nft.nft.collection?.symbol || "N/A"}</p>
* <p>Token ID: {nft.nft.tokenId}</p>
* // Render additional metadata as needed
* </>
* )}
* </li>
* ))}
* </ul>
* {nfts.hasNextPage && (
* <button onClick={fetchMore} disabled={loading}>
* {loading ? 'Loading...' : 'Load More'}
* </button>
* )}
* </div>
* );
* };
*
* export default NftsList;
* ```
* @remarks
* - **Pagination Support:** Utilize the {@link PaginationArgs} to control the number of NFTs fetched per request and to navigate through pages using cursors.
* - **Real-Time Updates:** The hook subscribes to changes in the NFT balances, ensuring that your UI reflects the latest data without manual refreshes.
* - **Error Handling:** Always check for errors returned by the hook to provide informative feedback to the user and handle different error scenarios gracefully.
* - **Context Requirement:** Ensure that your component is wrapped within a `KeybanProvider` to provide the necessary context for the hooks to function correctly.
* @see {@link KeybanAccount}
* @see {@link PaginationArgs}
* @see {@link PaginationExtra}
*/
declare function useKeybanAccountNfts(account: KeybanAccount, options?: PaginationArgs): ApiResult<PaginatedData<KeybanNftBalance>, PaginationExtra>;
/**
* The `useKeybanAccountNft` React hook allows you to fetch the balance of a specific NFT (ERC721 or ERC1155) owned by a Keyban account. It provides detailed information about the NFT, including metadata and collection details, offering a reactive and easy-to-use interface within functional components.
* @param account - The Keyban account object containing the address.
* @param tokenAddress - The address of the token contract.
* @param tokenId - The ID of the token.
* @returns - The result containing the NFT balance or an error.
* @throws {SdkError} If the NFT is not found (`SdkErrorTypes.NftNotFound`).
* @example
* ```tsx
* import { useKeybanAccount, useKeybanAccountNft } from "@keyban/sdk-react";
*
* const NftDisplay: React.FC<{ tokenAddress: Address; tokenId: string }> = ({ tokenAddress, tokenId }) => {
* const [account, accountError] = useKeybanAccount();
*
* if (accountError) {
* // Handle account retrieval error
* return <div>Error fetching account: {accountError.message}</div>;
* }
*
* const [nftBalance, nftError] = useKeybanAccountNft(account, tokenAddress, tokenId);
*
* if (nftError) {
* // Handle NFT retrieval error (e.g., NFT not found)
* return <div>Error fetching NFT: {nftError.message}</div>;
* }
*
* if (!nftBalance) {
* // Display a loading indicator or an appropriate message
* return <div>Loading NFT...</div>;
* }
*
* return (
* <div>
* <h3>NFT Details</h3>
* <p>NFT ID: {nftBalance.id}</p>
* {nftBalance.nft && (
* <>
* <p>Collection Name: {nftBalance.nft.collection?.name || "Unknown"}</p>
* <p>Symbol: {nftBalance.nft.collection?.symbol || "N/A"}</p>
* <p>Token ID: {nftBalance.nft.tokenId}</p>
* // Display additional metadata as needed
* </>
* )}
* </div>
* );
* };
*
* export default NftDisplay;
* ```
*/
declare function useKeybanAccountNft(account: KeybanAccount, tokenAddress: Address, tokenId: string): ApiResult<KeybanNftBalance>;
/**
* Returns an {@link ApiResult} tuple for the transfer history of an account.
*
* The `useKeybanAccountTransferHistory` hook fetches and subscribes to a paginated list
* of all asset transfers (incoming and outgoing) for a given Keyban account.
* @param account - The `KeybanAccount` object containing the user's wallet address.
* @param [options] - Pagination arguments:
* - `first?`: number of transfers to fetch initially.
* - `after?`: cursor string to fetch the next page.
* @returns
* - **0**: `PaginatedData<KeybanAssetTransfer>` — contains `nodes`, `hasNextPage`, `hasPrevPage`, `totalCount`.
* - **1**: `Error` if an error occurred during load, otherwise `null`.
* - **2**: `PaginationExtra` — `{ loading: boolean; fetchMore?: () => void }`.
* @throws {SdkError} If the provided account address is invalid (`SdkErrorTypes.AddressInvalid`).
* @throws {SdkError} If no transfer history is found (`SdkErrorTypes.TransferHistoryNotFound`).
* @example
* ```tsx
* import { useKeybanAccount, useKeybanAccountTransferHistory } from "@keyban/sdk-react";
*
* function TransferHistoryList() {
* const [account, accountError] = useKeybanAccount();
* if (accountError) throw accountError;
*
* const [history, historyError, { fetchMore, loading }] =
* useKeybanAccountTransferHistory(account, { first: 5 });
* if (historyError) throw historyError;
*
* return (
* <div>
* <h3>Your Transfer History</h3>
* <ul>
* {history.nodes.map((tx) => (
* <li key={tx.id}>
* <p>ID: {tx.id}</p>
* <p>From: {tx.fromId}</p>
* <p>To: {tx.toId}</p>
* <p>Amount: {tx.value}</p>
* <p>Date: {new Date(tx.transaction?.date!).toLocaleString()}</p>
* </li>
* ))}
* </ul>
* {history.hasNextPage && (
* <button onClick={() => fetchMore?.()} disabled={loading}>
* {loading ? "Loading…" : "Load more"}
* </button>
* )}
* </div>
* );
* }
* ```
* @remarks
* - This hook uses React Suspense via Apollo’s `useSuspenseQuery` and may suspend rendering until data is available.
* - Subscribes to real-time updates of transfers via GraphQL subscriptions.
* - Ensure your component is wrapped in a `<KeybanProvider>` and within a Suspense boundary.
* @see {@link KeybanAccount}
* @see {@link PaginationArgs}
* @see {@link PaginationExtra}
*/
declare function useKeybanAccountTransferHistory(account: KeybanAccount, options?: PaginationArgs): ApiResult<PaginatedData<KeybanAssetTransfer>, PaginationExtra>;
/**
* Returns an {@link ApiResult} tuple for the orders history of an account.
* @param account - The `KeybanAccount` object containing the user's wallet address.
* @param [options] - Pagination arguments:
* - `first?`: number of transfers to fetch initially.
* - `after?`: cursor string to fetch the next page.
* @returns
* - **0**: `PaginatedData<KeybanOrder>` — contains `nodes`, `hasNextPage`, `hasPrevPage`, `totalCount`.
* - **1**: `Error` if an error occurred during load, otherwise `null`.
* - **2**: `PaginationExtra` — `{ loading: boolean; fetchMore?: () => void }`.
*/
declare function useKeybanAccountOrders(account: KeybanAccount, options?: PaginationArgs): ApiResult<PaginatedData<KeybanOrder>, PaginationExtra>;
declare enum PromiseState {
Pending = 0,
Fulfilled = 1,
Rejected = 2
}
type PromiseResultExtra = {
refresh: () => void;
reset: () => void;
loading: boolean;
};
type PromiseResult<T> = {
[S in PromiseState]: {
readonly [PromiseState.Pending]: [null, null, PromiseResultExtra];
readonly [PromiseState.Fulfilled]: [T, null, PromiseResultExtra];
readonly [PromiseState.Rejected]: [null, Error, PromiseResultExtra];
}[S];
};
type UsePromiseResult<T, B extends boolean> = (B extends false ? PromiseResult<T>[PromiseState.Pending] : never) | PromiseResult<T>[PromiseState.Fulfilled] | PromiseResult<T>[PromiseState.Rejected];
/**
* This hook returns the status of the Keyban API.
* @private
* @returns - The promise resolving to the API status.
*/
declare function useKeybanApiStatus(): UsePromiseResult<_keyban_sdk_base.KeybanApiStatus, true>;
/**
* Represents the authentication state of the user.
*
* This type can be one of the following states:
*
* - **Unintialized**:
* - `user`: `undefined`
* - `isAuthenticated`: `undefined`
*
* - **Unauthenticated**:
* - `user`: `null`
* - `isAuthenticated`: `false`
*
* - **Authenticated**:
* - `user`: `KeybanUser`
* - `isAuthenticated`: `true`
*/
type BaseAuth = {
user: undefined;
isAuthenticated: undefined;
} | {
user: null;
isAuthenticated: false;
} | {
user: KeybanUser;
isAuthenticated: true;
};
/**
* Represents the authentication context, extending the base authentication state
* with loading status and methods for various login/logout flows.
* @property isLoading - Indicates whether an authentication operation is currently in progress.
* @property login - Initiates the login process, optionally specifying a connection type.
* @property passwordLogin - Initiates login using username and password.
* @property passwordlessStart - Initiates the passwordless login flow by sending an OTP.
* @property passwordlessLogin - Completes the passwordless login flow using the received OTP.
*/
type AuthContext = BaseAuth & {
/**
* Indicates whether an authentication operation is currently in progress.
* True while any login, logout or passwordless flow is pending.
*/
isLoading: boolean;
/**
* Initiates the login process.
* @param connection - Optional authentication connection type (e.g. "email", "sms").
* @returns A promise that resolves when login completes.
* @throws {Error} If login fails (network error or invalid credentials).
*/
login: (connection?: AuthConnection) => Promise<void>;
/**
* Logs out the current user.
* @returns A promise that resolves when logout completes.
* @throws {Error} If logout fails.
*/
logout: () => Promise<void>;
/**
* Initiates login using username and password.
* @param input -
* @returns A promise that resolves when authentication succeeds.
* @throws {Error} If credentials are invalid or login fails.
*/
passwordLogin(input: PasswordLoginInput): Promise<void>;
/**
* Initiates the passwordless login flow by sending an OTP.
* @param input -
* @returns A promise that resolves when the OTP is sent.
* @throws {Error} If sending OTP fails (invalid username or rate limit).
*/
passwordlessStart(input: PasswordlessStartInput): Promise<void>;
/**
* Completes the passwordless login flow using the received OTP.
* @param input -
* @returns A promise that resolves when authentication succeeds.
* @throws {Error} If the phone number or OTP is invalid or expired.
* - On invalid input: "Wrong phone number or verification code."
* - Backend may return other codes (e.g. expired OTP)
*/
passwordlessLogin(input: PasswordlessLoginInput): Promise<void>;
};
/**
* KeybanAuthProvider
* @param props - Component props
* @param props.children - Children
* @returns - JSX element
* @private
*/
declare function KeybanAuthProvider({ children }: React.PropsWithChildren): react_jsx_runtime.JSX.Element;
/**
* Custom hook to access the Keyban authentication context.
*
* This hook provides access to the authentication state and methods
* managed by the `KeybanProvider`. It must be called within a component
* that is a descendant of `KeybanProvider`.
* @returns The Keyban authentication context object.
* @throws {Error} If the hook is used outside of a `KeybanProvider`.
* @example
* ```tsx
* import React from 'react';
* import { useKeybanAuth } from './auth'; // Adjust the import path as needed
*
* function MyAuthenticatedComponent() {
* const { isAuthenticated, user, login, logout } = useKeybanAuth();
*
* if (!isAuthenticated) {
* return <button onClick={login}>Log In</button>;
* }
*
* return (
* <div>
* <p>Welcome, {user?.name}!</p>
* <button onClick={logout}>Log Out</button>
* </div>
* );
* }
* ```
*/
declare function useKeybanAuth(): AuthContext;
/**
* @module FormattedBalance
*/
/**
* Formats a balance in a human-readable format using the Keyban client.
* This is typically used to display the balance of an account, as retrieved by
* @param balance - The raw balance to format.
* @param token - The token details, if the balance is not native.
* @returns - The formatted balance as a string.
* @example
* ```tsx
* import { useFormattedBalance } from "@keyban/sdk-react";
*
* const formattedBalance = useFormattedBalance({raw: BigInt(2e17), isNative: true});
* console.log(formattedBalance); // "0.2 ETH"
* ```
*/
declare function useFormattedBalance(balance: Balance, token?: KeybanToken): string;
/**
* Props for the FormattedBalance component.
* @see {@link FormattedBalance}
* @property balance - The balance to be formatted and displayed.
* @property token - Optional token information associated with the balance.
*/
type FormatedBalanceProps = {
balance: Balance;
token?: KeybanToken;
};
/**
* A React component that formats and displays a balance.
* @param props - The properties for the FormattedBalance component.
* @returns A React element containing the formatted balance.
* @example
* ```tsx
* // Display a native balance in a React component
* import { useKeybanAccount, useKeybanAccountBalance, FormattedBalance } from "@keyban/sdk-react";
* const MyComponent: React.FC = () => {
* const [account, accountError] = useKeybanAccount();
* if (accountError) throw accountError;
*
* const [balance, balanceError] = useKeybanAccountBalance(account);
* if (balanceError) throw balanceError;
* return (
* <div>
* Your balance: <FormattedBalance balance={{ raw: balance, isNative: true }} />
* </div>
* );
* };
* ```
*/
declare function FormattedBalance(props: FormatedBalanceProps): string;
type ContainerProps = Pick<React.HTMLProps<HTMLDivElement>, "className" | "style">;
type InputProps = Pick<React.HTMLProps<HTMLInputElement>, "type" | "inputMode">;
type BaseProps = ContainerProps & InputProps;
/**
* Props for the KeybanInput component.
* @example
* ```tsx
* const props: KeybanInputProps = {
* name: "email",
* type: "email",
* onFocus: () => console.log("focused"),
* inputStyles: { textAlign: "center" }
* };
* ```
*/
type KeybanInputProps = BaseProps & {
/**
* The name attribute for the input, used to identify the input in form submissions.
* This is required and should be unique within the form context.
* @example "email", "password", "otp", "phone"
*/
name: string;
/**
* Callback fired when the input receives focus.
* Useful for managing form state or UI feedback.
*/
onFocus?: () => void;
/**
* Callback fired when the input loses focus.
* Useful for validation or form state management.
*/
onBlur?: () => void;
/**
* Callback fired when the input value changes.
* Note: The actual value is not accessible due to security isolation.
*/
onInput?: () => void;
/**
* Callback fired when the input change event is triggered.
* Note: The actual value is not accessible due to security isolation.
*/
onChange?: () => void;
/**
* Styling options for the input element inside the iframe.
* Limited to specific CSS properties for security reasons.
* @example
* ```tsx
* inputStyles={{
* textAlign: "center",
* fontSize: "16px",
* color: "#333"
* }}
* ```
*/
inputStyles?: Pick<{
[K in keyof React.CSSProperties]: string;
}, "colorScheme" | "backgroundColor" | "color" | "fontSize" | "textAlign">;
};
/**
* Ref interface for KeybanInput component.
* Provides imperative methods to control the input.
* @example
* ```tsx
* const inputRef = useRef<KeybanInputRef>(null);
*
* const handleButtonClick = () => {
* inputRef.current?.focus();
* };
*
* <KeybanInput ref={inputRef} name="email" />
* <button onClick={handleButtonClick}>Focus Input</button>
* ```
*/
interface KeybanInputRef {
/**
* Programmatically focus the input.
* Useful for enhancing user experience and accessibility.
*/
focus(): void;
}
/**
* KeybanInput renders a secure iframe-based input component for the Keyban SDK client.
* This component provides a secure way to handle sensitive user inputs like emails, phone numbers,
* passwords, and OTP codes by isolating them in a sandboxed iframe.
* @param props - KeybanInput props
* @returns The iframe element for SDK client input.
* @example
* **Basic email input:**
* ```tsx
* <KeybanInput
* name="email"
* type="email"
* />
* ```
* @example
* **Phone number input:**
* ```tsx
* <KeybanInput
* name="phone"
* type="tel"
* />
* ```
* @example
* **OTP code input with custom styling:**
* ```tsx
* <KeybanInput
* name="otp"
* inputMode="numeric"
* inputStyles={{ textAlign: "center" }}
* />
* ```
* @example
* **Password input:**
* ```tsx
* <KeybanInput
* name="password"
* type="password"
* />
* ```
* @example
* **Integration with Material-UI TextField:**
* ```tsx
* <TextField
* label="Email"
* variant="outlined"
* fullWidth
* slots={{
* htmlInput: () => (
* <Box
* component={KeybanInput}
* name="email"
* type="email"
* sx={{ flexGrow: 1 }}
* />
* ),
* }}
* />
* ```
* @example
* **Integration with MUI Tel Input:**
* ```tsx
* const PhoneInput = () => (
* <Box
* component={KeybanInput}
* type="tel"
* name="phone"
* sx={{ flexGrow: 1, p: 2, pl: 0 }}
* />
* );
*
* <MuiTelInput
* name="phone"
* defaultCountry="FR"
* fullWidth
* slots={{ htmlInput: PhoneInput }}
* />
* ```
* @example
* **With event handlers:**
* ```tsx
* <KeybanInput
* name="email"
* type="email"
* onFocus={() => console.log('Input focused')}
* onBlur={() => console.log('Input blurred')}
* onInput={() => console.log('Input changed')}
* />
* ```
* @example
* **Using with forwardRef for focus control:**
* ```tsx
* const inputRef = useRef<KeybanInputRef>(null);
*
* const handleFocus = () => {
* inputRef.current?.focus();
* };
*
* <KeybanInput
* ref={inputRef}
* name="email"
* type="email"
* />
* ```
* @remarks
* **Common Use Cases:**
* - **Authentication flows**: Email/password login, passwordless authentication
* - **OTP verification**: SMS or email verification codes
* - **Phone number input**: International phone numbers with country codes
* - **Secure form inputs**: Any sensitive user data that needs to be handled securely
*
* **Integration Patterns:**
* - **Standalone**: Direct usage as a form input
* - **Material-UI**: Integration with TextField using slots
* - **Custom components**: Wrapped in Box or other container components
* - **Third-party libraries**: Integration with specialized input libraries like MUI Tel Input
*
* **Security Features:**
* - **Iframe isolation**: Input is rendered in a sandboxed iframe for security
* - **Cross-origin messaging**: Secure communication between iframe and parent
* - **No direct DOM access**: Input values are not accessible from the parent context
*
* **Styling Options:**
* - **Container styling**: Use `style` and `className` props for container appearance
* - **Input styling**: Use `inputStyles` prop for iframe input appearance
* - **Theme integration**: Automatically inherits color scheme from parent document
* @see {@link KeybanInputProps} for all available props
* @see {@link KeybanInputRef} for imperative API
*/
declare const KeybanInput: React.ForwardRefExoticComponent<ContainerProps & InputProps & {
/**
* The name attribute for the input, used to identify the input in form submissions.
* This is required and should be unique within the form context.
* @example "email", "password", "otp", "phone"
*/
name: string;
/**
* Callback fired when the input receives focus.
* Useful for managing form state or UI feedback.
*/
onFocus?: () => void;
/**
* Callback fired when the input loses focus.
* Useful for validation or form state management.
*/
onBlur?: () => void;
/**
* Callback fired when the input value changes.
* Note: The actual value is not accessible due to security isolation.
*/
onInput?: () => void;
/**
* Callback fired when the input change event is triggered.
* Note: The actual value is not accessible due to security isolation.
*/
onChange?: () => void;
/**
* Styling options for the input element inside the iframe.
* Limited to specific CSS properties for security reasons.
* @example
* ```tsx
* inputStyles={{
* textAlign: "center",
* fontSize: "16px",
* color: "#333"
* }}
* ```
*/
inputStyles?: Pick<{ [K in keyof React.CSSProperties]: string; }, "colorScheme" | "backgroundColor" | "color" | "fontSize" | "textAlign">;
} & React.RefAttributes<KeybanInputRef>>;
/**
* Defines the properties for the KeybanProvider component.
*
* Includes the Keyban client configuration and supports React children.
* @see {@link KeybanClientConfig} for the available configuration options.
*/
type KeybanProviderProps = React.PropsWithChildren<KeybanClientConfig>;
/**
* Provider component for the Keyban SDK.
* This component wraps the application and provides Keyban SDK functionalities
* to the components within the application. It is responsible for configuring
* the Keyban client with the appropriate options and ensuring that the SDK is
* accessible via the `useKeybanClient` hook.
*
* The configuration options for the Keyban SDK are specified via the {@link KeybanClientConfig}
* type, which includes settings such as the API URL, blockchain network (`chain`), signing algorithm
* (`signer`), and storage mechanism (`storage`).
*
* The provider supports dynamic updates to certain configuration options, such as `chain`,
* allowing components to adjust the blockchain network or other configurations during the
* application's lifecycle.
*
* Additionally, the `clientShareProvider` prop allows for the injection of a client share provider function.
* This function is used to cipher the client's share of the end user and is stored securely within Keyban's infrastructure.
* By utilizing this, Keyban as the server and client share cannot sign operations on behalf of the end users.
* We recommend providing a unique key per client share to enhance security.
*
* You can use a custom implementation of a `ClientShareProvider` or the provided `KeybanClientShareProvider`.
* @param props - The Keyban provider configuration options.
* @throws {Error} If the configuration is invalid.
* @returns - The provider component wrapping the children components.
* @see {@link KeybanClientConfig} for the available configuration options.
* @see {@link ClientShareProvider} for managing shared keys in client-side operations.
* @example
* ```tsx
* import React from "react";
* import { KeybanProvider, KeybanNetwork } from "@keyban/sdk-react";
* import { MyClientShareProvider } from './ClientShareProvider';
* import { KeybanClientShareProvider } from '@keyban/sdk-base';
*
* const App: React.FC = () => {
*
* return (
* <KeybanProvider
* appId="your-app-id" // Your unique application ID from Keyban
* network={KeybanNetwork.EthereumAnvil} // Specify the blockchain network (e.g., Testnet or Mainnet)
* clientShareProvider={new MyClientShareProvider()} // Custom provider for client shares
* >
* <YourMainComponent />
* </KeybanProvider>
* );
* };
*
* const AppWithKeybanClientShareProvider: React.FC = () => {
*
* return (
* <KeybanProvider
* appId="your-app-id" // Your unique application ID from Keyban
* network={KeybanNetwork.EthereumAnvil} // Specify the blockchain network (e.g., Testnet or Mainnet)
* clientShareProvider={React.useMemo(() => new KeybanClientShareProvider(), [])} // Using KeybanClientShareProvider
* >
* <YourMainComponent />
* </KeybanProvider>
* );
* };
*
* export default App;
* ```
*/
declare function KeybanProvider(props: KeybanProviderProps): react_jsx_runtime.JSX.Element;
/**
* Hook to access the Keyban SDK functionalities within a React component.
*
* The `useKeybanClient` hook allows you to access the initialized Keyban client,
* enabling direct interaction with the SDK from functional React components. This hook
* ensures that the Keyban client is available within the application's context and allows
* you to utilize features such as account management, transactions, and blockchain queries.
* @returns - The initialized Keyban client.
* @throws {Error} If the hook is used outside of a {@link KeybanProvider}, indicating that
* the context is not properly configured to provide the Keyban client.
* @example
* ```tsx
* import React from 'react';
* import { useKeybanClient } from "@keyban/sdk-react";
*
* const MyComponent: React.FC = () => {
* const keybanClient = useKeybanClient();
*
* const handleCheckStatus = async () => {
* try {
* const status = await keybanClient.apiStatus();
* console.log(`Keyban API Status: ${status}`);
* } catch (error) {
* console.error("Error checking Keyban API status:", error);
* }
* };
*
* return (
* <div>
* <button onClick={handleCheckStatus}>Check API Status</button>
* </div>
* );
* };
*
* export default MyComponent;
* ```
* @see {@link KeybanClient} For more details on the Keyban client.
* @see {@link KeybanProvider} To understand how to set up the Keyban SDK context in your application.
*/
declare const useKeybanClient: () => KeybanClient;
export { type ApiResult, type AuthContext, type BaseAuth, type FormatedBalanceProps, FormattedBalance, KeybanAuthProvider, KeybanInput, type KeybanInputProps, type KeybanInputRef, KeybanProvider, type KeybanProviderProps, type PaginatedData, type PaginationExtra, useFormattedBalance, useKeybanAccount, useKeybanAccountBalance, useKeybanAccountNft, useKeybanAccountNfts, useKeybanAccountOrders, useKeybanAccountTokenBalance, useKeybanAccountTokenBalances, useKeybanAccountTransferHistory, useKeybanApiStatus, useKeybanAuth, useKeybanClient };