JSPM

@cosmos-kit/react

0.17.1
  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 2061
  • Score
    100M100P100Q112100F
  • License SEE LICENSE IN LICENSE

cosmos-kit wallet connector

Package Exports

  • @cosmos-kit/react
  • @cosmos-kit/react/main/index.js
  • @cosmos-kit/react/module/index.js

This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@cosmos-kit/react) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.

Readme

cosmos-kit

Cosmos Kit is a wallet adapter for developers to build apps that quickly and easily interact with Cosmos blockchains and wallets.

@cosmos-kit/react is the React integration for Cosmos Kit.

Getting Start

1. Installation

yarn add @cosmos-kit/react @cosmos-kit/core @cosmos-kit/keplr chain-registry

2. Connection

First, add the WalletProvider to your app, and include the supported chains and supported wallets:

import * as React from 'react';

import { ChakraProvider } from '@chakra-ui/react';
import { WalletProvider } from '@cosmos-kit/react';
import { chains } from 'chain-registry';
import { wallets } from '@cosmos-kit/keplr';

function WalletApp() {
  return (
    <ChakraProvider theme={defaultTheme}>
      <WalletProvider
        chains={chains} // supported chains, include all chains in `chain-registry` here.
        wallets={wallets} // supported wallets, include `keplrExtension` and `KeplrMobile` here.
      >
        <YourWalletRelatedComponents />
      </WalletProvider>
    </ChakraProvider>
  )
}

Get wallet properties and functions using the useWallet hook:

import * as React from 'react';

import { useWallet } from "@cosmos-kit/react";

function Component ({ chainName }: { chainName?: string }) => {
    const walletManager = useWallet();

    // Get wallet properties
    const {
        currentChainName, 
        currentWalletName, 
        walletStatus, 
        username, 
        address, 
        message,
      } = walletManager;

    // Get wallet functions
    const { 
        connect, 
        disconnect, 
        openView,
        setCurrentChain,
    } = walletManager;

    // if `chainName` in component props, `setCurrentChain` in `useEffect`
    React.useEffect(() => {
        setCurrentChain(chainName);
    }, [chainName]);
}

3. Signing Clients

There two signing clients available via walletManager functions: getStargateClient() and getCosmWasmClient().

Using signing client in react component:

import * as React from 'react';
import { cosmos } from 'interchain'; 
import { StdFee } from '@cosmjs/amino';
import { useWallet } from "@cosmos-kit/react";

function Component () => {
    const walletManager = useWallet();
    const {
        getStargateClient,
        getCosmWasmClient,
        address,
      } = walletManager;

    const sendTokens = async () => {
      const stargateClient = await getStargateClient();
      if (!stargateClient || !address) {
          console.error('stargateClient undefined or address undefined.')
          return;
      }

      const { send } = cosmos.bank.v1beta1.MessageComposer.withTypeUrl;

      const msg = send({
        amount: [ { denom: 'uatom', amount: '1000' } ],
        toAddress: address, fromAddress: address
      });

      const fee: StdFee = { amount: [ { denom: 'uatom', amount: '864' } ], gas: '86364' };

      await stargateClient.signAndBroadcast(address, [msg], fee, memo);
    }
}

3.1 Customized signing client options

The default options are undefined. You can provide your own options in WalletProvider.

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 { WalletProvider } from '@cosmos-kit/react';
import { wallets } from '@cosmos-kit/config';

// construct signer options
const signerOptions: SignerOptions = {
  stargate: (chain: Chain) => {
     // return corresponding stargate options or undefined
    return getSigningCosmosClientOptions();
  },
  cosmwasm: (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')
        };
    }
  }
}

function WalletApp() {
  return (
      <WalletProvider
        chains={chains}
        wallets={wallets}
        signerOptions={signerOptions} // Provide signerOptions
      >
      <YourWalletRelatedComponents />
    </WalletProvider>
  )
}

The SignerOptions object has stargate and cosmwasm properties which are functions that return client options:

// in '@cosmos-kit/core'
import { SigningStargateClientOptions } from '@cosmjs/stargate';
import { SigningCosmWasmClientOptions } from '@cosmjs/cosmwasm-stargate';

export interface SignerOptions {
  stargate?: (chain: Chain) => SigningStargateClientOptions | undefined;
  cosmwasm?: (chain: Chain) => SigningCosmWasmClientOptions | undefined;
}

4 Customized modal

You can bring your own UI. The WalletProvider provides a default modal for connection in @cosmos-kit/react.

import { DefaultModal } from '@cosmos-kit/react';

To define your own modal, you can input you modal component in WalletProvider props.

Required properties in your modal component:

import { WalletModalProps } from '@cosmos-kit/core';

// in `@cosmos-kit/core`
export interface WalletModalProps {
  isOpen: boolean;
  setOpen: Dispatch<boolean>;
}

A simple example to define your own modal:

import * as React from 'react';

import { WalletProvider, useWallet } from '@cosmos-kit/react';

// Define Modal Component
const MyModal = ({ isOpen, setOpen }: WalletModalProps) => {
  const walletManager = useWallet();

  function onCloseModal () {
    setOpen(false);
  };

  function onWalletClicked(name: string) {
    return async () => {
      console.info('Connecting ' + name);
      walletManager.setCurrentWallet(name);
      await walletManager.connect();
    }
  }

  return (
    <Modal isOpen={open} onClose={onCloseModal}>
      <ModalContent>
        <ModalHeader>Choose Wallet</ModalHeader>
        <ModalCloseButton />
        <ModalBody>
          {walletManager.wallets.map(({ name, prettyName }) => (
            <Button key={name} colorScheme='blue' variant='ghost' onClick={onWalletClicked(name)}>
              {prettyName}
            </Button>
          ))}
        </ModalBody>
      </ModalContent>
    </Modal>
  )
}

function WalletApp() {
  return (
    <WalletProvider 
        chains={chains}
        wallets={wallets}
        walletModal={MyModal} // Provide walletModal
    >
      <YourWalletRelatedComponents />
    </WalletProvider>
  )
}

5. Other props in WalletProvider

5.1 endpointOptions

Define preferred endpoints for each chain.

export type ChainName = string;

export interface Endpoints {
  rpc?: string[];
  rest?: string[];
};

export type EndpointOptions = Record<ChainName, Endpoints>;

e.g.

<WalletProvider
  ...
  endpointOptions={{
    osmosis: {
      rpc: ['http://test.com']
    }
  }}
>

5.2 viewOptions

Define automation for view. Optional

export interface ViewOptions {
  closeViewWhenWalletIsConnected?: boolean;
  closeViewWhenWalletIsDisconnected?: boolean;
  closeViewWhenWalletIsRejected?: boolean;
}

// default value
const viewOptions: ViewOptions = {
  closeViewWhenWalletIsConnected: false,
  closeViewWhenWalletIsDisconnected: true,
  closeViewWhenWalletIsRejected: false,
};

5.3 storageOptions

Define local storage attributes. Optional

export interface StorageOptions {
  disabled?: boolean;
  duration?: number; // ms
  clearOnTabClose?: boolean;
}

// default value
const storageOptions: StorageOptions = {
  disabled: false,
  duration: 108000,
  clearOnTabClose: false
};

Credits

🛠 Built by Cosmology — if you like our tools, please consider delegating to our validator ⚛️