# Cosmos Kit Documentation Cosmos Kit import React from "react"; import { WalletSection } from "../../components"; import { DownloadButton } from '../../components/download-button' # CosmosKit

cosmos-kit

CosmosKit is a wallet adapter for developers to build apps that quickly and easily interact with Cosmos blockchains and wallets. ## Get Started ⚡️ [How to use CosmosKit](/cosmos-kit/get-started) ## Try It Out! ## Wallet Developers 🔌 [How to integrate new wallets into CosmosKit](/cosmos-kit/integrating-wallets/adding-new-wallets) ## Packages ### [@cosmos-kit/core](https://github.com/hyperweb-io/cosmos-kit/tree/main/packages/core) Core package of CosmosKit, including types, utils and base classes. ### [@cosmos-kit/react](https://github.com/hyperweb-io/cosmos-kit/tree/main/packages/react) A wallet adapter for React with mobile WalletConnect support for the Cosmos ecosystem. ### [@cosmos-kit/react-lite](https://github.com/hyperweb-io/cosmos-kit/tree/main/packages/react-lite) A lighter version of `@cosmos-kit/react` without the default modal. ### [@cosmos-kit/ins](https://github.com/hyperweb-io/cosmos-kit/tree/main/packages/ins) Interchain Name System implementation ### [@cosmos-kit/walletconnect](https://github.com/hyperweb-io/cosmos-kit/tree/main/packages/walletconnect) [Wallet Connect V2](https://walletconnect.com/) support tools (usually used when integrating mobile wallets). ### [WALLETS](/cosmos-kit/integrating-wallets) Wallets integrated in CosmosKit. ### [@cosmos-kit/example](https://github.com/hyperweb-io/cosmos-kit/tree/main/packages/example) An example Next.js project integrating `@cosmos-kit/react` wallet adapter. ## Related Projects ### [create-cosmos-app](https://github.com/hyperweb-io/create-cosmos-app) Set up a modern Cosmos app by running one command ⚛️ ### [chain-registry](https://github.com/hyperweb-io/chain-registry) An npm module for the official Cosmos chain-registry ---------------------------------- Advanced # Advanced ## Code Structure To make user better understand the whole design structure of CosmosKit, here to briefly introduce some important classes from `@cosmos-kit/core`. There are four important classes. - WalletManager - MainWalletBase - ChainWalletBase - WalletRepo Before all, we need to clarify that there are two types of entities in CosmosKit as a wallet adapter: **Chain** and **Wallet**. Chain is identified by chain name i.e. `cosmoshub`, `osmosis` etc. And wallet is identified by wallet name i.e. `keplr-extension`, `keplr-mobile`, `cosmostation-extension` etc. > Note that we're taking a single wallet application as a wallet in CosmosKit rather than the wallet product name. Taking `Keplr` as an example, we differentiate `extension` and `mobile` in our code because they are connected via totally different codes. So for product `Keplr`, we have two wallets `keplr-extension` and `keplr-mobile` in CosmosKit. ### WalletManager `WalletManager` is the entrance of the whole code and it manages all `WalletRepo`, `MainWalletBase`, `ChainWalletBase` instances in it. It also corresponds to `ChainProvider` in `@cosmos-kit/react-lite` and `@cosmos-kit/react`. You can find that the properties of JSX element `ChainProvider` are almost the same with the constructor arguments of `WalletManager`. All necessary chain information and wallet information from `ChainProvider` will be passed to corresponding wallet classes via `WalletManager`. Three important properties/arguments in `ChainProvider`/`WalletManager` are `chains`, `assetLists` and `wallets`. `chains` and `assetLists` provide chain information, and `wallets` provides wallet information. Actually `wallets` is an array of `MainWalletBase` instances. Here leads to the second class `MainWalletBase`. ### MainWalletBase `MainWalletBase` is meant to provide a base implementation and unified interface for all different wallets like `keplr-extension`, `keplr-mobile` and `cosmostation-extension`. Basically every wallet has it's own `MainWallet` class, which extends `MainWalletBase` in common, but with `WalletClient` implemented in different ways. In this way `WalletManager` can handle all different wallets no matter how different they're inside. > For practice you can take a look at [How to Integrate New Wallets into CosmosKit](/integrating-wallets/adding-new-wallets) `MainWalletBase` is only about wallet and it's not about any specific chain. And it's responsible for initializing wallet client and managing all chain wallets. Here brings in the third class `ChainWalletBase`. > So far `MainWalletBase` is dealing with four different broadcast/synchronization events for chain wallets. > > - broadcast_client > - broadcast_env > - sync_connect > - sync_disconnect > > See details below. ### ChainWalletBase When you're trying to connect to a wallet, you always need to provide a target chain name so that the wallet knows what to response. So `ChainWalletBase` is the class actually being used for real connection. It's the finest grain of functionality that with chain specified and also wallet specified. We're separating `MainWalletBase` and `ChainWalletBase` because it's clearer to put some common properties like `wallet client` and `env` in the `MainWalletBase` to enable centralized management and distribution (events `broadcast_client` and `broadcast_env`), and put only chain specified functionalities in `ChainWalletBase`. Basically how many `chains` are provided in `ChainProvider` or `WalletManager`, how many `ChainWalletBase` instances will be constructed for a wallet. `ChainWalletBase` instances are independent with each other unless `sync` is set `true`. All the synchronization are also handled in `MainWalletBase` (events `sync_connect` and `sync_disconnect`). ### WalletRepo We have a class `MainWalletBase` with wallet specified to manage all chain wallets. All these chain wallets are with the same wallet name but different chain name. Accordingly we also have another class `WalletRepo`, which with chain specified to manage all chain wallets that with the same chain name but different wallet name. ### MainWalletBase vs. WalletRepo #### 1. **MainWalletBase** - **Purpose**: Manages a collection of chain wallets. - **Key Identifier**: Wallet name. - **Example**: It handles wallets like cosmoshub/keplr-extension, osmosis/keplr-extension, etc. These are wallets from different chains but with the same wallet name. #### 2. **WalletRepo** - **Purpose**: Manages chain wallets too, but with a different approach. - **Key Identifier**: Chain name. - **Example**: It manages wallets like cosmoshub/keplr-extension, cosmoshub/keplr-mobile, etc. These are wallets from the same chain but with different wallet names. #### Common Point - **Both MainWalletBase and WalletRepo** are involved in managing chain wallets, which are wallets associated with different blockchain networks. #### Key Differences - **MainWalletBase**: Focuses on managing wallets based on the wallet’s name. It doesn’t matter what chain the wallet is from; as long as they share the same wallet name, MainWalletBase manages them. - **WalletRepo**: Concentrates on managing wallets based on the chain’s name. Here, the specific wallet names don’t matter; WalletRepo groups and manages wallets that are on the same blockchain network. #### Practical Use - **In some decentralized applications (dapps)**, the focus might be more on the blockchain network (chain) rather than the wallet itself. In such cases, WalletRepo is particularly useful because it provides a perspective based on the chain, allowing different wallets on the same chain to be managed together. #### Summary - **MainWalletBase**: Manages wallets across different chains but with the same wallet name. - **WalletRepo**: Manages different wallets on the same chain. In essence, these two classes offer different ways of organizing and accessing chain wallets, based on what the primary point of interest is (wallet name or chain name). So far `WalletRepo` is only used in [`WalletModal`](https://docs.cosmology.zone/cosmos-kit/provider/chain-provider#walletmodal) properties. ---------------------------------- Get Started # How to use CosmosKit > 💡 Make sure you are using `React18` > > `CosmosKit V1` is deprecated, we suggest using [`CosmosKit V2`](./migration-to-v2) > > `defaultSignOptions` has been preset as below in latest version (core >= 2.7, react-lite >= 2.5, react >= 2.9): ```json { preferNoSetFee: false, preferNoSetMemo: true, disableBalanceCheck: true, }; ``` ## Quickstart 🏁 Get started quickly by using [create-cosmos-app](https://github.com/hyperweb-io/create-cosmos-app) to help you build high-quality Cosmos apps fast! ## Use CosmosKit from Scratch ### 1️⃣ Install Dependencies Taking `Keplr` wallet as an example. ```sh yarn add @cosmos-kit/react @cosmos-kit/keplr chain-registry ``` `@cosmos-kit/react` includes default modal made with `@interchain-ui/react`. If [customized modal](./provider/chain-provider/#customize-modal-with-walletmodal) is provided, you can use `@cosmos-kit/react-lite` instead to lighter your app. There are multiple wallets supported by CosmosKit. Details see [Integrating Wallets](./integrating-wallets) > Note: `@cosmjs/*` packages are peer dependencies in `@cosmos-kit/core`, so if you're not using `@cosmjs/*` in your dapp, `yarn install` would complain UNMET cosmjs peer dependencies. ### 2️⃣ Wrap Provider First, add [`ChainProvider`](./provider/chain-provider) and provider [required properties](./provider/chain-provider#required-properties). Example: ```tsx import * as React from 'react'; import { ChainProvider } from '@cosmos-kit/react'; import { chains, assets } from 'chain-registry'; import { wallets } from '@cosmos-kit/keplr'; // Import this in your top-level route/layout import "@interchain-ui/react/styles"; function CosmosApp() { return ( ); } ``` ### 3️⃣ Consume with Hook Take `useChain` as an example. ```tsx import * as React from 'react'; import { useChain } from "@cosmos-kit/react"; function Component ({ chainName }: { chainName: string }) => { const chainContext = useChain(chainName); const { status, username, address, message, connect, disconnect, openView, } = chainContext; } ``` ## Localstorage Settings ### current wallet - **Key**: `cosmos-kit@2:core//current-wallet` - **Type**: `string` It records current wallet name. You can use this key to implement auto-connection in dapp. And it will expire after provided [session duration](./provider/chain-provider#sessionoptions). ### accounts - **Key**: `cosmos-kit@2:core//accounts` - **Type**: `SimpleAccount[]` It records the connected chains' account information. It's used for account restore when refreshing in CosmosKit. And it will expire after provided [session duration](./provider/chain-provider#sessionoptions). ---------------------------------- Migration To V2 # Migration from V1 to V2 ## Major Changes 1. `ChakraUI` Removed In CosmosKit V2, we discard the dependency on `ChakraUI` due to numerous runtime errors and the cost of CSS-in-JS. Main changes lie in `@cosmos-kit/react`, where the default modal locates. All the modal components are imported from `@interchain-ui/react`, which is our UI Kit in Hyperweb. The latest `@interchain-ui/react` discards `ChakraUI` and instead adopts a pure CSS styling solution through a package called `vanilla-extract`. 2. Build Process Changed In CosmosKit V2, we used pure `tsc` to compile CommonJS, ESM (es2022) instead of `babel`. Also, `.js` and `.d.ts` files are no longer to be separated in different folders, in this way non-index sources can easily find its corresponding types. ## Migration Guides 1. In CosmosKit V2, we require developers to install `@interchain-ui/react` and require **`import "@interchain-ui/react/styles"`** in your top-level route/layout if you are using our default modal in `@cosmos-kit/react`. i.e. in [`_app.tsx`](https://github.com/hyperweb-io/cosmos-kit/blob/af05600fd1913e0d3eb1bbef05382c1a06c6af69/packages/example/pages/_app.tsx#L4) for next project. 2. We don't export `defaultTheme` anymore in `@cosmos-kit/react` in CosmosKit V2. 3. `WrappedWithChakra` and `modalTheme` is removed in properties of `ChainProvider` from `@cosmos-kit/react`. 4. `Web3Auth` wallet instance import has been replaced by constructing the wallet instance with a wallet generator function. In this way the web3auth implementation becomes much more secure, and also makes it support any of the login providers. See details [here](./integrating-wallets/web3auth) ## Customizing the default modal Customizing the default modal styles is done through `modalTheme` prop of `` We are currently providing 2 ways to customize the default modal: 1. Overriding the theme object: By using the `modalTheme.themeDefs` and `modalTheme.customTheme`, you can override all of the theme tokens however you want ```TSX {children} ``` The full object shape of `themeDefs[index].vars` is as below ```json { colors: { primary: ``, body: ``, background: ``, link: ``, linkHover: ``, text: ``, textSecondary: ``, textDanger: ``, textWarning: ``, textPlaceholder: ``, rewardBg: ``, rewardContent: ``, cardBg: ``, inputBorder: ``, inputBg: ``, inputDangerBorder: ``, inputDangerBg: ``, inputDisabledBg: ``, inputDisabledText: ``, progressBg: ``, progressValue: ``, progressCursor: ``, divider: ``, menuItemBg: ``, menuItemBgHovered: ``, menuItemBgActive: ``, skeletonBg: ``, black: ``, blackPrimary: ``, white: ``, transparent: ``, current: ``, whiteAlpha50: ``, whiteAlpha100: ``, whiteAlpha200: ``, whiteAlpha300: ``, whiteAlpha400: ``, whiteAlpha500: ``, whiteAlpha600: ``, whiteAlpha700: ``, whiteAlpha800: ``, whiteAlpha900: ``, blackAlpha50: ``, blackAlpha100: ``, blackAlpha200: ``, blackAlpha300: ``, blackAlpha400: ``, blackAlpha500: ``, blackAlpha600: ``, blackAlpha700: ``, blackAlpha800: ``, blackAlpha900: ``, gray50: ``, gray100: ``, gray200: ``, gray300: ``, gray400: ``, gray500: ``, gray600: ``, gray700: ``, gray800: ``, gray900: ``, red50: ``, red100: ``, red200: ``, red300: ``, red400: ``, red500: ``, red600: ``, red700: ``, red800: ``, red900: ``, orange50: ``, orange100: ``, orange200: ``, orange300: ``, orange400: ``, orange500: ``, orange600: ``, orange700: ``, orange800: ``, orange900: ``, yellow50: ``, yellow100: ``, yellow200: ``, yellow300: ``, yellow400: ``, yellow500: ``, yellow600: ``, yellow700: ``, yellow800: ``, yellow900: ``, green50: ``, green100: ``, green200: ``, green300: ``, green400: ``, green500: ``, green600: ``, green700: ``, green800: ``, green900: ``, blue50: ``, blue100: ``, blue200: ``, blue300: ``, blue400: ``, blue500: ``, blue600: ``, blue700: ``, blue800: ``, blue900: ``, primary50: ``, primary100: ``, primary200: ``, primary300: ``, primary400: ``, primary500: ``, primary600: ``, primary700: ``, primary800: ``, primary900: ``, purple50: ``, purple100: ``, purple200: ``, purple300: ``, purple400: ``, purple500: ``, purple600: ``, purple700: ``, purple800: ``, purple900: ``, }, font: { body: ``, }, space: { "0": ``, "1": ``, "2": ``, "3": ``, "4": ``, "5": ``, "6": ``, "7": ``, "8": ``, "9": ``, "10": ``, "11": ``, "12": ``, "13": ``, "14": ``, "15": ``, "16": ``, "17": ``, "18": ``, "19": ``, "20": ``, "21": ``, "22": ``, "23": ``, "24": ``, "25": ``, "26": ``, "27": ``, "28": ``, "29": ``, "30": ``, auto: ``, full: ``, fit: ``, max: ``, min: ``, viewHeight: ``, viewWidth: ``, none: ``, }, borderWidth: { none: ``, sm: ``, base: ``, md: ``, lg: ``, xl: ``, }, borderStyle: { none: ``, solid: ``, dotted: ``, dashed: ``, groove: ``, ridge: ``, hidden: ``, double: ``, inset: ``, outset: ``, unset: ``, }, boxShadow: { xs: ``, sm: ``, base: ``, md: ``, lg: ``, xl: ``, "2xl": ``, inset: ``, primaryOutline: ``, none: ``, "dark-lg": ``, }, radii: { none: ``, sm: ``, base: ``, md: ``, lg: ``, xl: ``, "2xl": ``, "3xl": ``, "4xl": ``, full: ``, }, letterSpacing: { tighter: ``, tight: ``, normal: ``, wide: ``, wider: ``, widest: ``, }, lineHeight: { normal: ``, none: ``, shorter: ``, short: ``, base: ``, tall: ``, taller: ``, }, fontWeight: { hairline: ``, thin: ``, light: ``, normal: ``, medium: ``, semibold: ``, bold: ``, extrabold: ``, black: ``, }, fontSize: { "3xs": ``, "2xs": ``, xs: ``, sm: ``, md: ``, lg: ``, xl: ``, "2xl": ``, "3xl": ``, "4xl": ``, "5xl": ``, "6xl": ``, "7xl": ``, "8xl": ``, "9xl": ``, "10xl": ``, "11xl": ``, "12xl": ``, "13xl": ``, "14xl": ``, "15xl": ``, }, zIndex: { "0": ``, "10": ``, "20": ``, "30": ``, "40": ``, "50": ``, "100": ``, auto: ``, }, } ``` 2. Overriding css vars specific to a component. This is done through the `modalTheme.overrides` prop, which is a record with keys corresponding to a slot names and values are objects of overridable property name and its value in each theme mode. ```json { : { : { light: , dark: } } } ``` Example: ```TSX {children} ``` Supported overridable slots/components and their overridable state/attributes are: ```json { "button": [ "bg", "hoverBg", "color", "hoverColor" ], "clipboard-copy-text": [ "color", "borderColor" ], "connect-modal": [ "bg", "shadow" ], "connect-modal-install-button": [ "bg", "borderColor", "color", "shadow" ], "connect-modal-head-title": [ "color" ], "connect-modal-wallet-button": [ "color", "bg", "focusedBg", "hoverBg", "focusedShadow", "hoverShadow", ], "connect-modal-wallet-button-label": [ "color" ], "connect-modal-wallet-button-sublogo": [ "bg", "borderColor" ], "connect-modal-qr-code": [ "bg", "color", "borderColor", "shadow" ], "connect-modal-qr-code-shadow": [ "bg" ], "connect-modal-qr-code-error": [ "bg" ], "connect-modal-qr-code-error-button": [ "bg", "color", "shadow" ], "connect-modal-qr-code-loading": [ "bg" ] } ``` Additionally, you can customize the base modal class names using the follow properties of ``'s `modalTheme` prop: ```ts type ModalCustomizationProps = { modalContainerClassName?: string; modalContentClassName?: string; modalChildrenClassName?: string; modalContentStyles?: React.CSSProperties; }; ``` ## Improvement in bundle size in v2 Since we dropped Chakra UI to build our own foundational UI system. The bundle size dropped a lot. Here are some screenshots and bundle size improvement ### Core UI size improvement In the new package `@interchain-ui/react`, package size dropped from 362kb to 159kb (minified + gzipped) ![Old](../../public/bundle-size-screenshots/old-cosmology-ui.png) ![New](../../public/bundle-size-screenshots/new-interchain-ui.png) ### Cosmos Kit size improvement Additionally, we also reduce the bundle size of cosmos kit by significant amount, from 386kb to just 28kb (minified + gzipped) ![Old](../../public/bundle-size-screenshots/old-v1-cosmos-kit.png) ![New](../../public/bundle-size-screenshots/new-v2-cosmos-kit.png) We're pretty happy with the improvement in V2 so far and looking to improve it much more. ---------------------------------- Connect Multi Chains ## How to connect multiple chains? ### 1. Use `useChains` Hook CosmosKit introduces **[`useChains`](../hooks/use-chains)** hook starting from `v2.3.0`. Use it to connect to multiple chains. ### 2. For A Specific Wallet (No Modal Required) Let's take `keplr-extension` for example. ```javascript import { useWalletClient } from "@cosmos-kit/react"; export default function Home() { const { status, client } = useWalletClient("keplr-extension"); // or cosmostation-extension, leap-extension, etc. useEffect(() => { if (status === "Done") { client.enable?.(["cosmoshub-4", "osmosis-1", "juno-1"]); client.getAccount?.("juno-4").then((account) => console.log(account)); client.getAccount?.("osmosis-1").then((account) => console.log(account)); client .getAccount?.("cosmoshub-4") .then((account) => console.log(account)); } }, [status]); // ... } ``` ### 3. No Specific Wallets (Modal Required, Version Prior to `v2.3.0`) There's no `useChains` hook in CosmosKit then, so the best you can do is below. ```javascript export default function Home() { const { openView } = useChain("cosmoshub"); // or juno, osmosis, etc. const { status, client } = useWalletClient(); useEffect(() => { if (status === "Done") { client.enable?.(["cosmoshub-4", "osmosis-1", "juno-1"]); client.getAccount?.("juno-4").then((account) => console.log(account)); client.getAccount?.("osmosis-1").then((account) => console.log(account)); client .getAccount?.("cosmoshub-4") .then((account) => console.log(account)); } }, [status]); return (
); } ``` ---------------------------------- Sign # Sign ## Global Settings ```ts { return 'amino'; } }} > const { getSigningStargateClient } = useChain('cosmoshub'); const aminoSigningClient = await getSigningStargateClient(); ``` By default use `amino` signer. Or you need to set `return 'direct'` if `direct` signer required. ## Individual Settings ```ts const { status, client } = useWalletClient('keplr-extension'); if (status === 'Done') { /** * OR: * const aminoSigner = client.getOfflineSignerAmino('cosmoshub'); * const directSigner = client.getOfflineSignerDirect('cosmoshub'); */ const aminoSigner = client.getOfflineSigner('cosmoshub', 'amino'); } const aminoSigningClient = await SigningStargateClient.connectWithSigner( rpcEndpoint, aminoSigner ); ``` ---------------------------------- Hooks There are multiple hooks provided in CosmosKit. They all require [**ChainProvider**](./provider/chain-provider) from either `@cosmos-kit/react` or `@cosmos-kit/react-lite` to provide necessary information. - [`useChain`](./hooks/use-chain): Provide chainWallet related properties and methods, and support multiple chains connected at one time. When `useChain` is called, corresponding chainWallets will be activated. - [`useChainWallet`](./hooks/use-chain-wallet): Provide chainWallet related properties and methods, and support multiple chains and wallets connected at one time. When `useChainWallet` is called, corresponding chainWallet will be activated. > See more information about [Differences Between `useChain` And `useChainWallet`](#differences-between-usechain-and-usechainwallet) - [`useManager`](./hooks/use-manager): Manage all chains and wallets. - [`useModalTheme`](./hooks/use-modal-theme): Manage default modal themes. - [`useNameService`](./hooks/use-name-service): Get alias name of address from a particular name server. - [`useWallet`](./hooks/use-wallet): Manage all chainWallets and the global status for a particular wallet. - [`useWalletClient`](./hooks/use-wallet-client): Get the wallet client for a particular wallet. - [`useIframe`](./hooks/use-iframe): Set up an iframe that can access the currently connected wallet automatically. ## Differences Between `useChain` And `useChainWallet` 1. `useChainWallet` requires an extra parameter `walletName`. 2. `useChain` will pop up a wallet modal to connect while `useChainWallet` not. 3. `useChain` exposes extra `openView` and `closeView` methods and `walletRepo` property. 4. the return value of methods `getRpcEndpoint`, `getRestEndpoint`, `getStargateClient`, `getCosmWasmClient`, `getNameService` can be different between `useChain` and `useChainWallet`, because `useChain` explores all `chainWallets` related to the parameter `chainName`. ---------------------------------- Use Chain Wallet ## Hook - useChainWallet - required provider: [**ChainProvider**](../provider/chain-provider) from either `@cosmos-kit/react` or `@cosmos-kit/react-lite` - parameters: - **chainName**: `ChainName` ( = `string` ); - **walletName**: `WalletName` ( = `string` ); - **sync**: `boolean` = `true` > parameter `sync` means whether to synchronize connection and disconnection to all other activated chainWallets. - return type: [**ChainWalletContext**](#type---chainwalletcontext) ## Type - ChainWalletContext ### Properties | Name | Description | Type | Default | | ------------------------ | -------------------------------------------- | ------------------------ | -------------- | | **chain** | chain registry information | `Chain` | - | | **assets** | chain assets information | `AssetList \| undefined` | `undefined` | | **wallet** | current selected wallet registry information | `Wallet \| undefined` | `undefined` | | **logoUrl** | chain logo url | `string \| undefined` | `undefined` | | **address** | chain address from current selected wallet | `string \| undefined` | `undefined` | | **username** | username from current selected wallet | `string \| undefined` | `undefined` | | **message** | error/warn/info message | `string \| undefined` | `undefined` | | **status** | wallet status | `WalletStatus` | `Disconnected` | | **isWalletDisconnected** | if `status === 'Disconnected'` | `boolean` | `true` | | **isWalletConnecting** | if `status === 'Connecting'` | `boolean` | `false` | | **isWalletConnected** | if `status === 'Connected'` | `boolean` | `false` | | **isWalletRejected** | if `status === 'Rejected'` | `boolean` | `false` | | **isWalletNotExist** | if `status === 'NotExist'` | `boolean` | `false` | | **isWalletError** | if `status === 'Error'` | `boolean` | `false` | ### Methods | Name | Description | Parameters | Return Type | Is Async | | ---------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | -------- | | **connect** | connect wallet | **wallet**?: `WalletName` | `void` | Y | | **disconnect** | disconnect current selected wallet | - | `void` | Y | | **getRpcEndpoint** | return rpc endpoint, `isLazy` explanation is [here](../provider/chain-provider#islazy) | **isLazy**?: `boolean` | `string \| ExtendedHttpEndpoint` | Y | | **getRestEndpoint** | return rest endpoint, `isLazy` explanation is [here](../provider/chain-provider#islazy) | **isLazy**?: `boolean` | `string \| ExtendedHttpEndpoint` | Y | | **getStargateClient** | - | - | `StargateClient` | Y | | **getCosmWasmClient** | - | - | `CosmWasmClient` | Y | | **getSigningStargateClient** | always validate endpoint in method | - | `SigningStargateClient` | Y | | **getSigningCosmWasmClient** | always validate endpoint in method | - | `SigningCosmWasmClient` | Y | | **getNameService** | get name service object supported on provided chain | - | `NameService` | Y | | **estimateFee** | if **type** is `undefined`, default using `SigningStargateClient` | **messages**: `EncodeObject[]`,
**type**?: `CosmosClientType`,
**memo**?: `string`,
**multiplier**?: `number` | `StdFee` | Y | | **sign** | using `cosmjs`. if **type** is `undefined`, default using `SigningStargateClient` | **messages**: `EncodeObject[]`,
**fee**?: `StdFee`,
**memo**?: `string`,
**type**?: `CosmosClientType` | `TxRaw` | Y | | **broadcast** | if **type** is `undefined`, default using `SigningStargateClient` | **signedMessages**: `TxRaw`,
**type**?: `CosmosClientType`, | `DeliverTxResponse` | Y | | **signAndBroadcast** | if **type** is `undefined`, default using `SigningStargateClient` | **messages**: `EncodeObject[]`,
**fee**?: `StdFee`,
**memo**?: `string`,
**type**?: `CosmosClientType`, | `DeliverTxResponse` | Y | ### Properties from Wallet Client | Name | Description | Type | Default | | ---------------------- | ----------- | ------------------ | ---------- | ----------- | | **qrUrl** | - | `Mutable\ | undefined` | `undefined` | | **appUrl** | - | `Mutable\ | undefined` | `undefined` | | **defaultSignOptions** | - | `SignOptions` | as below | `defaultSignOptions`: ```json { preferNoSetFee: false, preferNoSetMemo: true, disableBalanceCheck: true, }; ``` ### Methods from Wallet Client > These methods are equal to wallet client methods with argument `chainId` assigned as `chainId` corresponding to hook argument `chainName`. If you want to directly use wallet client methods, choose hook [`useWalletClient`](../hooks/use-wallet-client) instead. | Name | Description | Parameters | Return Type | Is Async | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | --------------------- | -------- | | **setDefaultSignOptions** | - | **options**: `SignOptions` | `void` | N | | **enable** | - | - | `void` | Y | | **getAccount** | - | - | `WalletAccount` | Y | | **getOfflineSigner** | prioritize returning `preferredSignType` (in `ChainProvider` properties, by default `amino`) corresponding signer if it is available, otherwise return signer that is provided. | Y | | **getOfflineSignerAmino** | - | - | `OfflineAminoSigner` | N | | **getOfflineSignerDirect** | - | - | `OfflineDirectSigner` | N | | **signAmino** | - | **signer**: `string`,
**signDoc**: `StdSignDoc`,
**signOptions**?: `SignOptions` | `AminoSignResponse` | Y | | **signDirect** | - | **signer**: `string`,
**signDoc**: `StdSignDoc`,
**signOptions**?: `SignOptions` | `DirectSignResponse` | Y | | **signArbitrary** | - | **signer**: `string`,
**data**: `string \| Uint8Array` | `StdSignature` | Y | | **sendTx** | - | **tx**: `Uint8Array`,
**mode**: `BroadcastMode` | `Uint8Array` | Y | ### Advanced **Used for deeper dive into the chain and wallet related objects** | Name | Description | Type | Default | | --------------- | ------------------- | ------------------------------ | ----------- | | **chainWallet** | current chainWallet | `ChainWalletBase \| undefined` | `undefined` | ## Examples ### [fetch address](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/use-chain-wallet.tsx) ### [governance](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/gov.tsx) ---------------------------------- Use Chain ## Hook - useChain - required provider: [**ChainProvider**](../provider/chain-provider) from either `@cosmos-kit/react` or `@cosmos-kit/react-lite` > To use `useChain` with `ChainProvider` from `@cosmos-kit/react-lite`, property [`walletModal`](../provider/chain-provider#walletmodal) must be provided. Or you can choose `ChainProvider` from `@cosmos-kit/react`, which provides `DefaultModal`. Or you can use [`useChainWallet`](./use-chain-wallet) instead. - parameters: - **chainName**: `ChainName` ( = `string` ); - **sync**: `boolean` = `true` > parameter `sync` means whether to synchronize connection and disconnection to all other activated chainWallets. - return type: [**ChainContext**](#type---chaincontext) ## Type - ChainContext ### Properties | Name | Description | Type | Default | | ------------------------ | -------------------------------------------- | ------------------------ | -------------- | | **chain** | chain registry information | `Chain` | - | | **assets** | chain assets information | `AssetList \| undefined` | `undefined` | | **wallet** | current selected wallet registry information | `Wallet \| undefined` | `undefined` | | **logoUrl** | chain logo url | `string \| undefined` | `undefined` | | **address** | chain address from current selected wallet | `string \| undefined` | `undefined` | | **username** | username from current selected wallet | `string \| undefined` | `undefined` | | **message** | error/warn/info message | `string \| undefined` | `undefined` | | **status** | wallet status | `WalletStatus` | `Disconnected` | | **isWalletDisconnected** | if `status === 'Disconnected'` | `boolean` | `true` | | **isWalletConnecting** | if `status === 'Connecting'` | `boolean` | `false` | | **isWalletConnected** | if `status === 'Connected'` | `boolean` | `false` | | **isWalletRejected** | if `status === 'Rejected'` | `boolean` | `false` | | **isWalletNotExist** | if `status === 'NotExist'` | `boolean` | `false` | | **isWalletError** | if `status === 'Error'` | `boolean` | `false` | ### Methods | Name | Description | Parameters | Return Type | Is Async | | ---------------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------- | -------- | | **openView** | open modal | - | `void` | N | | **closeView** | close modal | - | `void` | N | | **connect** | connect wallet | **wallet**?: `WalletName` | `void` | Y | | **disconnect** | disconnect current selected wallet | - | `void` | Y | | **getRpcEndpoint** | return rpc endpoint, `isLazy` explanation is [here](../provider/chain-provider#islazy) | **isLazy**?: `boolean` | `string \| ExtendedHttpEndpoint` | Y | | **getRestEndpoint** | return rest endpoint, `isLazy` explanation is [here](../provider/chain-provider#islazy) | **isLazy**?: `boolean` | `string \| ExtendedHttpEndpoint` | Y | | **getStargateClient** | - | - | `StargateClient` | Y | | **getCosmWasmClient** | - | - | `CosmWasmClient` | Y | | **getSigningStargateClient** | always validate endpoint in method | - | `SigningStargateClient` | Y | | **getSigningCosmWasmClient** | always validate endpoint in method | - | `SigningCosmWasmClient` | Y | | **getNameService** | get name service object supported on provided chain | - | `NameService` | Y | | **estimateFee** | if **type** is `undefined`, default using `SigningStargateClient` | **messages**: `EncodeObject[]`,
**type**?: `CosmosClientType`,
**memo**?: `string`,
**multiplier**?: `number` | `StdFee` | Y | | **sign** | using `cosmjs`. if **type** is `undefined`, default using `SigningStargateClient` | **messages**: `EncodeObject[]`,
**fee**?: `StdFee`,
**memo**?: `string`,
**type**?: `CosmosClientType` | `TxRaw` | Y | | **broadcast** | if **type** is `undefined`, default using `SigningStargateClient` | **signedMessages**: `TxRaw`,
**type**?: `CosmosClientType`, | `DeliverTxResponse` | Y | | **signAndBroadcast** | if **type** is `undefined`, default using `SigningStargateClient` | **messages**: `EncodeObject[]`,
**fee**?: `StdFee`,
**memo**?: `string`,
**type**?: `CosmosClientType`, | `DeliverTxResponse` | Y | ### Properties from Wallet Client | Name | Description | Type | Default | | ---------------------- | ----------- | ------------------ | ---------- | ----------- | | **qrUrl** | - | `Mutable\ | undefined` | `undefined` | | **appUrl** | - | `Mutable\ | undefined` | `undefined` | | **defaultSignOptions** | - | `SignOptions` | as below | `defaultSignOptions`: ```json { preferNoSetFee: false, preferNoSetMemo: true, disableBalanceCheck: true, }; ``` ### Methods from Wallet Client > These methods are equal to wallet client methods with argument `chainId` assigned as `chainId` corresponding to hook argument `chainName`. If you want to directly use wallet client methods, choose hook [`useWalletClient`](./use-wallet-client) instead. | Name | Description | Parameters | Return Type | Is Async | | -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | --------------------- | -------- | | **setDefaultSignOptions** | - | **options**: `SignOptions` | `void` | N | | **enable** | - | - | `void` | Y | | **getAccount** | - | - | `WalletAccount` | Y | | **getOfflineSigner** | prioritize returning `preferredSignType` (in `ChainProvider` properties, by default `amino`) corresponding signer if it is available, otherwise return signer that is provided. | - | `OfflineSigner` | Y | | **getOfflineSignerAmino** | - | - | `OfflineAminoSigner` | N | | **getOfflineSignerDirect** | - | - | `OfflineDirectSigner` | N | | **signAmino** | - | **signer**: `string`,
**signDoc**: `StdSignDoc`,
**signOptions**?: `SignOptions` | `AminoSignResponse` | Y | | **signDirect** | - | **signer**: `string`,
**signDoc**: `StdSignDoc`,
**signOptions**?: `SignOptions` | `DirectSignResponse` | Y | | **sendTx** | - | **tx**: `Uint8Array`,
**mode**: `BroadcastMode` | `Uint8Array` | Y | ### Advanced **Used for deeper dive into the chain and wallet related objects** | Name | Description | Type | Default | | --------------- | ------------------------------------------------------------------ | ------------------------------ | ----------- | | **chainWallet** | current chainWallet | `ChainWalletBase \| undefined` | `undefined` | | **walletRepo** | wallet repository, you can get all the chainWallets from this repo | `WalletRepo` | - | ## Examples ### [fetch address](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/index.tsx) ### [fetch balance & send tokens](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/tx.tsx) ---------------------------------- Use Chains ## Hook - useChains - required provider: [**ChainProvider**](../provider/chain-provider) from either `@cosmos-kit/react` or `@cosmos-kit/react-lite` > To use `useChains` with `ChainProvider` from `@cosmos-kit/react-lite`, property [`walletModal`](../provider/chain-provider#walletmodal) must be provided. Or you can choose `ChainProvider` from `@cosmos-kit/react`, which provides `DefaultModal`. Or you can use [`useChainWallet`](./use-chain-wallet) instead. - parameters: - **chainNames**: `ChainName[]` - **sync**: `boolean` = `true` > parameter `sync` means whether to synchronize connection and disconnection to all other activated chainWallets. - return type: **Record<ChainName, [**ChainContext**](./use-chain#type---chaincontext)>** ## Usage ```jsx export default function () { const chains = useChains(['cosmoshub', 'osmosis', 'stargaze', 'juno', 'akash']); const connected = Object.values(chains).every(chain => chain.isWalletConnected); const { connect, openView } = chains.cosmoshub; // Notice: calling chains.chainName.connect() will connect to all 5 chains above. return
Code Value
chains.cosmoshub.address {chains.cosmoshub.address}
chains.osmosis.address {chains.osmosis.address}
chains.stargaze.address {chains.stargaze.address}
chains.juno.address {chains.juno.address}
chains.akash.address {chains.akash.address}
; } ``` ---------------------------------- Use Iframe ## Hook - useIframe - required provider: [**ChainProvider**](../provider/chain-provider) from either `@cosmos-kit/react` or `@cosmos-kit/react-lite` - parameters: - **walletName?**: `WalletName` ( = `string` ); - **walletInfo?**: `{ prettyName?: string; logo?: string }` - **accountReplacement?**: `(chainId: string) => AccountReplacement | Promise | undefined` - **walletClientOverrides?**: `Partial>>` - **aminoSignerOverrides?**: `Partial>>` - **directSignerOverrides?**: `Partial>>` > `walletName` optionally chooses a wallet to use, like the > [`useWallet`](./use-wallet) hook. If unset, the main wallet is used. > > `walletInfo` optionally sets the iframe's connected wallet metadata. If unset, > the currently connected wallet metadata is used. > > `accountReplacement` optionally overrides the account details returned from > the wallet. > > `walletClientOverrides`, `aminoSignerOverrides`, and `directSignerOverrides` > allow fine-grained control over the various client methods such that the > controlling app can heavily customize the wallet passthrough experience. For > example, this allows the app to manually handle and wrap messages from the > nested app, like a smart contract wallet may want to do. > > Explore the types to better understand how to implement advanced functionality. - return type: **`{ wallet: MainWalletBase; iframeRef: RefCallback}`** ## Usage ```jsx export default function () { const { iframeRef } = useIframe(); const { connect, disconnect, isWalletConnected } = useChain("cosmoshub"); return (
); } ``` ---------------------------------- Use Manager ## Hook - useManager - required provider: [**ChainProvider**](../provider/chain-provider) from either `@cosmos-kit/react` or `@cosmos-kit/react-lite` - return type: [**ManagerConext**](#type---managerconext) ## Type - ManagerConext ### properties | Name | Description | Type | Default | | ---------------------- | -------------------------------------------------------------------------------- | ------------------ | ------- | | **chainRecords** | contains all chain registry and assets information | `ChainRecord[]` | [] | | **walletRepos** | contains all chain wallets information, each wallet repo identified with a chain | `WalletRepo[]` | [] | | **mainWallets** | all main wallets information | `MainWalletBase[]` | [] | | **defaultNameService** | - | `NameServiceName` | `icns` | ### methods | Name | Description | Parameters | Return Type | Is Async | | ------------------ | ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------- | -------- | | **getChainRecord** | get the basic info of a chain, which contains registry and assets information for this chain | **chainName**: `ChainName` | `ChainRecord` | N | | **getChainLogo** | get chain logo url | **chainName**: `ChainName` | `string \| undefined` | N | | **getWalletRepo** | get the wallet repository of a chain, which stores all chain wallets for this chain | **chainName**: `ChainName` | `WalletRepo` | N | | **getNameService** | get name service object supported on provided chain, if chain not provided, using `defaultNameService` in `ChainProvider` | **chainName?**: `ChainName` | `NameService` | Y | | **addChains** | add new chains in provider | **chains**: `Chain[]`,
**assetLists**: `AssetList[]`,
**signerOptions**?: `SignerOptions`,
**endpoints**?: `EndpointOptions["endpoints"]` | `void` | N | | **addEndpoints** | add new endpoints | **endpoints**: `EndpointOptions["endpoints"]` | `void` | N | | **on** | attach event handler to [events](#events) | **event**: `EventName`,
**handler**: `(params: any) => void` | `void` | N | | **off** | remove attached event handler | **event**: `EventName`,
**handler**: `(params: any) => void` | `void` | N | ## Events ### refresh_connection Every time the registered events `connectEventNamesOnWindow` and `connectEventNamesOnClient` (see [wallet registry](../integrating-wallets/adding-new-wallets#optional-properties)) are triggered, and the dapp has been connected to the corresponding wallet, the `refresh_connection` event will also be triggered. ## Examples ### [add chain](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/add-chain.tsx) ---------------------------------- Use Modal Theme ## Hook - useModalTheme If you're using default modal provided by CosmosKit, you might need this hook to get and set modal theme. - required provider: [**ChainProvider**](../provider/chain-provider) from `@cosmos-kit/react` ## Return Type - useModalTheme ### properties | Name | Description | Type | Default | | ----------- | ----------- | -- | -- | | **modalTheme** | currently `light` or `dark` or `system` are available | `ModePreference` | `light` | ### methods | Name | Description | Parameters | Return Type | Is Async | | ----------- | ----------- | -- | -- | -- | | **setModalTheme** | - | **theme**: `ModePreference` | `void` | N | ## Examples ### [dashboard](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/index.tsx) ---------------------------------- Use Name Service ## Hook - useNameService - required provider: [**ChainProvider**](../provider/chain-provider) from either `@cosmos-kit/react` or `@cosmos-kit/react-lite` - parameters: - **name?**: `NameServiceName` ( = `string` ); > Note: `name` is optional. if `name` is not provided, using the `defaultNameService` in `ChainProvider` - return type: [**Mutable\**](#type---mutablenameservice) ## Type - Mutable\ ### properties | Name | Description | Type | Default | | ----------- | ----------- | -- | -- | | **state** | - | `State` | `State.Init` | | **data** | - | `NameService` | `undefined` | | **message** | - | `string` | `undefined` | > Note: `state`, `data` and `message` are react states. ## Examples ### [name service](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/ns2.tsx) ---------------------------------- Use Wallet Client ## Hook - useWalletClient - required provider: [**ChainProvider**](../provider/chain-provider) from either `@cosmos-kit/react` or `@cosmos-kit/react-lite` - parameters: - **walletName?**: `WalletName` ( = `string` ); > if `walletName` is `undefined`, using `currentWallet` instead. See LocalStorage key `cosmos-kit@2:core//current-wallet` - return type: [**WalletClientContext**](#type---walletclientcontext) ## Type - WalletClientContext ### Properties | Name | Description | Type | Default | | ----------- | ------------------------------------------- | --------------------------- | ------------ | | **client** | wallet client | `WalletClient \| undefined` | `undefined` | | **status** | wallet client status | `State` | `State.Init` | | **message** | error message if wallet client is undefined | `string \| undefined` | `undefined` | ## Examples ### [get account](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/tx.tsx) ---------------------------------- Use Wallet ## Hook - useWallet - required provider: [**ChainProvider**](../provider/chain-provider) from either `@cosmos-kit/react` or `@cosmos-kit/react-lite` - parameters: - **walletName?**: `WalletName` ( = `string` ); - **activeOnly**: `boolean` (default to be `true`); > If `walletName` is `undefined`, using `currentWallet` instead. See LocalStorage key `cosmos-kit@2:core//current-wallet`. If `currentWallet` is also undefined, return default values. > If `activeOnly` is `true`, only look at chainWallets with `isActive` true. When `useChain` is called, corresponding chainWallet will be activated. - return type: [**WalletContext**](#type---walletcontext) ## Type - WalletContext ### Properties | Name | Description | Type | Default | | ---------------- | ------------------------------------------------------------------------------- | --------------------- | --------------------------- | | **mainWallet** | the mainWallet | `MainWalletBase | undefined` | | **chainWallets** | all the chainWallets (including chains that not be called by useChain) | `ChainWalletBase[]` | `[]` | | **wallet** | wallet registry information | `Wallet \| undefined` | `undefined` | | **status** | global wallet status involves all active chainWallets if `activeOnly` is `true` | `WalletStatus` | `WalletStatus.Disconnected` | | **message** | - | `string \| undefined` | `undefined` | ## Examples ### [global wallet status](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/example/pages/index.tsx) ---------------------------------- Integrating Wallets # Wallet Integrations ## Wallet Providers If you are a wallet provider, please see the docs for adding your wallet to our repository as a supported wallet: #### 🔌 [Documentation for Wallet Providers to add a new Wallet](./integrating-wallets/adding-new-wallets) ## Dapp developers ### Supported Wallets See left sidebar (Titles starting with `@` are wallets supported by CosmosKit). ---------------------------------- Adding All Wallets # How to Add All Wallets at Once The `cosmos-kit` package exports all supported `wallets` in CosmosKit. ## Add `cosmos-kit` ```sh # npm npm i cosmos-kit # pnpm pnpm i cosmos-kit # yarn yarn add cosmos-kit ``` ## Import the wallets ```js import { wallets } from "cosmos-kit"; ``` ## Add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ## Subset of wallets ```js import { wallets } from 'cosmos-kit' wallets.mobile // An array of mobile wallets wallets.extension // An array of extension wallets wallets.for('keplr', 'cosmostation') // [KeplrExtensionWallet, KeplrMobileWallet, CosmostationExtensionWallet, CosmostationMobileWallet] wallets.for('keplr', 'cosmostation').mobile // [KeplrMobileWallet, CosmostationMobileWallet] wallets.for('keplr', 'cosmostation').extension // [KeplrExtensionWallet, CosmostationExtensionWallet] wallets.not('coin98', 'compass') // wallets except Coin98 and Compass wallets.keplr // [KeplrExtensionWallet, KeplrMobileWallet] wallets.keplr.mobile // KeplrMobileWallet wallets.keplr.extension // KeplrExtensionWallet ``` ---------------------------------- Adding New Wallets # How to Integrate New Wallets into CosmosKit ## Quickly Add Extension Wallets 1. Copy files in [Leap Extension](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/leap-extension/src/extension) to your package; 2. Replace `Leap` with your wallet name (_with first letter capitalized_) **globally**; 3. Replace `leap` with your wallet name (_with first letter in lowercase_) **globally**; 4. Edit file `client.ts`, `registry.ts`, `types.ts` and `utils.ts`. Replace what is different from Leap with the new wallet specified methods/properties. 5. Construct the MainWallet (_class in `main-wallet.ts`_) instance and put it into `ChainProvider` `wallets` property. ## Quickly Add Mobile Wallets ### For wallets support [Wallet Connect v2.0](https://docs.walletconnect.com/2.0) 1. Copy files in [Keplr Mobile](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/keplr-mobile/src/wallet-connect) to your package; 2. Replace `Keplr` with your wallet name (_with first letter capitalized_) **globally**; 3. Replace `keplr` with your wallet name (_with first letter in lowercase_) **globally**; 4. Edit file `client.ts`, `registry.ts` and `types.ts`. Replace what is different from Keplr with the new wallet specified methods/properties. For `client.ts`, the main replacement would happen in `getAppUrl` and the `method` parameter of `sendCustomRequest` 5. Construct the MainWallet (_class in `main-wallet.ts`_) instance and put it into `ChainProvider` `wallets` property. ## Add New Wallets from Scratch ### 1️⃣ Prepare basic information for wallet #### Required properties | Key | Type | Description | | ------------------------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | **name** | `WalletName = string` | identifier | | **prettyName** | `string` | display name | | **mode** | `WalletMode = 'extension' \| 'wallet-connect'` | wallet client type | | **mobileDisabled**\* | `boolean` | display on mobile or not | | **walletconnect** | `{ name: string; projectId: string; encoding?: BufferEncoding }` | only required when you are integrating mobile wallets based on [walletconnect](https://walletconnect.com/). If `encoding` is undefined, by default using `hex` to encode bytes | \* Usually `true` when **mode** is `wallet-connect`, `false` when **mode** is `extension`. #### Optional properties | Key | Type | Description | | ----------------------------- | ---------------| ------------------------| | **rejectMessage** | `string` \| `{ source: string; target?: string }` | `rejectMessage` or `rejectMessage.source` is error message string thrown by wallet app/extension when user rejects, while `rejectMessage.target` is `message` returned by hooks. If not provided, `target` would be `'Request Rejected!'` | | **connectEventNamesOnWindow** | `string[]` | window event names to fire auto-connect | | **connectEventNamesOnClient** | `string[]` | wallet client event names to fire auto-connect (make sure `on` and `off` methods are defined in [`WalletClient`](#2-implement-walletclient)) | | **downloads** | [`DownloadInfo[]`](https://github.com/hyperweb-io/cosmos-kit/blob/ce50648487e73c1f6f17777347df7984168381af/packages/core/src/types/wallet.ts#L28-L31) | wallet app/extension download information | | **logo** | `string` \| `{ major: string, minor: string }` | wallet logo url, display on default modal. For MetaMask Snaps, use `logo: { major: METAMASK_LOGO, minor: WALLET_LOGO }`| | **extends** | 'MetaMask' | indicate it's a MetaMask Snap #### Examples - [Keplr Extension - Wallet Info](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/keplr-extension/src/extension/registry.ts) - [Keplr Mobile - Wallet Info](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/keplr-mobile/src/wallet-connect/registry.ts)jk ### 2️⃣ Implement `WalletClient` `MainWallet` is a class organizing all `ChainWallet`s. **It should extend `MainWalletBase` class**, in which protected `_chainWallets` property stores all `ChainWallet`s. #### Required methods | Key | Type | Description | | -------------------- | --------------------------------------------- | ------------------------------------------------------- | | **getSimpleAccount** | `(chainId: string) => Promise` | return account with address but without pubkey and algo | #### Optional methods | Key | Type | Description | | -------------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | | **getAccount** | `(chainId: string) => Promise`\* | return account with address, pubkey and algo | | **getOfflineSigner** | `(chainId: string, preferredSignType?: SignType) => Promise` | prioritize returning `preferredSignType` (by default `amino`) corresponding signer if it is available, otherwise return siger that is provided. | | **enable** | `(chainIds: string \| string[]) => Promise` | give permission for the webpage to access wallet | | **addChain** | `(chainInfo: ChainRecord) => Promise` | add new Cosmos-SDK based blockchains that isn't natively integrated to wallet app/extension | | **on** | `(type: string, listener: EventListenerOrEventListenerObject) => void` | add event listener | | **off** | `(type: string, listener: EventListenerOrEventListenerObject) => void` | remove event listener | #### Examples - [Keplr Client](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/keplr-extension/src/extension/client.ts) ### 3️⃣ Extend `ChainWalletBase` Create a `ChainWallet` class that extends `ChainWalletBase`. `ChainWallet` provides wallet information for a particular chain, e.g. `address`, `offlineSigner`, etc. `ChainWalletBase` has implemented a bunch of methods such as wallet connection, sign, broadcast, etc. [[learn more]](#). Therefore, normally you don't need to do any extra work inside `ChainWallet`. But feel free to overwrite these methods or add new methods/properties if customization is needed to meet new demand. #### Examples - [Keplr Extension - Chain Wallet](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/keplr-extension/src/extension/chain-wallet.ts) - [Keplr Mobile - Chain Wallet](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/keplr-mobile/src/wallet-connect/chain-wallet.ts) ### 4️⃣ Extend `MainWalletBase` Create a `MainWallet` class that extends `MainWalletBase`. `MainWallet` organizes all `ChainWallet`s, which are stored in protected member `_chainWallets`. > Note: Class `ChainWallet` created in [Step 3](#3-extend-chainwalletbase) is required in `MainWalletBase` construction. #### Required methods | Key | Type | | -------------- | ------------------------------------------ | | **initClient** | `() => void \| Promise`\* | \* `WalletClient` is the one implemented in [Step 2](#2-implement-walletclient). Also, feel free to overwrite methods in `MainWalletBase` or add new methods/properties if necessary. #### Examples - [Keplr Extension - Main Wallet](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/keplr-extension/src/extension/main-wallet.ts) - [Keplr Mobile - Main Wallet](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/keplr-mobile/src/wallet-connect/main-wallet.ts) ### 5️⃣ Get `MainWallet` instance You can construct your `MainWallet` Instance according to your `MainWallet` construct method now. Usually the `walletInfo` object prepared in [Step 1](#1-prepare-basic-information-for-wallet) is imported here as a construction argument. #### Examples - [keplrExtension](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/keplr-extension/src/keplr.ts) & [keplrMobile](https://github.com/hyperweb-io/cosmos-kit/tree/main/wallets/keplr-mobile/src/keplr.ts) Last but not least, append this instance to the `wallets` property of [ChainProvider](../provider/chain-provider). ## 6️⃣ Don't Forget To Update Docs Add `Mardown File` just like other wallets [here](https://github.com/hyperweb-io/cosmos-kit/tree/main/packages/docs/pages/integrating-wallets). ---------------------------------- Compass # How to Add Compass Wallet to CosmosKit There are two packages for compass - `@cosmos-kit/compass` - `@cosmos-kit/compass-extension` `@cosmos-kit/compass` export all available compass wallets (currently only extension available), while if you only want to add a particular one, choose `@cosmos-kit/compass-extension` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/compass` for example ## add `@cosmos-kit/compass` ``` yarn add @cosmos-kit/compass ``` ## import the wallets ```js import { wallets as compass } from "@cosmos-kit/compass"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Cosmos Metamask Extension # How to Add Cosmos MetaMask Extension to CosmosKit - `@cosmos-kit/cosmos-extension-metamask` `@cosmos-kit/cosmos-extension-metamask` export wallets for connecting to the official Cosmos MetaMask Snap ## add `@cosmos-kit/cosmos-extension-metamask` ``` yarn add @cosmos-kit/cosmos-extension-metamask ``` ## import the wallets ```js import { wallets } from "@cosmos-kit/cosmos-extension-metamask"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Cosmostation # How to Add Cosmostation Wallet to CosmosKit There are three packages for cosmostation - `@cosmos-kit/cosmostation` - `@cosmos-kit/cosmostation-extension` - `@cosmos-kit/cosmostation-mobile` (using walletconnect v1, v2 is coming soon) `@cosmos-kit/cosmostation` export all available cosmostation wallets, while if you only want to add a particular one, choose `@cosmos-kit/cosmostation-extension` or `@cosmos-kit/cosmostation-mobile` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/cosmostation` for example ## add `@cosmos-kit/cosmostation` ``` yarn add @cosmos-kit/cosmostation ``` ## import the wallets ```js import { wallets as cosmostation } from "@cosmos-kit/cosmostation"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Exodus # How to Add Exodus Wallet to CosmosKit There are two packages for exodus - `@cosmos-kit/exodus` - `@cosmos-kit/exodus-extension` `@cosmos-kit/exodus` export all available exodus wallets (currently only extension available), while if you only want to add a particular one, choose `@cosmos-kit/exodus-extension` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/exodus` for example ## add `@cosmos-kit/exodus` ``` yarn add @cosmos-kit/exodus ``` ## import the wallets ```js import { wallets as exodus } from "@cosmos-kit/exodus"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Fin # How to Add Fin Wallet to CosmosKit There are two packages for fin - `@cosmos-kit/fin` - `@cosmos-kit/fin-extension` `@cosmos-kit/fin` export all available fin wallets (currently only extension available), while if you only want to add a particular one, choose `@cosmos-kit/fin-extension` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/fin` for example ## add `@cosmos-kit/fin` ``` yarn add @cosmos-kit/fin ``` ## import the wallets ```js import { wallets as fin } from "@cosmos-kit/fin"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Frontier # How to Add Frontier Wallet to CosmosKit There are two packages for frontier - `@cosmos-kit/frontier` - `@cosmos-kit/frontier-extension` `@cosmos-kit/frontier` export all available frontier wallets (currently only extension available), while if you only want to add a particular one, choose `@cosmos-kit/frontier-extension` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/frontier` for example ## add `@cosmos-kit/frontier` ``` yarn add @cosmos-kit/frontier ``` ## import the wallets ```js import { wallets as frontier } from "@cosmos-kit/frontier"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Keplr # How to Add Keplr Wallet to CosmosKit There are three packages for keplr - `@cosmos-kit/keplr` - `@cosmos-kit/keplr-extension` - `@cosmos-kit/keplr-mobile` `@cosmos-kit/keplr` export all available keplr wallets, while if you only want to add a particular one, choose `@cosmos-kit/keplr-extension` or `@cosmos-kit/keplr-mobile` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/keplr` for example ## install `@cosmos-kit/keplr` ``` yarn add @cosmos-kit/keplr ``` ## import the wallets ```js import { wallets as keplr } from "@cosmos-kit/keplr"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Leap Capsule Social Login # @cosmos-kit/leap-capsule-social-login `@cosmos-kit/leap-capsule-social-login` is the social login integration for CosmosKit using `@leapwallet/cosmos-social-login-capsule-provider` > You need install [@leapwallet/cosmos-social-login-capsule-provider-ui](https://www.npmjs.com/package/@leapwallet/cosmos-social-login-capsule-provider-ui) package for UI. > When you build it please have the environment variables `CAPSULE_API_KEY` and `CAPSULE_ENV` which you can request from [here](https://7f4shq8oyfd.typeform.com/to/F86oVLhb?typeform-source=usecapsule.com) ## NextJS For nextjs we recommend to load the module dynamic or async as it is not yet supporting SSR. > When you build it please have the environment variables `NEXT_PUBLIC_CAPSULE_API_KEY` and `NEXT_PUBLIC_CAPSULE_ENV` which you can request from [here](https://7f4shq8oyfd.typeform.com/to/F86oVLhb?typeform-source=usecapsule.com) ### In next.config.js > transpilePackages: ["@cosmos-kit/leap-social-login", "@leapwallet/capsule-web-sdk-lite", "@leapwallet/cosmos-social-login-capsule-provider"], ### For example ```jsx function MyApp({ Component, pageProps }: AppProps) { const defaultWallets: MainWalletBase[] = [...keplrWallets, ...leapWallets]; const [wallets, setWallets] = useState(defaultWallets) const [loadingWallets, setLoadingWallet] = useState(false); useEffect(() => { setLoadingWallet(true) import("@cosmos-kit/leap-capsule-social-login").then( (CapsuleModule) => { return CapsuleModule.wallets; }, ).then((leapSocialLogin) => { setWallets([...keplrWallets, ...leapWallets, ...leapSocialLogin]) setLoadingWallet(false); }) }, []) if (loadingWallets) { return <>Loading... } return ( ); } export default MyApp; const LeapSocialLogin = dynamic( () => import("@leapwallet/cosmos-social-login-capsule-provider-ui").then( (m) => m.CustomCapsuleModalView, ), { ssr: false }, ); export function CustomCapsuleModalViewX() { const [showCapsuleModal, setShowCapsuleModal] = useState(false); useEffect(() => { window.openCapsuleModal = () => { setShowCapsuleModal(true); } }, []) return ( <> { window.successFromCapsuleModal(); }} onLoginFailure={ () => { window.failureFromCapsuleModal(); } } /> ); } ``` ---------------------------------- Leap Metamask Comos Snap # How to Add Leap Metamask Cosmos Snap to CosmosKit - `@cosmos-kit/leap-metamask-cosmos-snap` `@cosmos-kit/leap-metamask-cosmos-snap` export wallets for connecting to the leap cosmos snap in metamask ## add `@cosmos-kit/leap-metamask-cosmos-snap` ``` yarn add @cosmos-kit/leap-metamask-cosmos-snap ``` ## import the wallets ```js import { wallets } from "@cosmos-kit/leap-metamask-cosmos-snap"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Leap # How to Add Leap Wallet to CosmosKit There are three packages for leap - `@cosmos-kit/leap` - `@cosmos-kit/leap-extension` - `@cosmos-kit/leap-mobile` - `@cosmos-kit/leap-metamask-cosmos-snap` `@cosmos-kit/leap` export all available leap wallets, while if you only want to add a particular one, choose `@cosmos-kit/leap-extension` or `@cosmos-kit/leap-mobile` or `@cosmos-kit/leap-metamask-cosmos-snap` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/leap` for example ## add `@cosmos-kit/leap` ``` yarn add @cosmos-kit/leap ``` ## import the wallets ```js import { wallets as leap } from "@cosmos-kit/leap"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Ledger # How to Add Ledger to CosmosKit ## Prerequisites 1. Connect your Ledger device via an USB cable and unlock it. 2. Open the Cosmos app in Ledger, which shows `Cosmos Ready` in the screen. ## Browser Support This package uses the [WebUSB](https://caniuse.com/webusb) API to connect to Ledger devices. We recommend using the latest version of Chrome and Chrome Android. - https://developer.mozilla.org/en-US/docs/Web/API/USB/getDevices - https://developer.mozilla.org/en-US/docs/Web/API/USB/requestDevice ## Add `@cosmos-kit/ledger` ```sh # npm npm i @cosmos-kit/ledger # pnpm pnpm i @cosmos-kit/ledger # yarn yarn add @cosmos-kit/ledger ``` ## Import the wallets ```js import { wallets as ledger } from "@cosmos-kit/ledger"; ``` ## Add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Ninji # How to Add Ninji Wallet to CosmosKit There are two packages for ninji - `@cosmos-kit/ninji` - `@cosmos-kit/ninji-extension` `@cosmos-kit/ninji` export all available ninji wallets (currently only extension available), while if you only want to add a particular one, choose `@cosmos-kit/ninji-extension` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/ninji` for example ## add `@cosmos-kit/ninji` ``` yarn add @cosmos-kit/ninji ``` ## import the wallets ```js import { wallets as ninji } from "@cosmos-kit/ninji"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Okx # How to Add Okx Wallet to CosmosKit There are two packages for okxwallet - `@cosmos-kit/okxwallet` - `@cosmos-kit/okxwallet-extension` `@cosmos-kit/okxwallet` export all available okxwallet wallets, while if you only want to add a particular one, choose `@cosmos-kit/okxwallet-extension` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/okxwallet` for example ## install `@cosmos-kit/okxwallet` ``` yarn add @cosmos-kit/okxwallet ``` ## import the wallets ```js import { wallets as okxwallet } from "@cosmos-kit/okxwallet"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Omni # How to Add Omni Wallet to CosmosKit There are two packages for omni - `@cosmos-kit/omni` - `@cosmos-kit/omni-mobile` `@cosmos-kit/omni` export all available omni wallets (currently only mobile available), while if you only want to add a particular one, choose `@cosmos-kit/omni-mobile` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/omni` for example ## add `@cosmos-kit/omni` ``` yarn add @cosmos-kit/omni ``` ## import the wallets ```js import { wallets as omni } from "@cosmos-kit/omni"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Shell # How to Add Shell Wallet to CosmosKit There are three packages for shell - `@cosmos-kit/shell` - `@cosmos-kit/shell-extension` `@cosmos-kit/shell` export all available shell wallets, while if you only want to add a particular one, choose `@cosmos-kit/shell-extension` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/shell` for example ## install `@cosmos-kit/shell` ``` yarn add @cosmos-kit/shell ``` ## import the wallets ```js import { wallets as shell } from "@cosmos-kit/shell"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Station # How to Add Station Wallet to CosmosKit There are two packages for station - `@cosmos-kit/station` - `@cosmos-kit/station-extension` `@cosmos-kit/station` export all available station wallets (currently only extension available), while if you only want to add a particular one, choose `@cosmos-kit/station-extension` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/station` for example ## add `@cosmos-kit/station` ``` yarn add @cosmos-kit/station ``` ## import the wallets ```js import { wallets as station } from "@cosmos-kit/station"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Trust # How to Add Trust Wallet to CosmosKit There are three packages for Trust - `@cosmos-kit/trust` - `@cosmos-kit/trust-extension` (NOT recommended) - `@cosmos-kit/trust-mobile` > 💡 According to [Trust Doc](https://developer.trustwallet.com/developer/develop-for-trust/browser-extension), Trust Wallet Browser Extension currently supports only Ethereum & EVM chains, and support for Cosmos is still in progress. Because of the block from wallet side, `@cosmos-kit/trust-extension` is not fully implemented yet and we don't recommend to use it for now. > > Because of the reason above, only `@cosmos-kit/trust-mobile` is included in `@cosmos-kit/trust` so far. Take `@cosmos-kit/trust` for example ## install `@cosmos-kit/trust` ``` yarn add @cosmos-kit/trust ``` ## import the wallets ```js import { wallets as trust } from "@cosmos-kit/trust"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Vectis # How to Add Vectis Wallet to CosmosKit There are two packages for vectis - `@cosmos-kit/vectis` - `@cosmos-kit/vectis-extension` `@cosmos-kit/vectis` export all available vectis wallets (currently only extension available), while if you only want to add a particular one, choose `@cosmos-kit/vectis-extension` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/vectis` for example ## add `@cosmos-kit/vectis` ``` yarn add @cosmos-kit/vectis ``` ## import the wallets ```js import { wallets as vectis } from "@cosmos-kit/vectis"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Web3auth # How to Add Web3Auth Wallet to CosmosKit > ### Note! This package is still on progress. it doesn't work on mobile yet and it's pretty vulnerable to XSS attacks. There is one package for web3auth - `@cosmos-kit/web3auth` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` ## install `@cosmos-kit/web3auth` ``` yarn add @cosmos-kit/web3auth ``` ## import the wallets ```js import { makeWeb3AuthWallets, PromptSign } from "@cosmos-kit/web3auth"; import { useMemo, useState } from "react"; ``` ## set up web3auth account to retrieve a client ID https://web3auth.io/docs/dashboard-setup/ ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { const [web3AuthPrompt, setWeb3AuthPrompt] = useState<{ signData: SignData resolve: (approved: boolean) => void } | undefined>(); const web3AuthWallets = useMemo( () => makeWeb3AuthWallets({ loginMethods: [ // add whichever login methods you want to support { provider: "google", name: "Google", logo: "https://upload.wikimedia.org/wikipedia/commons/5/53/Google_%22G%22_Logo.svg", }, ], // get client ID and network from your web3auth dashboard: // https://web3auth.io/docs/dashboard-setup/get-client-id client: { clientId: "localhostid", web3AuthNetwork: "testnet", }, // set state to show data to sign and approve/reject buttons in modal promptSign: async (_, signData) => new Promise((resolve) => setWeb3AuthPrompt({ signData, resolve: (approved) => { setWeb3AuthPrompt(undefined); resolve(approved); }, }) ), }), [] ); return ( {/* wallet signature prompt */} web3AuthPrompt?.resolve(false)} > web3AuthPrompt?.resolve(true)} reject={() => web3AuthPrompt?.resolve(false)} /> ); } export default MyCosmosApp; ``` ---------------------------------- Xdefi # How to Add Xdefi Wallet to CosmosKit There are two packages for xdefi - `@cosmos-kit/xdefi` - `@cosmos-kit/xdefi-extension` `@cosmos-kit/xdefi` export all available xdefi wallets (currently only extension available), while if you only want to add a particular one, choose `@cosmos-kit/xdefi-extension` > Note: all these packages export `wallets` and it's an array of `MainWalletBase` Take `@cosmos-kit/xdefi` for example ## add `@cosmos-kit/xdefi` ``` yarn add @cosmos-kit/xdefi ``` ## import the wallets ```js import { wallets as xdefi } from "@cosmos-kit/xdefi"; ``` ## add to your provider ```js function MyCosmosApp({ Component, pageProps }: AppProps) { return ( ); } export default MyCosmosApp; ``` ---------------------------------- Chain Provider Chain Provider provides necessary information for [hooks](../hooks). There are two `ChainProvider` from two packages (`@cosmos-kit/react` and `@cosmos-kit/react-lite`) respectively. They are basically the same only except that `ChainProvider` from `@cosmos-kit/react` has more properties of `default modal` (See [Properties for default modal ](#optional-properties-only-for-default-modal) below). > Note: `preferredSignType` in [`signerOptions`](#signeroptions) determines which signer to use when signing document. By default using `amino` type. ## Required Properties These properties are shared by `ChainProvider`s from `@cosmos-kit/react` and `@cosmos-kit/react-lite`. ### chains Required property of type `(Chain | string)[]`. It defines supported chains. Any actions involving chains beyond it might cause errors. If chain has been registered in `@chain-registry/client`, you can also simply provide chain name (type `string`) here and it'll fetch the chain information automatically. See [`Chain` schema](https://github.com/cosmos/chain-registry/blob/master/chain.schema.json). #### adding localnet and testnets Example of adding `localosmosis` `_app.tsx`: ```ts import { ChainProvider } from '@cosmos-kit/react'; import { wallets } from '@cosmos-kit/keplr'; import { assets, chains } from 'chain-registry'; import { getSigningCosmosClientOptions } from 'osmojs'; import { GasPrice } from '@cosmjs/stargate'; import { SignerOptions } from '@cosmos-kit/core'; import { Chain, AssetList } from '@chain-registry/types'; import { localosmosis, localosmosisAssets } from '../config/localosmosis'; function App({ Component, pageProps }: AppProps) { const localosmosis: Chain = {...}; // with chain_name: 'localosmosis' const localosmosisAssets: AssetList = {...}; // with chain_name: 'localosmosis' const signerOptions: SignerOptions = { signingStargate: (_chain: Chain) => { return getSigningCosmosClientOptions(); }, signingCosmwasm: (chain: Chain) => { switch (chain.chain_name) { case 'localosmosis': return { gasPrice: GasPrice.fromString('0.0025uosmo') }; } } }; return ( ); } ``` ### wallets Required property of type `MainWalletBase[]` It defines supported wallets. There are several wallets out of box. ```ts import { wallets as keplrWallet } from "@cosmos-kit/keplr"; import { wallets as cosmostationWallets } from "@cosmos-kit/cosmostation"; import { wallets as leapwallets } from "@cosmos-kit/leap"; ``` If you don't like the default wallet settings such as icon, app name (they would be displayed on default modal), you can choose to provide your own settings by importing wallets like this. ```ts import { KeplrExtensionWallet, KeplrMobileWallet } from '@cosmos-kit/keplr'; const keplrExtensionInfo: Wallet = {...}; const keplrMobileInfo: Wallet = {...}; const keplrExtension = new KeplrExtensionWallet(keplrExtensionInfo); const KeplrMobile = new KeplrMobileWallet(keplrMobileInfo); export const wallets = [keplrExtension, KeplrMobile]; ``` In addition, you can integrate new wallets in a few steps. 🔌 [How to integrate new wallets into CosmosKit](../integrating-wallets/adding-new-wallets) ### walletconnectOptions Required when `mobile` wallets dependent on `@comos-kit/walletconnect`(implements walletconnect v2 connection) are added in [`wallets`](#wallets). **Type:** `WalletConnectOptions` ```tsx export interface WalletConnectOptions { signClient: { projectId: string } & SignClientTypes.Options; } ``` `projectId` is required and can be obtained from [WalletConnect Cloud](https://cloud.walletconnect.com/sign-in). Create (or use an existing) dapp project and copy its associated project id. ## Optional Properties ### assetLists Optional property of type `AssetList[]` (comes from `chain-registry`) It provides chains related assets information. If not provided, will fetch assets information with `@chain-registry/client` according to the chain name provided in [`chains`](#chains). See [`AssetList` schema](https://github.com/cosmos/chain-registry/blob/master/assetlist.schema.json). ### walletModal Optional in most cases (Exception see [useChain](../hooks/use-chain)). **Type**: `({ isOpen, setOpen, walletRepo }: WalletModalProps) => JSX.Element` Basically the order of wallets follows the order of property `wallets` in ChainProvider, except that all mobiles are moved to the back. You can also define your own modal component with required props. #### customize modal with `walletModal` > Suggest customizing modal with [`modalViews`](#modalviews) instead if you only need to customize modal UI without involving any customized data logic. [`modalViews`](#modalviews) provides an easy and fast way to partially change the default modal UI. Example of using self-defined modal. `_app.tsx`: ```tsx import * as React from 'react'; import { ChainProvider } from '@cosmos-kit/react'; // Define Modal Component const MyModal = ({ isOpen, setOpen, walletRepo, theme }: WalletModalPropsV2) => { function onCloseModal() { setOpen(false); } return ( Choose Wallet {walletRepo.wallets.map(({ walletName, connect }) => ( ))} ); }; function CosmosApp() { return ( ); } ``` ### defaultNameService **Type:** `NameServiceName` = `string`; Currently two name services are registered: `'icns'` and `'stargaze'`. The default name service is `icns`. This property is only used in `getNameService` of `useManager` when parameter `chainName` is undefined, and in `useNameService` when the parameter `name` is not provided. Otherwise it will return the name service object corresponding to provided chain. Therefore it won't affect `getNameService` method returned by `useChain`, since `chainName` is always provide in `useChain`. ### endpointOptions Optional property. Define preferred endpoints for each chain. **Type:** `EndpointOptions` > Note: From `@cosmos-kit/core@1.2.1` `EndpointOptions` type changes a little bit ```tsx export type ChainName = string; export interface ExtendedHttpEndpoint extends HttpEndpoint { isLazy?: boolean; } export interface Endpoints { rpc?: (string | ExtendedHttpEndpoint)[]; rest?: (string | ExtendedHttpEndpoint)[]; isLazy?: boolean; } // Expired Type: `type EndpointOptions = Record` export interface EndpointOptions { isLazy?: boolean; endpoints?: Record; } ``` **Example:** ```tsx ``` #### isLazy **`isLazy` Explanation:** `isLazy` is used to control endpoints validation (get the fastest one when first validating). - When `isLazy` is `false`, will do endpoints validation - When `isLazy` is `true`, will **disable** endpoints validation - When `isLazy` is `undefined`, will inherit higher level explicitly set `isLazy`. If none is explicitly set, will do endpoints validation There are four levels of `isLazy` setting. **Four Levels of `isLazy`:** 1. Global `isLazy`: `isLazy` in `EndpointOptions` is the highest level with the lowerst priority, which is meant to globally control all endpoints. 2. Chain `isLazy`: `isLazy` in `Endpoints` will control all endpoints for a particular chain. If `isLazy` in `EndpointOptions` and `isLazy` in `Endpoints` are all set and don't agree, the latter predominates. 3. Endpoint `isLazy`: `isLazy` in `ExtendedHttpEndpoint` only controls the one in `ExtendedHttpEndpoint` object. For signing or broadcasting a transaction, this one is the lowerst level and with the highest priority. 4. Parameter `isLazy`: `isLazy` in `getRpcEndpoint` and `getRestEndpoint` parameters. It also globally controls all endpoints. (Note: this one only affects getting endpoint functions with the highest priority, but won't affect signing or broadcasting a transaction.) The calculation of final `isLazy` can be seen [here](https://github.com/hyperweb-io/cosmos-kit/blob/main/packages/core/src/utils/endpoint.ts#L32-L59). **`isLazy` Examples:** - Disabling all endpoints validation ```tsx endpointOptions={{ isLazy: true }} ``` - Disabling `cosmoshub` endpoints validation ```tsx endpointOptions={{ cosmoshub: { isLazy: true } }} ``` - Disabling a particular endpoint validation ```tsx endpointOptions={{ cosmoshub: { rpc: [{ url: 'http://test.com', isLazy: true, }] } }} ``` ### sessionOptions Define connection session options. **Type:** `SessionOptions` ```tsx export interface SessionOptions { duration: number; // ms callback?: () => void; // when session expires } ``` **Default:** ```tsx const sessionOptions: SessionOptions = { duration: 1800000, // half an hour callback: () => { this.mainWallets.forEach((w) => w.disconnectAll(false)); window?.localStorage.removeItem("cosmos-kit@2:core//current-wallet"); }, }; ``` ### signerOptions Optional property. ```ts import * as React from "react"; import { Chain } from "@chain-registry/types"; import { chains } from "chain-registry"; import { GasPrice } from "@cosmjs/stargate"; import { getSigningCosmosClientOptions } from "interchain"; import { SignerOptions } from "@cosmos-kit/core"; import { ChainProvider } from "@cosmos-kit/react"; import { wallets } from '@cosmos-kit/keplr'; // construct signer options const signerOptions: SignerOptions = { signingStargate: (chain: Chain) => { // return corresponding stargate options or undefined return getSigningCosmosClientOptions(); }, signingCosmwasm: (chain: Chain) => { // return corresponding cosmwasm options or undefined switch (chain.chain_name) { case "osmosis": return { gasPrice: GasPrice.fromString("0.0025uosmo"), }; case "juno": return { gasPrice: GasPrice.fromString("0.0025ujuno"), }; } }, preferredSignType: (chain: Chain) => { // `preferredSignType` determines which signer is preferred for `getOfflineSigner` method. By default `amino`. It might affect the `OfflineSigner` used in `signingStargateClient` and `signingCosmwasmClient`. But if only one signer is provided, `getOfflineSigner` will always return this signer, `preferredSignType` won't affect anything. return 'amino'; } }; function CosmosApp() { return ( ); } ``` ### logLevel Optional property. By default `WARN`. **Type:** `'TRACE' | 'DEBUG' | 'INFO' | 'WARN' | 'ERROR' | 'NONE'` Will disable logs lower than the value of `logLevel` (The log level order is the same with the order above). If `logLevel` is `NONE`, no logs would be printed. ### throwErrors Optional property. By default `false`. **Type:** `boolean | 'connect_only'` If set `true`, will throw error when wallet status to be `WalletStatus.Error`, `WalletStatus.Rejected` or `WalletStatus.NotExist`, or wallet client status to be `State.Error`. If set `connect_only`, will only throw connect errors. ### subscribeConnectEvents Optional property. By default `true`. **Type:** `boolean` If set `false`, will NOT subscribe registered `connectEventNamesOnWindow` and `connectEventNamesOnClient` in [wallet registry](../integrating-wallets/adding-new-wallets#optional-properties). ## Optional Properties Only for Default Modal These properties **only** exist in `ChainProvider` from `@cosmos-kit/react`, and only counts when property [`walletModal`](#walletmodal) is `undefined`. ### modalTheme Optional property to customize default modal theme. **Type** ```tsx type ThemeCustomizationProps = Pick< // This type comes from @interchain-ui/react ThemeProviderProps, "defaultTheme" | "overrides" | "themeDefs" | "customTheme" >; ``` ### modalViews Optional property of type `ModalViews`. **Type** ```tsx type ModalViewImpl = { head: React.ReactNode; content: React.ReactNode; }; type ModalViewImplGetter = ( props: WalletViewProps | WalletListViewProps ) => ModalViewImpl; type ModalViews = { Connecting?: (props: WalletViewProps) => ModalViewImplGetter; Connected?: (props: WalletViewProps) => ModalViewImplGetter; Error?: (props: WalletViewProps) => ModalViewImplGetter; NotExist?: (props: WalletViewProps) => ModalViewImplGetter; Rejected?: (props: WalletViewProps) => ModalViewImplGetter; QRCode?: (props: WalletViewProps) => ModalViewImplGetter; } & { WalletList?: (props: WalletListViewProps) => JSX.Element; }; export interface WalletViewProps { onClose: () => void; onReturn: () => void; wallet: ChainWalletBase; } export interface WalletListViewProps { onClose: () => void; wallets: ChainWalletBase[]; } ``` #### customize modal with `modalViews` Example of using self-defined modal views. `_app.tsx`: ```tsx import * as React from 'react'; import { ChainProvider } from '@cosmos-kit/react'; // Define Modal Connected View Component const ConnectedView = ({ onClose, onReturn, wallet, }: WalletViewProps) => { const { walletInfo: { prettyName }, username, address, } = wallet; return
{`${prettyName}/${username}/${address}`}
; }; function CosmosApp() { return ( ); } ``` ### modalOptions - `mobile.displayQRCodeEveryTime` By default `false`. When set `true`, it'll cause all existing pairings be removed everytime wallet is disconnected. It corresponds to the `DisconnectOptions.walletconnect.removeAllPairings` in `disconnect` method. ### includeAllWalletsOnMobile Optional property. By default `false`, which means on mobile only wallets with registry value of `mobileDisabled` (or returned value of `mobileDisabled` function) is `false` or `undefined` be displayed on wallet list page of default modal. For example, most `extension` wallets are set `mobileDisabled` `true`. Therefore you can't see `extension` wallets on mobile by default. If you want to see all wallets on mobile, set `includeAllWalletsOnMobile` `true`;