### Install IdentityKit and Dependencies Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/installation.mdx Install the core library and required peer dependencies. ```bash npm i @nfid/identitykit ``` ```bash npm i @dfinity/ledger-icp @dfinity/identity @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils @dfinity/auth-client ``` -------------------------------- ### Run IdentityKit Playground Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/local-playground.mdx Execute this command to install dependencies and start the local playground environment. ```sh npm i && npm run playground ``` -------------------------------- ### Install IdentityKit Source: https://github.com/internet-identity-labs/identitykit/blob/main/README.md Install the core library package. ```sh npm install @nfid/identitykit ``` -------------------------------- ### Example Wallet Signer Configuration Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/adding-a-new-signer-to-identity-kit.mdx An example of how to configure a new wallet signer in `packages/identitykit/src/lib/signers.ts`. Ensure all fields like id, description, providerUrl, transportType, label, and icon are correctly populated according to IdentityKit and ICRC standards. ```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==", } ``` -------------------------------- ### Install IdentityKit Dependencies Source: https://context7.com/internet-identity-labs/identitykit/llms.txt Install the core library and required peer dependencies for the Internet Computer Protocol. ```bash # Install IdentityKit npm install @nfid/identitykit # Install required peer dependencies npm install @dfinity/ledger-icp @dfinity/identity @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils @dfinity/auth-client ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/internet-identity-labs/identitykit/blob/main/README.md Install required ICP agent and identity packages. ```sh npm install @dfinity/ledger-icp @dfinity/identity @dfinity/agent @dfinity/candid @dfinity/principal @dfinity/utils @dfinity/auth-client ``` -------------------------------- ### Basic IdentityKitProvider and ConnectWallet Setup Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/connect-wallet.mdx Wrap your application with IdentityKitProvider and include the ConnectWallet component. Pass callbacks for connection success, failure, and disconnection events to the provider. ```jsx import { IdentityKitProvider, ConnectWallet } from "@nfid/identitykit/react" export const YourApp = () => { return {}} onConnectSuccess={() => {}} onDisconnect={() => {}} > ; }; ``` -------------------------------- ### DNS Entry Example for Custom Domain Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/configuring-custom-domains.mdx Provides an example of DNS records required for a custom domain. This includes CNAME and TXT records to map your domain to the Internet Computer network and verify ownership. ```plaintext | Type | Name | Content | | ----- | ---------------- | --------------------------------------------- | | CNAME | @ | icp1.io | | CNAME | _acme-challenge | _acme-challenge.yourcustomdomain.com.icp2.io | | TXT | _canister-id | 3y5ko-7qaaa-aaaal-aaaaq-cai | ``` -------------------------------- ### Initializing IdentityKitProvider with Empty Signer Client Options Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/advanced-options.mdx Shows the basic structure for initializing IdentityKitProvider with an empty signerClientOptions object. This serves as a starting point for further customization. ```jsx import { IdentityKitProvider } from "@nfid/identitykit/react" export const YourApp = () => { return ( ) } ``` -------------------------------- ### DNS Entry Example for Subdomain Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/configuring-custom-domains.mdx Shows the DNS configuration for a subdomain (e.g., app.yourcustomdomain.com). Similar to a root domain, it requires CNAME and TXT records for proper routing and verification. ```plaintext | Type | Name | Content | | ----- | -------------------- | ------------------------------------------------- | | CNAME | app | icp1.io | | CNAME | _acme-challenge.app | _acme-challenge.app.yourcustomdomain.com.icp2.io | | TXT | _canister-id | 3y5ko-7qaaa-aaaal-aaaaq-cai | ``` -------------------------------- ### Implement Custom DropdownMenu Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/connect-wallet.mdx Example of creating a custom dropdown menu structure using IdentityKit's exported sub-components. ```jsx 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 ) } ``` -------------------------------- ### Initialize IdentityKit Provider Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/signers-list.mdx Basic setup for IdentityKitProvider in your React application. Ensure this is wrapped around your app's root component. ```jsx import { IdentityKitProvider } from "@nfid/identitykit/react" export const App = () => ( ) ``` -------------------------------- ### Configuring Idle Options for Signer Client Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/advanced-options.mdx Demonstrates how to configure idleOptions within signerClientOptions to customize user inactivity timeouts. This example shows an empty configuration, implying default settings will be used. ```jsx import { IdentityKitProvider } from "@nfid/identitykit/react" export const YourApp = () => { return ( ) } ``` -------------------------------- ### Setting Up Authenticated and Unauthenticated Agents Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/executing-canister-calls.mdx Use the useAgent hook to get an authenticated agent for calls requiring user execution and wallet approval. Set up an unauthenticated agent for calls that do not require user interaction. ```typescript 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() ``` -------------------------------- ### Execute Canister Calls with Delegation Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/miscellaneous/auth-options.mdx Use the DELEGATION authType with specific targets in signerClientOptions to execute canister calls. This requires following the guide for executing canister calls. ```jsx const App = () => { return ( ); }; ``` -------------------------------- ### Validate and Get Permission Method Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/validation-of-permission-methods.mdx Implement a function to validate incoming method names against the supported enum. Throws a NotSupportedError if the method is not found. ```typescript 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 } ``` -------------------------------- ### Using useInitializing hook Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useIsInitializing.mdx Import and use the hook to determine if the identity kit is currently initializing. Connect wallet functionality remains disabled until this process completes. ```typescript import { useInitializing } from "@nfid/identitykit/react" const isInitializing = useInitializing() ``` -------------------------------- ### Disable Automatic Extension Signer Discovery Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/signers-list.mdx Set `discoverExtensionSigners` to `false` to prevent IdentityKit from automatically discovering and adding installed extension signers to the list. ```jsx import { IdentityKitProvider } from "@nfid/identitykit/react" export const App = () => ( ) ``` -------------------------------- ### Wrap Application with IdentityKitProvider Source: https://github.com/internet-identity-labs/identitykit/blob/main/README.md Enable wallet connection functionality by wrapping the application component. ```javascript import { IdentityKitProvider } from "@nfid/identitykit/react" const App = () => { return ( ) } ``` -------------------------------- ### List Custom Domains in ic-domains File Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/configuring-custom-domains.mdx Add your custom domain names to the `ic-domains` file located in the `.well-known` directory. Each domain should be on a new line. ```plaintext yourcustomdomain.com yourothercustomdomain.com ``` -------------------------------- ### Configure .ic-assets.json for origin headers Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/deploying-to-production.mdx Configuration to ensure the .well-known directory is served with correct CORS and content-type headers. ```typescript ;[ { match: ".well-known", ignore: false, }, { match: ".well-known/ii-alternative-origins", headers: { "Access-Control-Allow-Origin": "*", "Content-Type": "application/json", }, ignore: false, }, ] ``` -------------------------------- ### Import and Use useIdentity Hook Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useIdentity.mdx Import the useIdentity hook from the IdentityKit React package and call it to get the current identity. The identity will be undefined if a different authType is selected or the user is not connected. ```typescript import { useIdentity } from "@nfid/identitykit/react" const identity = useIdentity() ``` -------------------------------- ### Clone IdentityKit Repository Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/adding-a-new-signer-to-identity-kit.mdx Use this command to clone the IdentityKit repository to your local machine. This is the first step in adding a new signer. ```bash git clone https://github.com/internet-identity-labs/identitykit.git ``` -------------------------------- ### Import and Use useAccounts Hook Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useAccounts.mdx Import the useAccounts hook from the IdentityKit React library and call it to get the list of connected accounts. This hook is only effective when IdentityKitAuthType is set to ACCOUNTS and the user is authenticated. ```typescript import { useAccounts } from "@nfid/identitykit/react" const accounts = useAccounts() ``` -------------------------------- ### Project folder structure for derivation origin Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/deploying-to-production.mdx The required directory structure for hosting the .well-known configuration files. ```typescript ├── dfx.json ├── path │ ├── to │ │ ├── frontend │ │ │ ├── .ic-assets.json │ │ │ ├── .well-known │ │ │ │ └── ii-alternative-origins ``` -------------------------------- ### Get Delegation Type with useDelegationType Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useDelegationType.mdx Import and use the useDelegationType hook to determine the current delegation type. This hook returns IdentityKitDelegationType.ACCOUNT if delegation has targets, IdentityKitDelegationType.RELYING_PARTY if it does not, and undefined if the user is not connected or authType is set to IdentityKitAuthType.ACCOUNTS. ```typescript import { useDelegationType } from "@nfid/identitykit/react" const delegationType = useDelegationType() ``` -------------------------------- ### Import IdentityKit Styles and Provider Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/installation.mdx Import the required CSS and the IdentityKitProvider component. ```typescript import "@nfid/identitykit/react/styles.css" import { IdentityKitProvider } from "@nfid/identitykit/react" ``` -------------------------------- ### Import IdentityKit Styles Source: https://github.com/internet-identity-labs/identitykit/blob/main/README.md Include the required CSS styles in your project. ```javascript import "@nfid/identitykit/react/styles.css" ``` -------------------------------- ### Configure Alternative Origins in ii-alternative-origins File Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/configuring-custom-domains.mdx Specify all valid origins, including your custom domains, in the `ii-alternative-origins` JSON file. This ensures the Internet Identity service recognizes and accepts authentication requests from these domains. ```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" ] } ``` -------------------------------- ### Define ii-alternative-origins JSON Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/deploying-to-production.mdx List all potential URLs users might use to access the application to maintain consistent wallet derivation. ```typescript { "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" ] } ``` -------------------------------- ### Folder Structure for Custom Domains Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/configuring-custom-domains.mdx Illustrates the expected folder structure for integrating custom domains, ensuring the `.well-known` directory and its contents are correctly placed within your frontend assets. ```plaintext // your folder structure should look like this ├── dfx.json ├── path │ ├── to │ │ ├── frontend │ │ │ ├── .ic-assets.json │ │ │ ├── .well-known │ │ │ │ ├── ii-alternative-origins │ │ │ │ └── ic-domains ``` -------------------------------- ### Initialize useAuth hook Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useAuth.mdx Import and destructure the useAuth hook to access authentication methods and user state. ```typescript import { useAuth } from "@nfid/identitykit/react" const { connect, disconnect, isConnecting, user } = useAuth() ``` -------------------------------- ### Add ConnectWallet Component Source: https://github.com/internet-identity-labs/identitykit/blob/main/README.md Render the wallet connection button within the application. ```javascript import { ConnectWallet } from "@nfid/identitykit/react" export const YourApp = () => { return } ``` -------------------------------- ### Implement On-Chain Wallet Support Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/installation.mdx Add ICRC-10 and ICRC-28 support to your backend canisters to enable wallet authentication. ```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 } } ``` -------------------------------- ### IdentityKitProvider and ConnectWallet Integration Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/connect-wallet.mdx This snippet shows the basic integration of the ConnectWallet component within the IdentityKitProvider, including essential callbacks for connection events. ```APIDOC ## IdentityKitProvider and ConnectWallet Integration ### Description This demonstrates the fundamental setup for using the `ConnectWallet` component. It requires wrapping your application with `IdentityKitProvider` and passing callback functions for connection success, failure, and disconnection events. ### Method N/A (Component Integration) ### Endpoint N/A (Component Integration) ### Parameters #### IdentityKitProvider Props - **onConnectFailure** (function) - Optional - Callback function executed when wallet connection fails. - **onConnectSuccess** (function) - Optional - Callback function executed when wallet connection is successful. - **onDisconnect** (function) - Optional - Callback function executed when the wallet is disconnected. ### Request Example ```jsx import { IdentityKitProvider, ConnectWallet } from "@nfid/identitykit/react" export const YourApp = () => { return {}} onConnectSuccess={() => {}} onDisconnect={() => {}} > ; }; ``` ### Response N/A (Component Integration) ``` -------------------------------- ### Creating a Custom ConnectWallet Button Component Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/connect-wallet.mdx Implement a custom component for the connect wallet button. This custom component can include additional elements like images and must accept an onClick prop to trigger the modal. ```jsx function ConnectWalletButton({ onClick, ...props }: ConnectWalletButtonProps) { return (
// for example add some image etc.
) } ``` -------------------------------- ### Import useIdentityKit Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useIdentityKit.mdx Import the hook from the IdentityKit React package. ```typescript import { useIdentityKit } from "@nfid/identitykit/react" ``` -------------------------------- ### Customizing ConnectWallet Components Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/connect-wallet.mdx This snippet illustrates how to replace default components within ConnectWallet with custom ones for advanced UI customization. ```APIDOC ## Customizing ConnectWallet Components ### Description IdentityKit allows for deep customization by enabling you to provide your own React components for the connect button, connected button, and dropdown menu. This offers flexibility in tailoring the user interface to your application's design. ### Method N/A (Component Integration) ### Endpoint N/A (Component Integration) ### Parameters #### ConnectWallet Props - **connectButtonComponent** (React.Component) - Optional - A custom component to render the connect button. - **connectedButtonComponent** (React.Component) - Optional - A custom component to render the button when a wallet is connected. - **dropdownMenuComponent** (React.Component) - Optional - A custom component to render the dropdown menu. ### Request Example ```jsx import { ConnectWalletButton, ConnectedWalletButton, ConnectWalletDropdownMenu, } from "@nfid/identitykit/react" export const YourApp = () => { return ( ) } ``` ### Response N/A (Component Integration) ``` -------------------------------- ### Handle initialization error Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useAuth.mdx The connect function throws an error if called before IdentityKit is fully initialized. ```typescript Error("Identitykit is not initialized yet") ``` -------------------------------- ### Render ConnectWallet Component Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/installation.mdx Import and render the ConnectWallet component within your application. ```typescript import { ConnectWallet } from "@nfid/identitykit/react" export const YourApp = () => { return ; }; ``` -------------------------------- ### Import and Use useBalance Hook Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useBalance.mdx Import the useBalance hook from IdentityKit and destructure the balance and fetchBalance functions. Both balance and fetchBalance will be undefined until a successful connection. ```typescript import { useBalance } from "@nfid/identitykit/react" const { balance, fetchBalance } = useBalance() ``` -------------------------------- ### Configure IdentityKitProvider with derivationOrigin Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/deploying-to-production.mdx Set the derivationOrigin within signerClientOptions to ensure stable authentication origins. ```jsx import { IdentityKitProvider, IdentityKitTheme } from "@nfid/identitykit/react" import { NFIDW } from "@nfid/identitykit" const App = () => { return ( ) } ``` -------------------------------- ### Define Supported Permission Methods Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/validation-of-permission-methods.mdx Use an enum to define the supported permission methods for your wallet. This helps in type-safe handling and validation. ```typescript export enum PermissionMethod { ICRC27_ACCOUNTS = "icrc27_accounts", ICRC34_DELEGATION = "icrc34_delegation", ICRC49_CALL_CANISTER = "icrc49_call_canister", } ``` -------------------------------- ### useIdentityKit Hook Overview Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useIdentityKit.mdx This snippet shows how to import and use the useIdentityKit hook to access various identity-related states and functions. ```APIDOC ## useIdentityKit Hook ### Description The `useIdentityKit` hook provides a convenient way to access the currently connected user's information, including their wallet address (as a valid ICRC-1 Account), balance, and disconnect function. It consolidates these essential details into a single hook for ease of use. Hook is deprecated, please use separate hooks for retrieving data below for better performance ### Import ```typescript import { useIdentityKit } from "@nfid/identitykit/react" ``` ### Usage ```typescript const { isInitializing, user, isUserConnecting, icpBalance, signer, identity, delegationType, accounts, connect, disconnect, fetchIcpBalance, } = useIdentityKit() ``` ### Return Values #### isInitializing - **Type**: `boolean` - **Description**: Represents whether `identitykit` has initialized for the connected user on page reload. The 'Connect wallet' button will be disabled until initialization is complete. #### user - **Type**: `{ principal: Principal, subaccount?: SubAccount } | undefined` - **Description**: Contains the currently connected user's principal and subaccount. This will be `undefined` until a successful connection. #### isUserConnecting - **Type**: `boolean` - **Description**: Indicates whether the user is currently in the process of connecting (signer selected, but the user is not yet fully connected). #### icpBalance - **Type**: `number | undefined` - **Description**: The balance of the connected user. This will be `undefined` until a successful connection. #### signer - **Type**: `Signer | undefined` - **Description**: The selected signer. This will be `undefined` until a signer is selected. #### identity - **Type**: `Identity | PartialIdentity | undefined` - **Description**: If `IdentityKitProvider.authType` is set to `IdentityKitAuthType.DELEGATION`, this value will contain the `@dfinity` identity after a successful connection. It will be `undefined` if another `authType` is selected or if the user is not connected. #### delegationType - **Type**: `IdentityKitDelegationType.ACCOUNT | IdentityKitDelegationType.RELYING_PARTY` - **Description**: Equals `IdentityKitDelegationType.ACCOUNT` if the delegation has targets, `IdentityKitDelegationType.RELYING_PARTY` if the delegation does not have targets. It is `undefined` if the user is not connected or if `authType` is set to `IdentityKitAuthType.ACCOUNTS`. #### accounts - **Type**: `{ principal: Principal, subaccount?: SubAccount }[] | undefined` - **Description**: Contains the connected accounts if `IdentityKitProvider.authType` is set to `IdentityKitAuthType.ACCOUNTS` and the user is connected. Otherwise, it will be `undefined`. #### connect - **Type**: `(signerIdOrUrl?: string) => void` - **Description**: Triggers the opening of the connect wallet modal. If `signerIdOrUrl` is provided, it will attempt to open the signer with the specified ID or if the provided value is a valid signer URL. Function will throw `Error("Identitykit is not initialized yet")` until identitykit initializes. So make sure you disable your connect button in these cases. #### disconnect - **Type**: `() => Promise` - **Description**: Triggers a manual disconnect for the user. #### fetchIcpBalance - **Type**: `() => Promise | undefined` - **Description**: Manually fetches the ICP balance of the connected user. This function will be `undefined` if the user is not connected. ``` -------------------------------- ### Configure IdentityKitProvider Source: https://context7.com/internet-identity-labs/identitykit/llms.txt Wrap the application with the IdentityKitProvider to manage authentication types, signers, and session settings. ```jsx import "@nfid/identitykit/react/styles.css" import { IdentityKitProvider, IdentityKitAuthType, IdentityKitTheme } from "@nfid/identitykit/react" import { NFIDW, InternetIdentity, Stoic, OISY } from "@nfid/identitykit" const App = () => { return ( console.log("Connected successfully")} onConnectFailure={(error) => console.error("Connection failed:", error)} onDisconnect={() => console.log("Disconnected")} > ) } ``` -------------------------------- ### Using useSigner Hook Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useSigner.mdx Basic implementation of the useSigner hook within a React component. ```typescript import { useSigner } from "@nfid/identitykit/react" const signer = useSigner() ``` -------------------------------- ### useInitializing Hook Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useIsInitializing.mdx The useInitializing hook returns a boolean value that indicates if the IdentityKit is currently initializing. This is useful for disabling wallet connection UI elements until the initialization process is complete. ```APIDOC ## useInitializing ### Description Returns a boolean representing whether IdentityKit has initialized for a connected user on page reload. Connect wallet functionality should be disabled until initialization finishes. ### Signature `() => boolean` ### Usage ```typescript import { useInitializing } from "@nfid/identitykit/react" const isInitializing = useInitializing() ``` ``` -------------------------------- ### Manage authentication state with useAuth Source: https://context7.com/internet-identity-labs/identitykit/llms.txt Provides connect/disconnect functionality and current user information. Requires the IdentityKit provider to be configured in the application. ```typescript import { useAuth } from "@nfid/identitykit/react" import { useInitializing } from "@nfid/identitykit/react" const AuthComponent = () => { const { connect, disconnect, isConnecting, user } = useAuth() const isInitializing = useInitializing() const handleConnect = async () => { try { await connect() // Opens wallet selection modal // Or connect directly to specific signer: // await connect("NFIDW") } catch (error) { console.error("Connection failed:", error) } } if (isInitializing) { return
Loading...
} if (user) { return (

Connected: {user.principal.toString()}

{user.subaccount &&

Subaccount: {user.subaccount}

}
) } return ( ) } ``` -------------------------------- ### Customizing ConnectWalletButton Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/connect-wallet.mdx Details on how to customize the appearance and behavior of the ConnectWalletButton, including text, styling, and custom click handlers. ```APIDOC ## Customizing ConnectWalletButton ### Description The `ConnectWalletButton` component can be customized by passing props such as `children` for text and `className` for styling. It also supports rendering custom components and attaching `onClick` handlers to trigger the signers modal. ### Method N/A (Component Customization) ### Endpoint N/A (Component Customization) ### Parameters #### ConnectWalletButton Props - **children** (string) - Optional - Custom text for the button. Default is "Connect wallet". - **className** (string) - Optional - CSS class for styling the button. - **onClick** (function) - Optional - Handler function to be called when the button is clicked, typically to open the signers modal. ### Request Example ```jsx // Customizing text and class Sign in // Creating a custom button component function CustomConnectWalletButton({ onClick, ...props }: ConnectWalletButtonProps) { return (
// for example add some image etc.
) } ``` ### Response N/A (Component Customization) ``` -------------------------------- ### Use useIdentityKit hook Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useIdentityKit.mdx Destructure the hook to access authentication state, user data, and wallet functions. ```typescript const { isInitializing, user, isUserConnecting, icpBalance, signer, identity, delegationType, accounts, connect, disconnect, fetchIcpBalance, } = useIdentityKit() ``` -------------------------------- ### Provide Custom Signers List Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/signers-list.mdx Customize the order of wallets by providing a specific array of signers to the IdentityKitProvider. This allows you to prioritize or include specific wallets like NFIDW, InternetIdentity, Stoic, and OISY. ```jsx import { IdentityKitProvider } from "@nfid/identitykit/react" import { NFIDW, InternetIdentity, Stoic, OISY } from "@nfid/identitykit" export const App = () => ( ) ``` -------------------------------- ### Implement ConnectWallet Component Source: https://context7.com/internet-identity-labs/identitykit/llms.txt Use the ConnectWallet component to render connection buttons and modals, with options for basic, custom text, or fully custom UI implementations. ```jsx import { ConnectWallet, ConnectWalletButton, ConnectedWalletButton, ConnectWalletDropdownMenu, ConnectWalletDropdownMenuButton, ConnectWalletDropdownMenuItems, ConnectWalletDropdownMenuItem, ConnectWalletDropdownMenuAddressItem, ConnectWalletDropdownMenuDisconnectItem } from "@nfid/identitykit/react" // Basic usage export const BasicWallet = () => // Custom button text export const CustomButtonText = () => ( Sign in with Wallet ) // Fully customized with custom components export const FullyCustomized = () => ( ( )} connectedButtonComponent={({ connectedAccount, icpBalance, ...props }) => ( {`${connectedAccount.slice(0, 8)}... | ${icpBalance} ICP`} )} dropdownMenuComponent={({ connectedAccount, icpBalance, disconnect }) => ( {connectedAccount} )} /> ) ``` -------------------------------- ### Apply a Dark Theme to IdentityKitProvider Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/theming.mdx Pass the IdentityKitTheme.DARK value to the theme prop of IdentityKitProvider to apply the dark theme. Ensure IdentityKitProvider and IdentityKitTheme are imported. ```jsx import { IdentityKitProvider } from "@nfid/identitykit/react" import { IdentityKitTheme } from "@nfid/identitykit/react" export const App = () => ( ) ``` -------------------------------- ### Configure IdentityKit for Account Authentication Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/miscellaneous/auth-options.mdx Use the `IdentityKitProvider` with `authType={IdentityKitAuthType.ACCOUNTS}` to enable standard account authentication. This is suitable for dApps that primarily look up account data and prioritize user security and autonomy. ```jsx const App = () => { return ( ) } ``` -------------------------------- ### Register Custom Domain with Boundary Nodes Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/configuring-custom-domains.mdx Use `curl` to send a POST request to the ICP boundary nodes API to register your custom domain. Replace `CUSTOM_DOMAIN` with your actual domain name. This step is crucial for the network to recognize your domain. ```bash curl -sLv -X POST \ -H 'Content-Type: application/json' \ https://icp0.io/registrations \ --data @- < ( ) // Account Delegation: No pop-ups for target canisters, pop-ups for others const AccountDelegationApp = () => ( ) // Relying Party Delegation: No pop-ups, isolated user identity per dApp const RelyingPartyApp = () => ( ) // Per-signer auth type configuration const CustomAuthApp = () => ( ) ``` -------------------------------- ### Importing IDL Factories for Canister Calls Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/executing-canister-calls.mdx Import the idlFactory for your target canister and any other canisters you need to interact with, such as ICRC-1 token ledgers. ```typescript import { idlFactory as targetIdlFactory } from "/path/to/target/did.js" import { idlFactory as nonTargetIdlFactory } from "/path/to/nontarget/did.js" ``` -------------------------------- ### Setting authType Globally Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/advanced-options.mdx Demonstrates how to set a single authType for all signers when initializing IdentityKitProvider. This can be overridden by specific signer configurations. ```jsx 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 ( ) } ``` -------------------------------- ### Creating Actors for Canister Calls Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/executing-canister-calls.mdx Create actors using imported idlFactories and canister IDs. Differentiate between actors for unauthenticated calls and those requiring authentication, which may trigger wallet prompts. ```typescript // 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]) ``` -------------------------------- ### Access signer information with useSigner Source: https://context7.com/internet-identity-labs/identitykit/llms.txt Retrieves details about the currently selected wallet or signer, such as label, ID, and provider URL. ```typescript import { useSigner } from "@nfid/identitykit/react" const SignerInfo = () => { const signer = useSigner() if (!signer) { return

No signer selected

} return (

{signer.label}

ID: {signer.id}

Provider URL: {signer.providerUrl}

Transport: {signer.transportType}

{signer.description &&

{signer.description}

} {signer.icon && {signer.label}}
) } ``` -------------------------------- ### Custom ConnectedWalletButton with Account and Balance Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/connect-wallet.mdx Create a custom component for the connected wallet button that displays the connected account address and ICP balance. This component receives `connectedAccount` and `icpBalance` props. ```jsx function CustomConnectedWalletButton({ connectedAccount, icpBalance, ...props }: ConnectedWalletButtonProps) { return ( {`Disconnect ${connectedAccount} ${icpBalance} ICP`} ) } ``` -------------------------------- ### Default authType Configuration Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/advanced-options.mdx Shows the default authType settings for various signers. This configuration prioritizes specific signer settings over global ones. ```jsx // 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 } ``` -------------------------------- ### Successful Registration Response Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/guides/configuring-custom-domains.mdx The expected response after successfully registering a custom domain with the boundary nodes. It returns a JSON object containing a `REQUEST_ID` that can be used for tracking. ```json {"id":"REQUEST_ID"} ``` -------------------------------- ### Customizing ConnectWalletButton Text Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/connect-wallet.mdx Set custom text for the ConnectWalletButton by passing children to it. The default text is 'Connect wallet'. ```jsx Sign in ``` -------------------------------- ### useAgent Hook Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useAgent.mdx The useAgent hook returns an IdentityKitAgent instance. This agent manages canister calls, showing approval pop-ups when necessary. It defaults to using a signerAgent for pop-ups and a Dfinity HttpAgent with the user's identity for other calls. The agent is undefined until the user is connected and the agent is initialized. ```APIDOC ## useAgent Hook ### Description Provides an IdentityKitAgent instance for making authenticated canister calls. It handles user approval pop-ups and utilizes the appropriate HTTP agent based on the connection status. ### Method `useAgent(options?: HttpAgentOptions) => IdentityKitAgent | undefined` ### Parameters #### Query Parameters - **options** (HttpAgentOptions) - Optional - Configuration options for the HTTP agent, such as `retryTimes` and `host`. ### Request Example ```typescript import { useAgent } from "@nfid/identitykit/react" const agent = useAgent() ``` Or with custom options: ```typescript import { useAgent } from "@nfid/identitykit/react" const agent = useAgent({ retryTimes: 1, host: "https://my-custom-host.ic0.app" }) ``` ### Response #### Success Response (IdentityKitAgent | undefined) - **IdentityKitAgent** - An agent instance that can be used to make canister calls. - **undefined** - Returned until the user is connected and the agent is created. ### Notes If no custom configuration is provided, the agent typically defaults to `https://ic0.app` or the relevant boundary node. If the environment is not recognized, it falls back to `https://icp-api.io`. Custom options can be provided to change these and other agent settings. ``` -------------------------------- ### Wrap Application with IdentityKitProvider Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/installation.mdx Wrap your application component with the provider, specifying authType and target canisters. ```jsx const App = () => { return ( ) } ``` -------------------------------- ### Manage Signer Discovery and Exclusion Source: https://context7.com/internet-identity-labs/identitykit/llms.txt Controls which wallet signers are available and manages automatic browser extension discovery behavior. ```jsx import { IdentityKitProvider } from "@nfid/identitykit/react" import { NFIDW, InternetIdentity, Stoic, OISY } from "@nfid/identitykit" // Custom signer list const CustomSignersApp = () => ( ) // Disable automatic extension discovery const NoExtensionDiscoveryApp = () => ( ) // Exclude specific discovered extensions const ExcludeExtensionsApp = () => ( ) // Disable featured signer (compact mode) const CompactModeApp = () => ( ) ``` -------------------------------- ### Customizing ConnectedWalletButton Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/connect-wallet.mdx Information on customizing the ConnectedWalletButton, including available props for displaying account information and balance. ```APIDOC ## Customizing ConnectedWalletButton ### Description The `ConnectedWalletButton` component can be customized similarly to `ConnectWalletButton`. Custom components receive additional props like `connectedAccount` and `icpBalance` to display relevant information about the connected wallet. ### Method N/A (Component Customization) ### Endpoint N/A (Component Customization) ### Parameters #### ConnectedWalletButton Props - **connectedAccount** (string) - The address of the connected account. - **icpBalance** (number | undefined) - The balance of the connected account in ICP, or undefined if fetching. - Other standard HTML button props. ### Request Example ```jsx function CustomConnectedWalletButton({ connectedAccount, icpBalance, ...props }: ConnectedWalletButtonProps) { return ( {`Disconnect ${connectedAccount} ${icpBalance} ICP`} ) } ``` ### Response N/A (Component Customization) ``` -------------------------------- ### useBalance Hook Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/hooks/useBalance.mdx The useBalance hook returns the current balance of the connected user and a function to refetch the balance. Note that both values are undefined until a successful connection is established. ```APIDOC ## useBalance Hook ### Description Retrieves the balance of the connected user and provides a function to refetch the balance data. ### Signature `() => ({ balance: number | undefined, fetchBalance: (() => Promise) | undefined })` ### Usage ```typescript import { useBalance } from "@nfid/identitykit/react" const { balance, fetchBalance } = useBalance() ``` ### Notes - Both `balance` and `fetchBalance` will be `undefined` until a successful connection is established. ``` -------------------------------- ### Styling ConnectWalletButton with className Source: https://github.com/internet-identity-labs/identitykit/blob/main/docs/pages/getting-started/connect-wallet.mdx Apply custom CSS classes to the ConnectWalletButton using the className prop for styling, such as changing the background color. ```jsx Sign in ```