### Start IdentityKit Playground Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/local-playground Execute this command in the project directory to install dependencies and launch the local playground environment. ```bash npm i && npm run playground ``` -------------------------------- ### Install IdentityKit with bun Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Install the core IdentityKit library using bun. ```bash bun add @nfid/identitykit ``` -------------------------------- ### Install IdentityKit with npm Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Install the core IdentityKit library using npm. ```bash npm i @nfid/identitykit ``` -------------------------------- ### Install IdentityKit with yarn Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Install the core IdentityKit library using yarn. ```bash yarn add @nfid/identitykit ``` -------------------------------- ### Install IdentityKit with pnpm Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Install the core IdentityKit library using pnpm. ```bash pnpm add @nfid/identitykit ``` -------------------------------- ### Install Peer Dependencies with bun Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Install necessary peer dependencies for IdentityKit using bun. ```bash bun add @dfinity/ledger-icp @dfinity/identity @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils @dfinity/auth-client ``` -------------------------------- ### Install Peer Dependencies with npm Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Install necessary peer dependencies for IdentityKit using npm. ```bash npm i @dfinity/ledger-icp @dfinity/identity @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils @dfinity/auth-client ``` -------------------------------- ### Initialize IdentityKitProvider Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/signers-list Basic setup for the IdentityKitProvider component in a React application. ```javascript import { IdentityKitProvider } from "@nfid/identitykit/react" export const App = () => ( ) ``` -------------------------------- ### Install Peer Dependencies with yarn Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Install necessary peer dependencies for IdentityKit using yarn. ```bash yarn add @dfinity/ledger-icp @dfinity/identity @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils @dfinity/auth-client ``` -------------------------------- ### Basic IdentityKitProvider and ConnectWallet Setup Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/connect-wallet Use IdentityKitProvider to wrap your app and pass connection callbacks. Then, render the ConnectWallet component for a default connect/disconnect button. ```javascript import { IdentityKitProvider, ConnectWallet } from "@nfid/identitykit/react" export const YourApp = () => { return {}} onConnectSuccess={() => {}} onDisconnect={() => {}} > ; }; ``` -------------------------------- ### Install Peer Dependencies with pnpm Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Install necessary peer dependencies for IdentityKit using pnpm. ```bash pnpm add @dfinity/ledger-icp @dfinity/identity @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils @dfinity/auth-client ``` -------------------------------- ### Get IdentityKit Agent with useAgent Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useAgent Import and use the useAgent hook to obtain the IdentityKit agent. The agent is undefined until the user is connected. ```javascript import { useAgent } from "@nfid/identitykit/react" const agent = useAgent() ``` -------------------------------- ### Get IdentityKit Agent with Custom Options Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useAgent Configure the useAgent hook with custom options such as retry times and host. If no custom configuration is provided, the agent defaults to https://ic0.app or a relevant boundary node. ```javascript import { useAgent } from "@nfid/identitykit/react" const agent = useAgent({ retryTimes: 1, host: "https://my-custom-host.ic0.app" }) ``` -------------------------------- ### Import and Use useAccounts Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useAccounts Import the useAccounts hook from '@nfid/identitykit/react' and call it to get the connected accounts. This hook is only effective when IdentityKitAuthType.ACCOUNTS is set and the user is connected. ```javascript import { useAccounts } from "@nfid/identitykit/react" const accounts = useAccounts() ``` -------------------------------- ### Set ACCOUNTS authType for IdentityKitProvider Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/authenticating-accounts Configure the IdentityKitProvider with `IdentityKitAuthType.ACCOUNTS` to enable explicit user approval for authenticated transactions. This setup is required before executing canister calls. ```javascript const App = () => { return ( ) } ``` -------------------------------- ### Import and Use useDelegationType Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useDelegationType Import the useDelegationType hook from the @nfid/identitykit/react package and call it to get the delegation type. ```javascript import { useDelegationType } from "@nfid/identitykit/react" const delegationType = useDelegationType() ``` -------------------------------- ### Folder Structure for Custom Domain Configuration Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/configuring-custom-domains Illustrates the expected folder structure for configuring custom domains, including the placement of `ic-domains` and `ii-alternative-origins` files within the `.well-known` directory. ```text // your folder structure should look like this ├── dfx.json ├── path │ ├── to │ │ ├── frontend │ │ │ ├── .ic-assets.json │ │ │ ├── .well-known │ │ │ │ ├── ii-alternative-origins │ │ │ │ └── ic-domains ``` -------------------------------- ### Add Wallet Signer Configuration Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/adding-a-new-signer-to-identity-kit Configure your wallet by adding its details to the `signers.ts` file. Ensure all fields like id, description, providerUrl, transportType, label, and icon are correctly populated. ```typescript const YourWalletSigner: SignerConfig = { id: "YourWalletSignerIdentifier", description: "Your wallet description.", providerUrl: "https://your-wallet-rpc-url.com", transportType: TransportType.NEW_TAB, label: "Your Wallet Name", icon: "data:image/svg+xml;base64,PHN2ZyB3aWR0ac+Cg==", } ``` -------------------------------- ### Add Custom Domains to ic-domains File Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/configuring-custom-domains List your custom domains in the `ic-domains` file located in the `.well-known` directory. Ensure this file has no extension. ```text yourcustomdomain.com yourothercustomdomain.com ``` -------------------------------- ### Configure signerClientOptions Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/advanced-options Initializes the IdentityKitProvider with custom signer client options. ```typescript import { IdentityKitProvider } from "@nfid/identitykit/react" export const YourApp = () => { return ( ) } ``` -------------------------------- ### Set Up Authenticated and Unauthenticated Agents Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/executing-canister-calls Use an unauthenticated agent for calls that do not require user execution. Use the useAgent hook for authenticated calls, which may trigger wallet approval pop-ups. ```javascript import { useAgent } from "@nfid/identitykit/react" import { HttpAgent } from "@dfinity/agent" import { useEffect } from "react" const ICP_API_HOST = "https://icp-api.io/" // Use an unauthenticatedAgent (aka anonymous agent) // when the user doesn't need to execute the call themselves. const [unauthenticatedAgent, setUnauthenticatedAgent] = useState() useEffect(() => { HttpAgent.create({ host: ICP_API_HOST }).then(setUnauthenticatedAgent) }, []) // Use an authenticatedAgent when making authenticated calls. // A wallet approval pop-up will be displayed if necessary. const authenticatedAgent = useAgent() ``` -------------------------------- ### Customizing ConnectWalletDropdownMenu Structure Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/connect-wallet Build a custom dropdown menu using provided components like ConnectWalletDropdownMenuButton, ConnectWalletDropdownMenuItems, and ConnectWalletDropdownMenuItem. This allows reordering, changing, or adding menu items. ```javascript function DropdownMenu({ connectedAccount, icpBalance, disconnect }: ConnectWalletDropdownMenuProps) { return ( // or to make your own component for connected state and trigger dropdown on click Your custom menu item ) } ``` -------------------------------- ### useInitializing Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useIsInitializing The `useInitializing` hook returns a boolean value indicating whether the identity kit is initializing for the connected user on page reload. While initializing, wallet connection UI elements will be disabled. ```APIDOC ## useInitializing Hook ### Description Provides a boolean value representing whether the identity kit has initialized for the connected user on page reload. Wallet connection will be disabled until initialization is complete. ### Usage ```javascript import { useInitializing } from "@nfid/identitykit/react" const isInitializing = useInitializing() ``` ### Return Value - **isInitializing** (boolean) - `true` if the identity kit is currently initializing, `false` otherwise. ``` -------------------------------- ### Creating a Custom ConnectWalletButton Component Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/connect-wallet Develop a custom component for the connect button. It can accept an onClick prop to trigger the signer's modal and include additional elements like images. ```javascript function ConnectWalletButton({ onClick, ...props }: ConnectWalletButtonProps) { return (
// for example add some image etc.
) } ``` -------------------------------- ### Add ConnectWallet Button to Your App Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Import and render the ConnectWallet component from IdentityKit to allow users to connect their wallets. ```javascript import { ConnectWallet } from "@nfid/identitykit/react" export const YourApp = () => { return ; }; ``` -------------------------------- ### Configure Custom Signers List Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/signers-list Override the default wallet order by providing a custom array of signers to the signers prop. ```javascript import { IdentityKitProvider } from "@nfid/identitykit/react" import { NFIDW, InternetIdentity, Stoic, OISY } from "@nfid/identitykit" export const App = () => ( ) ``` -------------------------------- ### Configure .ic-assets.json for Static Assets Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/deploying-to-production Add this configuration to your project's .ic-assets.json file to manage static assets, particularly for the .well-known directory. It specifies how to handle requests for these assets, including CORS headers. ```json ;[ { match: ".well-known", ignore: false, }, { match: ".well-known/ii-alternative-origins", headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", }, ignore: false, }, ] ``` -------------------------------- ### Clone IdentityKit Repository Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/adding-a-new-signer-to-identity-kit Use this command to clone the IdentityKit repository to your local machine before making any changes. ```bash git clone https://github.com/internet-identity-labs/identitykit.git ``` -------------------------------- ### Configure IdentityKitProvider with derivationOrigin Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/deploying-to-production Integrate IdentityKitProvider into your React application and set the derivationOrigin in signerClientOptions. This ensures users authenticate against a stable origin, even if your frontend URL changes. ```jsx import { IdentityKitProvider, IdentityKitTheme } from "@nfid/identitykit/react" import { NFIDW } from "@nfid/identitykit" const App = () => { return ( ) } ``` -------------------------------- ### Import and Use useBalance Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useBalance Import the useBalance hook from the @nfid/identitykit/react package. Both balance and fetchBalance will be undefined until a successful connection is established. ```javascript import { useBalance } from "@nfid/identitykit/react" const { balance, fetchBalance } = useBalance() ``` -------------------------------- ### Configure IdentityKitProvider with Delegation Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Wrap your application with IdentityKitProvider, setting authType to DELEGATION and providing your backend canister IDs. ```javascript const App = () => { return ( ) } ``` -------------------------------- ### Using the useSigner Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useSigner Basic implementation of the useSigner hook within a React component. ```javascript import { useSigner } from "@nfid/identitykit/react" const signer = useSigner() ``` -------------------------------- ### Import and Use useInitializing Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useIsInitializing Import the useInitializing hook from the @nfid/identitykit/react package. This hook returns a boolean indicating the initialization status. ```javascript import { useInitializing } from "@nfid/identitykit/react" const isInitializing = useInitializing() ``` -------------------------------- ### Create Actors for Canister Calls Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/executing-canister-calls Create actors using imported idlFactories and canister IDs. Use the unauthenticated agent for calls that do not require authentication and will not prompt for wallet approval. Use the authenticated agent for calls that require authentication and may prompt for approval. ```javascript // Actor for methods the user DOES NOT need to be authenticated to call (i.e. icrc2_allowance). // These will never result in a wallet approval prompt. const nonTargetUnauthenticatedActor = unauthenticatedAgent && Actor.createActor(nontargetIdlFactory, { agent: unauthenticatedAgent, canisterId: NON_TARGET_CANISTER_ID_TO_CALL, }) // Actor for methods the user DOES need to be authenticated to call (i.e. icrc2_approve). // These may result in a wallet approval prompt depending on how the user authenticated. // Will be undefined until user is not connected or IdentityKitAgent is being created. const authenticatedActor = useMemo(() => { return ( authenticatedAgent && // or nonTargetIdlFactory Actor.createActor(targetIdlFactory, { agent: authenticatedAgent, canisterId: TARGET_CANISTER_ID_TO_CALL, // or NON_TARGET_CANISTER_ID_TO_CALL }) ) }, [identityKitAgent, targetIdlFactory]) ``` -------------------------------- ### Import idlFactories for Canister Calls Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/executing-canister-calls Import the idlFactory for your target canister and any other canisters (e.g., ICRC-1 token ledger) you intend to call. ```javascript // import the idlFactory for your canister that implements icrc28_trusted_origins import { idlFactory as targetIdlFactory } from "/path/to/target/did.js" // import the idlFactory of another canister (i.e. ICRC-1 token ledger) import { idlFactory as nonTargetIdlFactory } from "/path/to/nontarget/did.js" ``` -------------------------------- ### Import IdentityKit Styles and Provider Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Import the necessary CSS styles and the IdentityKitProvider component for your React application. ```javascript import "@nfid/identitykit/react/styles.css" import { IdentityKitProvider } from "@nfid/identitykit/react" ``` -------------------------------- ### Configure Alternative Origins in ii-alternative-origins Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/configuring-custom-domains Update the `ii-alternative-origins` file with your custom domains to allow them as alternative origins for your ICP canister. Include both the canister ID and raw URLs. ```json { "alternativeOrigins": [ "https://your-canister-id.icp0.io", "https://your-canister-id.raw.icp0.io", "https://your-canister-id.ic0.app", "https://your-canister-id.raw.ic0.app", "https://your-canister-id.icp0.icp-api.io", "https://your-canister-id.icp-api.io", "https://yourcustomdomain.com", "https://yourothercustomdomain.com" ] } ``` -------------------------------- ### Configure IdentityKit for Account Delegations Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/miscellaneous/auth-options Use the DELEGATION authType with a targets list to enable automatic transaction execution for specific canisters. ```javascript const App = () => { return ( ); }; ``` -------------------------------- ### Configure idleOptions Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/advanced-options Sets idle options within signerClientOptions to manage user inactivity timeouts. ```typescript import { IdentityKitProvider } from "@nfid/identitykit/react" export const YourApp = () => { return ( ) } ``` -------------------------------- ### Customizing ConnectWallet Components Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/connect-wallet Replace default components within ConnectWallet by passing custom components to its props. Ensure your app is wrapped in necessary providers. ```javascript import { ConnectWalletButton, ConnectedWalletButton, ConnectWalletDropdownMenu, } from "@nfid/identitykit/react" export const YourApp = () => { return ( ) } ``` -------------------------------- ### Import useIdentityKit Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useIdentityKit Import the useIdentityKit hook from the @nfid/identitykit/react package. This is the first step to using the hook in your React components. ```javascript import { useIdentityKit } from "@nfid/identitykit/react" ``` -------------------------------- ### IdentityKitProvider Configuration Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/advanced-options Configuration options for the IdentityKitProvider component to manage authentication types and signer client settings. ```APIDOC ## IdentityKitProvider Configuration ### Description Configure the IdentityKitProvider to control authentication types, signer client options, and session idle behavior. ### Parameters #### Request Body - **authType** (IdentityKitAuthType | {[signerId:string]: IdentityKitAuthType}) - Optional - Defines the authentication strategy (DELEGATION or ACCOUNTS) for signers. - **signerClientOptions** (object) - Optional - Configuration for the underlying signer client. - **maxTimeToLive** (bigint) - Optional - Delegation expiration in nanoseconds (default: 30 minutes). - **storage** (AuthClientStorage) - Optional - Custom storage implementation (default: IndexedDB). - **keyType** ("ECDSA" | "Ed25519") - Optional - Key type for storage (default: Ed25519). - **identity** (SignIdentity | PartialIdentity) - Optional - Base identity to use. - **idleOptions** (object) - Optional - Configuration for inactivity timeouts. - **idleTimeout** (number) - Optional - Timeout in milliseconds (default: 4 hours). - **disableIdle** (boolean) - Optional - Whether to disable idle logout (default: enabled). - **crypto** (object) - Optional - Custom crypto implementation for random bytes. - **window** (Window) - Optional - Custom window object for message events. - **windowOpenerFeatures** (string) - Optional - Comma-separated window features for signers. - **allowInternetIdentityPinAuthentication** (boolean) - Optional - Enable PIN-based authentication for Internet Identity. ### Request Example ``` -------------------------------- ### Register Custom Domain with ICP Boundary Nodes Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/configuring-custom-domains Use `curl` to register your custom domain with the ICP boundary nodes. Replace `CUSTOM_DOMAIN` with your actual domain name. This command sends a POST request with the domain name in JSON format. ```bash curl -sLv -X POST \ -H 'Content-Type: application/json' \ https://icp0.io/registrations \ --data @- < { return ( ) } ``` -------------------------------- ### Configure IdentityKit for Accounts Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/miscellaneous/auth-options Use the ACCOUNTS authType to require explicit user approval for every canister call. ```javascript const App = () => { return ( ) } ``` -------------------------------- ### Define Alternative Origins for Canister Access Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/deploying-to-production Create the ii-alternative-origins file to list all possible URLs users might use to access your application. This is crucial for ensuring consistent authentication across different access points. ```json { "alternativeOrigins": [ "https://your-canister-id.icp0.io", "https://your-canister-id.raw.icp0.io", "https://your-canister-id.ic0.app", "https://your-canister-id.raw.ic0.app", "https://your-canister-id.icp0.icp-api.io", "https://your-canister-id.icp-api.io" ] } ``` -------------------------------- ### useAuth Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useAuth The useAuth hook allows developers to manage user authentication, including connecting to wallets, disconnecting, and accessing user principal information. ```APIDOC ## useAuth Hook ### Description A React hook used for connection, disconnection, and accessing user data within the NFID IdentityKit ecosystem. ### Usage ```javascript import { useAuth } from "@nfid/identitykit/react" const { connect, disconnect, isConnecting, user } = useAuth() ``` ### Return Values - **user** ({ principal: Principal, subaccount?: SubAccount } | undefined) - Currently connected user principal and subaccount. Returns undefined until a successful connection. - **isConnecting** (boolean) - Indicates whether the user is currently in the process of connecting. - **connect** ((signerIdOrUrl?: string) => Promise) - Triggers the connection flow. Opens the wallet modal if no argument is provided, or attempts to connect to a specific signer if an ID or URL is provided. Throws an error if IdentityKit is not initialized. - **disconnect** (() => Promise) - Triggers a manual disconnection of the current user session. ``` -------------------------------- ### Connect Function Usage Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useAuth The connect function triggers the wallet connection modal. It can optionally accept a signer ID or URL to pre-select a signer or open a specific signer URL. Ensure IdentityKit is initialized before calling this function to avoid errors. ```javascript connect ``` -------------------------------- ### Custom ConnectedWalletButton with Account and Balance Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/connect-wallet Create a custom button for the connected state that displays the connected account address and ICP balance. It accepts standard button props and specific account/balance data. ```javascript function CustomConnectedWalletButton({ connectedAccount, icpBalance, ...props }: ConnectedWalletButtonProps) { return ( {`Disconnect ${connectedAccount} ${icpBalance} ICP`} ) } ``` -------------------------------- ### useBalance Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useBalance The useBalance hook provides the current user's balance and a function to manually trigger a balance refresh. ```APIDOC ## useBalance ### Description Retrieves the balance of the currently connected user and provides a function to refetch the balance data. ### Return Value - **balance** (number | undefined) - The current balance of the user. Returns undefined until a successful connection is established. - **fetchBalance** (() => Promise | undefined) - A function to trigger a balance update. Returns undefined until a successful connection is established. ### Usage Example ```javascript import { useBalance } from "@nfid/identitykit/react" const { balance, fetchBalance } = useBalance() ``` ``` -------------------------------- ### useIdentityKit Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useIdentityKit A hook for managing user connection state, identity, and wallet interactions. Note: This hook is deprecated. ```APIDOC ## useIdentityKit ### Description Provides access to the currently connected user, wallet address, balance, and connection controls. This hook is deprecated; use specific hooks for individual data points for better performance. ### Import ```javascript import { useIdentityKit } from "@nfid/identitykit/react" ``` ### Return Values - **isInitializing** (boolean) - Indicates if IdentityKit is initializing on page reload. - **user** ({ principal: Principal, subaccount?: SubAccount } | undefined) - Currently connected user principal and subaccount. - **isUserConnecting** (boolean) - Indicates if the user is currently in the process of connecting. - **icpBalance** (number | undefined) - The ICP balance of the connected user. - **signer** (Signer | undefined) - The selected signer. - **identity** (Identity | PartialIdentity | undefined) - The DFINITY identity if using DELEGATION auth type. - **delegationType** (IdentityKitDelegationType) - The type of delegation (ACCOUNT or RELYING_PARTY). - **accounts** (Array<{ principal: Principal, subaccount?: SubAccount }> | undefined) - List of connected accounts if using ACCOUNTS auth type. - **connect** ((signerIdOrUrl?: string) => void) - Function to trigger the connect wallet modal. - **disconnect** (() => Promise) - Function to manually disconnect the user. - **fetchIcpBalance** (() => Promise | undefined) - Function to manually refresh the user's ICP balance. ### Usage Example ```javascript const { isInitializing, user, connect, disconnect } = useIdentityKit(); ``` ``` -------------------------------- ### Initiate an ICP Transfer Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/request-transfer Uses the current agent to create an actor for the ICP ledger and executes a transfer to a specified destination principal. ```javascript // agent will know which is the currently connected wallet const agent = useAgent() // you'll need to import the idlFactory for ICP (or any other ledger canister) // and specify which canister you're calling, in this case the ICP ledger. // note: it would be very helpful to have a common 'ICRCledgerFactory' // so individual ledger canister idl's don't need to be imported. const actor = Actor.createActor(idlFactory, { agent, canisterId: "ryjl3-tyaaa-aaaaa-aaaba-cai", }) const destinationPrincipal = SOME_DESTINATION_PRINCIPAL const address = AccountIdentifier.fromPrincipal({ principal: Principal.fromText(destinationPrincipal), }).toHex() const transferArgs = { to: fromHexString(address), fee: { e8s: BigInt(10000) }, memo: BigInt(0), from_subaccount: [], created_at_time: [], amount: { e8s: BigInt(1000) }, } const response = await actor.transfer(transferArgs) ``` -------------------------------- ### Connect Function Usage with Signer ID Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useIdentityKit The connect function can be called with an optional signerIdOrUrl. If provided, it attempts to open the specified signer; otherwise, it opens the default connect wallet modal. Ensure the identity kit is initialized before calling this function to avoid errors. ```javascript connect(signerIdOrUrl?: string) => void ``` -------------------------------- ### Implement ICRC-10 and ICRC-28 Canister Functions Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Add these functions to your backend canisters to support on-chain wallet interactions and trusted origins. ```rust use candid::{self, CandidType, Deserialize}; #[derive(CandidType, Deserialize, Eq, PartialEq, Debug)] pub struct SupportedStandard { pub url: String, pub name: String, } #[query] fn icrc10_supported_standards() -> Vec { vec![ SupportedStandard { url: "https://github.com/dfinity/ICRC/blob/main/ICRCs/ICRC-10/ICRC-10.md".to_string(), name: "ICRC-10".to_string(), }, SupportedStandard { url: "https://github.com/dfinity/wg-identity-authentication/blob/main/topics/icrc_28_trusted_origins.md".to_string(), name: "ICRC-28".to_string(), }, ] } #[derive(Clone, Debug, CandidType, Deserialize)] pub struct Icrc28TrustedOriginsResponse { pub trusted_origins: Vec } // list every base URL that users will authenticate to your app from #[update] fn icrc28_trusted_origins() -> Icrc28TrustedOriginsResponse { let trusted_origins = vec![ String::from("https://your-frontend-canister-id.icp0.io"), String::from("https://your-frontend-canister-id.raw.icp0.io"), String::from("https://your-frontend-canister-id.ic0.app"), String::from("https://your-frontend-canister-id.raw.ic0.app"), String::from("https://your-frontend-canister-id.icp0.icp-api.io"), String::from("https://your-frontend-canister-id.icp-api.io"), String::from("https://yourcustomdomain.com"), String::from("https://yourothercustomdomain.com") ]; return Icrc28TrustedOriginsResponse { trusted_origins } } ``` -------------------------------- ### Customizing ConnectWalletButton Text Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/connect-wallet Set custom text for the ConnectWalletButton by passing children to it. The default text is 'Connect wallet'. ```javascript Sign in ``` -------------------------------- ### Configure TypeScript Module Resolution Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/installation Ensure your tsconfig.json has module set to 'node16' or 'nodenext' for compatibility. ```json { "compilerOptions": { "module": "node16", // or "moduleResolution": "node16" } } ``` -------------------------------- ### Apply a theme to IdentityKitProvider Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/theming Pass an IdentityKitTheme value to the theme prop of the IdentityKitProvider component to set the visual style. ```typescript import { IdentityKitProvider } from "@nfid/identitykit/react" import { IdentityKitTheme } from "@nfid/identitykit/react" export const App = () => ( ) ``` -------------------------------- ### Fetch ICP Balance Function Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useIdentityKit The fetchIcpBalance function allows for manually refreshing the ICP balance of the connected user. This function is only available if the user is connected; otherwise, it will be undefined. ```javascript fetchIcpBalance: () => Promise | undefined ``` -------------------------------- ### Customizing ConnectWalletButton ClassName Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/connect-wallet Apply custom CSS classes to the ConnectWalletButton using the className prop for styling, such as changing the background color. ```javascript Sign in ``` -------------------------------- ### Execute Canister Calls Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/executing-canister-calls Execute your canister calls using the created actor. Ensure the actor is defined before attempting to call a method. ```javascript if (actor) { const result = await actor.{yourmethod} } ``` -------------------------------- ### useAccounts Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useAccounts Retrieves the list of connected accounts for the authenticated user. ```APIDOC ## useAccounts ### Description Returns the connected accounts if `IdentityKitProvider.authType` is set to `IdentityKitAuthType.ACCOUNTS` and the user is connected. Otherwise, it returns `undefined`. ### Signature `() => ({ principal: Principal, subaccount?: SubAccount}[] | undefined)` ### Usage Example ```javascript import { useAccounts } from "@nfid/identitykit/react" const accounts = useAccounts() ``` ``` -------------------------------- ### Configure Featured Signer in IdentityKitProvider Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/featured-signer Sets a specific signer as the featured option in the IdentityKit modal. ```typescript import { IdentityKitProvider } from "@nfid/identitykit/react" import { NFIDW } from "@nfid/identitykit" export const App = () => ( {/* Your App */} ) ``` -------------------------------- ### Configure authType in IdentityKitProvider Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/advanced-options Sets the authentication type for signers, either globally or per-signer. Note that manual overrides will not automatically switch if the chosen authType is unsupported by the signer. ```typescript // By default authType is set to { [NFIDW.id]: IdentityKitAuthType.DELEGATION, [Plug.id]: IdentityKitAuthType.DELEGATION, [OISY.id]: IdentityKitAuthType.ACCOUNTS, // does not support icrc34_delegation [InternetIdentity.id]: IdentityKitAuthType.DELEGATION, // does not support icrc27_accounts [Stoic.id]: IdentityKitAuthType.DELEGATION // does not support icrc27_accounts } import { IdentityKitProvider } from "@nfid/identitykit/react" // authType can be set for all signers at once (the list above takes priority over this) export const YourApp = () => { return ( ) } // or custom for specific signer export const YourApp = () => { return ( ) } ``` -------------------------------- ### useAgent Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useAgent The useAgent hook retrieves an IdentityKitAgent instance, which handles identity-based canister calls and approval pop-ups. ```APIDOC ## useAgent ### Description Hook to get identityKitAgent, which manages when to show approval pop-ups to make canister calls. It uses a built-in signerAgent to show pop-ups and a dfinity HttpAgent with identity from identitykit otherwise. ### Parameters #### Options - **options** (HttpAgentOptions) - Optional - Configuration object for the HttpAgent, including properties like retryTimes and host. ### Return Values - **Agent|undefined** - The retrieved agent will be undefined until the user is connected and the agent is initialized. ### Usage Example ```javascript import { useAgent } from "@nfid/identitykit/react" const agent = useAgent({ retryTimes: 1, host: "https://my-custom-host.ic0.app" }) ``` ``` -------------------------------- ### useIdentity Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useIdentity The `useIdentity` hook provides access to the user's identity within the IdentityKit context. Its return value depends on the `authType` configuration of `IdentityKitProvider`. ```APIDOC ## useIdentity Hook ### Description The `useIdentity` hook returns the user's identity object if the `IdentityKitProvider.authType` is set to `IdentityKitAuthType.DELEGATION` and the user is successfully connected. Otherwise, it returns `undefined`. ### Signature `() => (Identity | PartialIdentity | undefined)` ### Usage ```javascript import { useIdentity } from "@nfid/identitykit/react" const identity = useIdentity() ``` ### Return Value - **Identity | PartialIdentity | undefined**: The user's identity object, a partial identity object, or undefined if not connected or using a different authType. ``` -------------------------------- ### useSigner Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useSigner The useSigner hook provides information about the currently selected signer. It returns an object containing details about the signer or undefined if no signer is selected. ```APIDOC ## useSigner Hook ### Description Provides information about the currently selected signer. ### Return Type ```typescript { id: string; // Unique identifier for the signer providerUrl: string; // URL of the provider associated with the signer label: string; // Human-readable name displayed to users transportType: TransportType; // Method used by the signer (NEW_TAB, EXTENSION, etc.) icon?: string; // Base64-encoded icon image for the signer (optional) description?: string; // Human-readable description of the signer (optional) } | undefined ``` ### Usage ```javascript import { useSigner } from "@nfid/identitykit/react"; const signer = useSigner(); ``` ``` -------------------------------- ### Accessing Identity with useIdentity Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useIdentity Retrieves the current identity object. Requires the component to be wrapped in an IdentityKitProvider. ```typescript import { useIdentity } from "@nfid/identitykit/react" const identity = useIdentity() ``` -------------------------------- ### Destructure useIdentityKit Hook Properties Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useIdentityKit Destructure the properties returned by the useIdentityKit hook to access various functionalities. These include initialization status, user details, connection states, balance, signer, identity, delegation type, accounts, and control functions like connect, disconnect, and fetchIcpBalance. ```javascript const { isInitializing, user, isUserConnecting, icpBalance, signer, identity, delegationType, accounts, connect, disconnect, fetchIcpBalance, } = useIdentityKit() ``` -------------------------------- ### Implement Permission Method Validation Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/validation-of-permission-methods Use this TypeScript code to validate incoming method names against a predefined enum. It throws an error for unsupported methods, ensuring only approved methods are processed. ```typescript export enum PermissionMethod { ICRC27_ACCOUNTS = "icrc27_accounts", ICRC34_DELEGATION = "icrc34_delegation", ICRC49_CALL_CANISTER = "icrc49_call_canister", } function getPermissionMethod(methodName: string): PermissionMethod { const method = PermissionMethod[methodName.toUpperCase() as keyof typeof PermissionMethod] if (!method) { throw new NotSupportedError(`The method name ${methodName} is not supported`) } return method } ``` -------------------------------- ### Successful Boundary Node Registration Response Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/configuring-custom-domains A successful registration with ICP boundary nodes returns a JSON object containing the request ID. ```json {"id":"REQUEST_ID"} ``` -------------------------------- ### Signer Return Type Definition Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useSigner The structure of the object returned by the useSigner hook, which is undefined until a signer is selected. ```typescript () => { id: string // Unique identifier for the signer providerUrl: string // URL of the provider associated with the signer label: string // Human-readable name displayed to users transportType: TransportType // Method used by the signer (NEW_TAB, EXTENSION, etc.) icon?: string // Base64-encoded icon image for the signer (optional) description?: string // Human-readable description of the signer (optional) } | undefined ``` -------------------------------- ### Implement ICRC-28 Trusted Origins in Rust Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/miscellaneous/target-canisters Defines the icrc28_trusted_origins update method and the required icrc10_supported_standards query method for target canisters. ```rust #[derive(CandidType, Deserialize, Eq, PartialEq, Debug)] pub struct SupportedStandard { pub url: String, pub name: String, } #[query] fn icrc10_supported_standards() -> Vec { vec![ SupportedStandard { url: "https://github.com/dfinity/ICRC/blob/main/ICRCs/ICRC-10/ICRC-10.md".to_string(), name: "ICRC-10".to_string(), }, SupportedStandard { url: "https://github.com/dfinity/wg-identity-authentication/blob/main/topics/icrc_28_trusted_origins.md".to_string(), name: "ICRC-28".to_string(), }, ] } #[derive(Clone, Debug, CandidType, Deserialize)] pub struct Icrc28TrustedOriginsResponse { pub trusted_origins: Vec } #[update] fn icrc28_trusted_origins() -> Icrc28TrustedOriginsResponse { let trusted_origins = vec![ String::from("dscvr.one") // to be replaced with application's frontend origin(s) ]; return Icrc28TrustedOriginsResponse { trusted_origins } } ``` -------------------------------- ### Disconnect Function Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useIdentityKit The disconnect function is used to manually trigger the disconnection of the user's wallet. It returns a Promise that resolves when the disconnection is complete. ```javascript disconnect: () => Promise ``` -------------------------------- ### ICRC-28 Trusted Origins API Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/miscellaneous/target-canisters This endpoint allows wallet providers to query the trusted origins for a given canister. The target canister must implement the `icrc28_trusted_origins` method. ```APIDOC ## POST /icrc28_trusted_origins ### Description Retrieves a list of trusted origins for a canister. This method is intended to be called as an update call for secure consensus. ### Method UPDATE ### Endpoint /icrc28_trusted_origins ### Parameters ### Request Body This method does not require a request body. ### Response #### Success Response (200) - **trusted_origins** (array[string]) - A list of trusted origins (URLs) for the canister. #### Response Example ```json { "trusted_origins": [ "dscvr.one" ] } ``` ``` -------------------------------- ### ICRC-10 Supported Standards API Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/miscellaneous/target-canisters This endpoint returns a list of supported standards for a canister, including ICRC-10 and ICRC-28. It's important that this list does not include standards for tradable assets. ```APIDOC ## QUERY /icrc10_supported_standards ### Description Returns a list of supported standards implemented by the canister. ### Method QUERY ### Endpoint /icrc10_supported_standards ### Parameters ### Request Body This method does not require a request body. ### Response #### Success Response (200) - **supported_standards** (array[object]) - A list of supported standards, each with a `url` and `name`. - **url** (string) - The URL pointing to the standard's documentation. - **name** (string) - The name of the standard. #### Response Example ```json { "supported_standards": [ { "url": "https://github.com/dfinity/ICRC/blob/main/ICRCs/ICRC-10/ICRC-10.md", "name": "ICRC-10" }, { "url": "https://github.com/dfinity/wg-identity-authentication/blob/main/topics/icrc_28_trusted_origins.md", "name": "ICRC-28" } ] } ``` ``` -------------------------------- ### Define Custom Signer Authentication Type Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/guides/adding-a-new-signer-to-identity-kit If your new signer does not support ICRC34 delegation, you must define a custom authentication type for it in `identity-kit.ts`. This ensures proper handling of authentication methods. ```typescript export const IdentityKitCustomSignerAuthType = { [OISY.id]: IdentityKitAuthType.ACCOUNTS, [InternetIdentity.id]: IdentityKitAuthType.DELEGATION, [Stoic.id]: IdentityKitAuthType.DELEGATION, [new_signer_id]: IdentityKitAuthType, } ``` -------------------------------- ### Exclude Specific Extension Signers Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/signers-list Filter out specific discovered signers by providing an array of objects containing their uuid or name. ```javascript import { IdentityKitProvider } from "@nfid/identitykit/react" export const App = () => ( ) ``` -------------------------------- ### Disable Automatic Extension Discovery Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/signers-list Prevent IdentityKit from automatically detecting and adding ICRC-94 compliant wallet extensions. ```javascript import { IdentityKitProvider } from "@nfid/identitykit/react" export const App = () => ( ) ``` -------------------------------- ### useDelegationType Hook Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useDelegationType The useDelegationType hook returns the current delegation type. It can be ACCOUNT, RELYING_PARTY, or undefined. ```APIDOC ## useDelegationType Hook ### Description Returns the current delegation type. It equals `IdentityKitDelegationType.ACCOUNT` if delegation has targets, `IdentityKitDelegationType.RELYING_PARTY` if delegation doesn’t have targets, and `undefined` if the user is not connected or `authType` is set to `IdentityKitAuthType.ACCOUNTS`. ### Return Value `IdentityKitDelegationType.ACCOUNT` | `IdentityKitDelegationType.RELYING_PARTY` | `undefined` ### Usage ```javascript import { useDelegationType } from "@nfid/identitykit/react" const delegationType = useDelegationType() ``` ``` -------------------------------- ### Disconnect Function Usage Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/hooks/useAuth The disconnect function is used to manually trigger the user's disconnection from the service. It returns a Promise that resolves when the disconnection is complete. ```javascript disconnect ``` -------------------------------- ### Disable Featured Signer in IdentityKitProvider Source: https://qzjsg-qiaaa-aaaam-acupa-cai.icp0.io/docs/getting-started/featured-signer Disables the featured signer feature by passing false to the featuredSigner prop. ```typescript import { IdentityKitProvider } from "@nfid/identitykit/react" export const App = () => ( {/* Your App */} ) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.