### Installing Dependencies (Bash)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/templates/next-wagmi-template/README.md
Installs the necessary project dependencies using either npm or yarn package managers. This is the first step after cloning the repository.
```bash
npm install
#or
yarn
```
--------------------------------
### Running Development Server (Bash)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/templates/next-wagmi-template/README.md
Starts the Next.js development server, making the application accessible locally, typically at http://localhost:3000. The server supports hot-reloading for development.
```bash
npm run dev
# or
yarn dev
```
--------------------------------
### Scaffolding a Sei Application using CLI
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/README.md
This command executes the `@sei-js/create-sei app` CLI tool, which launches an interactive setup wizard. The wizard guides the user through selecting a project template, including framework options like Next.js or Vite.js and blockchain interaction methods like EVM or Cosmos.
```Shell
npx @sei-js/create-sei app
```
--------------------------------
### Installing Dependencies with npm or yarn (Bash)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/templates/vite-cosmos-template/README.md
This command installs the necessary project dependencies listed in the package.json file. Use either npm install or yarn depending on your preferred package manager.
```bash
npm install
```
```bash
yarn
```
--------------------------------
### Installing Dependencies (npm/yarn)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/templates/vite-wagmi-template/README.md
Commands to install project dependencies using either npm or yarn package managers. This is the first step to set up the project.
```bash
npm install
#or
yarn
```
--------------------------------
### Installing Dependencies with npm or yarn (Bash)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/templates/next-cosmos-template/README.md
These commands are used to install the necessary project dependencies listed in the package.json file. You can choose either npm or yarn based on your preference.
```bash
npm install
```
```bash
yarn
```
--------------------------------
### Install @sei-js/registry Package (Bash)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/registry/README.md
Installs the @sei-js/registry package using the Yarn package manager.
```bash
yarn add @sei-js/registry
```
--------------------------------
### Installing @sei-js/ledger
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/ledger/README.md
Command to add the @sei-js/ledger package to your project using Yarn.
```bash
yarn add @sei-js/ledger
```
--------------------------------
### Running Development Server with npm or yarn (Bash)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/templates/vite-cosmos-template/README.md
This command starts the local development server, typically configured in the package.json scripts. It allows you to view and interact with the application in a browser, often with hot-reloading enabled.
```bash
npm run dev
```
```bash
yarn dev
```
--------------------------------
### Example Usage with StargateClient
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/ledger/README.md
Demonstrates connecting to a Sei testnet RPC, deriving an address using Ledger, creating a signer, and signing/broadcasting a delegation transaction using @cosmjs/stargate.
```typescript
import {
coins,
SigningStargateClient,
StdFee
} from "@cosmjs/stargate";
import {
createTransportAndApp,
getAddresses,
SeiLedgerOfflineAminoSigner
} from "@sei-js/ledger";
const testApp = async () => {
const validatorAddress = "seivaloper1sq7x0r2mf3gvwr2l9amtlye0yd3c6dqa4th95v";
const rpcUrl = "https://rpc-testnet.sei-apis.com/";
const memo = "Delegation";
const path = "m/44'/60'/0'/0/0";
const {app} = await createTransportAndApp();
const {nativeAddress} = await getAddresses(app, path);
const ledgerSigner = new SeiLedgerOfflineAminoSigner(app, path)
const signingStargateClient = await SigningStargateClient.connectWithSigner(rpcUrl, ledgerSigner)
const msgDelegate = {
typeUrl: "/cosmos.staking.v1beta1.MsgDelegate",
value: {
delegatorAddress: nativeAddress.address,
validatorAddress: validatorAddress,
amount: coins(500, "usei"),
},
};
const fee: StdFee = {
amount: [{denom: "usei", amount: "20000"}],
gas: "200000",
};
const result = await signingStargateClient.signAndBroadcast(nativeAddress.address, [msgDelegate], fee, memo)
console.log("Broadcast result:", result);
};
testApp();
```
--------------------------------
### Installing Sei EVM Library with Yarn
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/evm/README.md
Command to add the `@sei-js/evm` package and its required peer dependencies (`ethers`, `viem`) using Yarn.
```bash
yarn add @sei-js/evm ethers viem
```
--------------------------------
### Running Development Server with npm or yarn (Bash)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/templates/next-cosmos-template/README.md
These commands start the local development server for the Next.js application. The server typically runs on http://localhost:3000 and supports hot-reloading.
```bash
npm run dev
```
```bash
yarn dev
```
--------------------------------
### Running Development Server (npm/yarn)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/templates/vite-wagmi-template/README.md
Commands to start the local development server for the application using either npm or yarn. The application will typically be accessible in a web browser after running this command.
```bash
npm run dev
# or
yarn dev
```
--------------------------------
### Initializing an Ethers Wallet
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Provides an example of how to create a random Ethers wallet and connect it to a local RPC provider. This wallet is used for signing messages and sending transactions in the subsequent confidential transfer examples. Requires the `ethers` library.
```Typescript
const provider = new ethers.JsonRpcProvider("http://localhost:8545");
const testWallet = ethers.Wallet.createRandom().connect(provider);
```
--------------------------------
### Installing @sei-js/cosmjs Package (Bash)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Command to add the @sei-js/cosmjs package to your project using Yarn. This is the first step to integrate the library into your development environment.
```Bash
yarn add @sei-js/cosmjs
```
--------------------------------
### Installing Sei Global Wallet Package (bash)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/sei-global-wallet/README.md
This JavaScript import statement registers the Sei Global Wallet provider with EIP-6963 compatible wallet interfaces. It makes the wallet discoverable by applications that support the EIP-6963 standard.
```javascript
import "@sei-js/sei-global-wallet/eip6963";
```
--------------------------------
### Importing Encoding Utilities from @sei-js/cosmos/encoding (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmos/README.md
Provides examples of importing the main Encoder class, aminoConverters for legacy signing, and seiProtoRegistry for @cosmjs/stargate clients from the @sei-js/cosmos/encoding package. These imports are necessary prerequisites for using the encoding and decoding features.
```typescript
// Import Encoder, then follow the path to the desired module
import { Encoder } from '@sei-js/cosmos/encoding';
// Import Amino converters for legacy Cosmos SDK support
import { aminoConverters } from "@sei-js/cosmos/encoding";
// Import typeUrl registry for cosmjs Stargate clients
import { seiProtoRegistry } from "@sei-js/cosmos/encoding";
```
--------------------------------
### Using createTransportAndApp
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/ledger/README.md
Imports and calls the createTransportAndApp function to establish a connection to the Ledger device and get the Sei app instance.
```typescript
import { createTransportAndApp } from '@sei-js/ledger';
const { transport, app } = await createTransportAndApp();
console.log(transport, app);
```
--------------------------------
### Performing IBC Transfer and Signing/Broadcasting using @sei-js/cosmjs
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Demonstrates how to perform an IBC token transfer using `getSigningStargateClient`. It also includes an example of creating a DEX message, calculating a fee, and signing/broadcasting a transaction using the client.
```tsx
import { calculateFee } from '@cosmjs/stargate';
import { getSigningStargateClient } from '@sei-js/cosmjs';
// Don't forget to connect if using a wallet extension
// or create a wallet from a mnemonic (See above)
await window.compass.connect(chainId);
const offlineSigner = await window.compass.getOfflineSigner(chainId);
const signingClient = await getSigningStargateClient(RPC_URL, offlineSigner);
const amount = { amount: SEND_AMOUNT, denom: TOKEN_DENOM };
const ibcResponse = await signingClient.sendIbcTokens(SENDER_ADDRESS, DESTINATION_ADDRESSS, amount, 'transfer', CHANNEL_ID, undefined, undefined, fee)
// Create message to place an order
const { placeOrders } = seiprotocol.seichain.dex.MessageComposer.withTypeUrl;
const msg = placeOrders({ contractAddr, creator, funds, orders });
const fee = calculateFee(150000, "0.1usei");
// Sign and broadcast the message
const response = signingClient.signAndBroadcast(firstAccount.address, [msg], fee);
```
--------------------------------
### Getting Signing Stargate Client with Custom Registry
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Demonstrates how to create a `SigningStargateClient` using a custom registry that includes both default Cosmos types and Sei protocol-specific types, allowing for interaction with custom Sei messages.
```tsx
import { Registry } from "@cosmjs/proto-signing";
import { defaultRegistryTypes } from "@cosmjs/stargate";
import { getSigningStargateClient } from '@sei-js/cosmjs';
import { seiprotocol, seiprotocolProtoRegistry } from "@sei-js/proto";
// Set up Sei proto registry
const registry = new Registry([
...defaultRegistryTypes,
...seiprotocolProtoRegistry,
]);
// Create a client with registry
const signingClient = await getSigningStargateClient(RPC_URL, offlineSigner, { registry });
```
--------------------------------
### Executing Smart Contract Message (Mint NFT) using SigningCosmWasmClient
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Provides an example of executing a smart contract message (specifically a 'mint' message) using the `SigningCosmWasmClient`. It shows how to define the execute message, calculate a fee, and call the `execute` method.
```tsx
import { getSigningCosmWasmClient } from "@sei-js/cosmjs";
const offlineSigner = await window.compass.getOfflineSigner(chainId);
// Create a CosmWasmClient
const signingCosmWasmClient = await getSigningCosmWasmClient(RPC_URL, offlineSigner);
// Execute a message on a smart contract
const fee = calculateFee(150000, "0.1usei");
const msg = { mint: {} };
const result = await signingCosmWasmClient.execute(SENDER_ADDRESS, CONTRACT_ADDRESS, msg, fee);
```
--------------------------------
### Getting SigningCosmWasmClient for Executions using @sei-js/cosmjs
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Explains how to get a `SigningCosmWasmClient` instance using `getSigningCosmWasmClient` from `@sei-js/cosmjs`. This client is required for executing messages on smart contracts and needs an offline signer.
```tsx
import { getSigningCosmWasmClient } from "@sei-js/cosmjs";
const offlineSigner = await window.compass.getOfflineSigner(chainId);
// Create a CosmWasmClient
const signingCosmWasmClient = await getSigningCosmWasmClient(RPC_URL, offlineSigner);
```
--------------------------------
### Using Ledger with Sei-js for Transaction Signing
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmos/README.md
Explains how to set up a Ledger device with @sei-js/ledger and @cosmjs/stargate to sign and broadcast a staking delegation transaction. It covers creating the transport, getting the address, initializing the signer, setting up amino types and the signing client, creating the message, and broadcasting the transaction.
```typescript
import {createTransportAndApp, SeiLedgerOfflineAminoSigner} from "@sei-js/ledger";
import { Encoder } from '@sei-js/cosmos/encoding';
import { aminoConverters } from "@sei-js/cosmos/encoding";
import { AminoTypes, SigningStargateClient, coin } from "@cosmjs/stargate";
const hdPath = "m/44'/60'/0'/0/0"
const validatorAddress = "seivaloper1r0tmhjhxmvwlzq5sy3z83qnyvc74uvs9ykek9l";
const { app } = await createTransportAndApp();
const cosmosAddressData = await app.getCosmosAddress(hdPath, false);
const ledgerOfflineAminoSigner = new SeiLedgerOfflineAminoSigner(app, hdPath);
const aminoTypes = new AminoTypes(aminoConverters);
const signingStargateClient = await SigningStargateClient.connectWithSigner(
rpcUrl,
ledgerOfflineAminoSigner,
{ aminoTypes },
);
const fee = {
amount: [{denom: "usei", amount: "20000"}],
gas: "200000",
};
const msgDelegate = Encoder.cosmos.staking.v1beta1.MsgDelegate.fromPartial({
delegator_address: cosmosAddressData.address,
validator_address: validatorAddress,
amount: coin(2000, "usei"),
});
const protoMessage = { typeUrl: `/${Encoder.cosmos.staking.v1beta1.MsgDelegate.$type}`, value: msgDelegate };
// This will automatically get converted to the correct amino type due to the aminoTypes registry passed to the SigningStargateClient
const result = await signingStargateClient.signAndBroadcast(cosmosAddressData.address, [protoMessage], fee, memo)
if (result.code === 0) {
console.log("Transaction broadcast successfully:", result);
} else {
console.error("Error broadcasting transaction:", result.rawLog);
}
```
--------------------------------
### Getting Default Signing Stargate Client
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Illustrates how to obtain a `SigningStargateClient` configured with default Sei protocol registry and amino types by providing an RPC URL and an offline signer (e.g., from a connected wallet extension like Compass).
```tsx
import { getSigningStargateClient } from '@sei-js/cosmjs';
// Don't forget to connect if using a wallet extension
// or create a wallet from a mnemonic (See above)
await window.compass.connect(chainId);
const offlineSigner = await window.compass.getOfflineSigner(chainId);
const signingClient = await getSigningStargateClient(RPC_URL, offlineSigner);
```
--------------------------------
### Generating or Restoring a Sei Wallet (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Demonstrates how to generate a new wallet with a mnemonic phrase or restore an existing one using a seed phrase and HD path. It shows how to get the correct HD paths for Cosmos and EVM-compatible Sei addresses.
```TypeScript
import { getHdPath, generateWallet, restoreWallet } from "@sei-js/cosmjs";
const cosmosHdPath = getHdPath(0, 118); // This is the default path for Sei wallets account index 0
const evmHdPath = getHdPath(0, 60); // This is the default path for EVM wallets account index 0
// 12 word mnemonic by default
const generatedWallet = await generateWallet(24, cosmosHdPath);
console.log('generated mnemonic', generatedWallet.mnemonic);
// or restore a wallet given a seed phrase and coin type 60 HD path
const restoredWallet = await restoreWallet(SEED_PHRASE, evmHdPath);
console.log('restored mnemonic', restoredWallet.mnemonic);
```
--------------------------------
### Getting CosmWasmClient for Queries using @sei-js/cosmjs
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Shows how to obtain a `CosmWasmClient` instance using `getCosmWasmClient` from `@sei-js/cosmjs`. This client is suitable for querying smart contract state but not for executing messages.
```tsx
import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";
import { getCosmWasmClient } from "@sei-js/cosmjs";
// Create a CosmWasmClient
const cosmWasmClient = await getCosmWasmClient(RPC_URL);
```
--------------------------------
### Getting Address from Compressed Public Key (compressedPubKeyToAddress)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Derives the corresponding Bech32 address string from a byte array representing a compressed public key using the `compressedPubKeyToAddress` utility function.
```tsx
import { compressedPubKeyToAddress } from '@sei-js/cosmjs';
const address = compressedPubKeyToAddress(new Uint8Array([/* public key bytes */]));
console.log(address);
```
--------------------------------
### Initializing and Updating Git Submodules (Shell)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/registry/RUNBOOK.md
This command initializes, fetches, and checks out the specified commit for all submodules in the repository, including nested submodules.
```Shell
git submodule update --init --recursive
```
--------------------------------
### Connecting to Sei EVM and Using Address Precompile with Ethers v6
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/evm/README.md
Shows how to create an ethers provider and signer, request accounts, and interact with the `getAddressPrecompileEthersV6Contract` to retrieve the Cosmos address associated with an EVM address. Requires `@sei-js/evm` and `ethers`.
```ts
import { ADDRESS_PRECOMPILE_ADDRESS } from '@sei-js/evm';
import { ethers } from 'ethers';
const provider = new ethers.BrowserProvider(window.ethereum); // or any other provider
const signer = await provider.getSigner();
const accounts = await provider.send('eth_requestAccounts', []);
const contract = getAddressPrecompileEthersV6Contract(ADDRESS_PRECOMPILE_ADDRESS, signer);
const cosmosAddress = await contract.getSeiAddr(accounts[0]);
```
--------------------------------
### Setting up Wagmi Provider for Sei EVM (React)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/evm/README.md
Demonstrates how to configure the `WagmiProvider` with the Sei Arctic 1 chain and integrate it with `@tanstack/react-query` for state management in a React application. Requires `@sei-js/evm`, `wagmi`, and `@tanstack/react-query`.
```tsx
import { ReactNode } from 'react';
import { WagmiProvider } from 'wagmi';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ARCTIC_1_VIEM_CHAIN, createWagmiConfig } from '@sei-js/evm';
const queryClient = new QueryClient();
export const WalletProvider = ({ children }: { children: ReactNode }) => {
return (
{children}
);
};
```
--------------------------------
### Instantiating SeiLedgerOfflineAminoSigner
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/ledger/README.md
Imports and creates a new instance of SeiLedgerOfflineAminoSigner using the Ledger app instance and derivation path.
```typescript
import { SeiLedgerOfflineAminoSigner } from '@sei-js/ledger';
const ledgerSigner = new SeiLedgerOfflineAminoSigner(app, "m/44'/60'/0'/0/0");
```
--------------------------------
### Integrating CosmosKit with Sei Chains
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Demonstrates how to import and use Sei chain and asset list configurations from @sei-js/cosmjs within a CosmosKit ChainProvider component to set up wallet connections for multiple Sei networks.
```tsx
import { COSMOS_KIT_ASSET_LIST, PACIFIC_1_SEI_COSMOS_KIT_CHAIN, ATLANTIC_2_SEI_COSMOS_KIT_CHAIN, ARCTIC_1_SEI_COSMOS_KIT_CHAIN } from '@sei-js/cosmjs'
import { wallets } from '@cosmos-kit/keplr';
function CosmosApp() {
return (
);
}
```
--------------------------------
### Import and Use Registry Data (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/registry/README.md
Demonstrates how to import core data structures like TOKEN_LIST from the @sei-js/registry package and find a specific asset by its denom.
```typescript
import { TOKEN_LIST, NETWORKS, IBC_INFO, GAS_INFO } from '@sei-js/registry'
const uAtom = TOKEN_LIST.find(asset => asset.denom === 'uatom')
```
--------------------------------
### Sign and Broadcast Sei Transaction using @cosmjs/stargate (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmos/README.md
Demonstrates how to set up a @cosmjs/stargate SigningStargateClient using Sei's pre-built registry and amino converters. It shows how to create a MsgSend message, structure it for the Stargate client, and sign and broadcast the transaction using an offline signer.
```TypeScript
import { Encoder } from '@sei-js/cosmos/encoding';
import { seiProtoRegistry } from "@sei-js/cosmos/encoding";
import { aminoConverters } from "@sei-js/cosmos/encoding";
import {SigningStargateClient} from "@cosmjs/stargate";
import {Registry, AminoTypes} from "@cosmjs/proto-signing";
// or any other way to get an offline signer
const offlineSigner = await window.compass.getOfflineSigner("arctic-1");
const accounts = await offlineSigner.getAccounts();
// Create a @cosmjs/stargate registry with the Sei proto registry
const registry = new Registry(seiProtoRegistry);
const aminoTypes = new AminoTypes(aminoConverters);
// Create a Stargate client with the registry and amino types
const stargateClient = await SigningStargateClient.connectWithSigner(
"https://rpc-arctic-1.sei-apis.com",
offlineSigner,
{
aminoTypes: new AminoTypes(aminoConverters),
registry: new Registry(seiProtoRegistry),
}
);
// Create a MsgSend object
const msgSend = Encoder.cosmos.bank.v1beta1.MsgSend.fromPartial({
from_address: accounts[0].address,
to_address: "sei1v6459sl87jyfkvzmy6y8a6j2fj8k5r6x2n2l9",
amount: [{ denom: "usei", amount: "10" }]
});
// Create a message object with the typeUrl and value. (For Stargate clients the value isn't encoded, but gRPC clients typically require it to be encoded)
const message = { typeUrl: `/${Encoder.cosmos.bank.v1beta1.MsgSend.$type}`, value: msgSend };
const txResponse = await stargateClient.signAndBroadcast(accounts[0].address, [message], {
amount: [{ denom: "usei", amount: "100000" }],
gas: "200000"
});
console.log(txResponse.transactionHash);
```
--------------------------------
### Initialize Account using Viem/wagmi (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Creates a confidential account on the Sei network. This requires a signed denom and uses Viem and wagmi hooks (useAccount, usePublicClient, useWriteContract) to prepare transaction parameters, estimate gas, and write the contract.
```ts
import { getInitializeAccountViemArgs } from "sei-confidential";
import { useWriteContract, useAccount } from "wagmi";
import { usePublicClient } from "wagmi";
const { address } = useAccount();
const publicClient = usePublicClient();
const { writeContractAsync } = useWriteContract();
const txParams = await getInitializeAccountViemArgs(signedDenom, address, "usei");
const estimatedGas = await publicClient.estimateContractGas(txParams);
await writeContractAsync({ ...txParams, gas: estimatedGas });
```
--------------------------------
### Initializing a Confidential Account (Ethers)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Shows how to create a confidential account on the Sei chain for a specified address and denom using the `initializeAccountEthers` function. Requires the `signedDenom` signature (generated in Step 1), the wallet address, the denom, and the Ethers wallet object.
```Typescript
await initializeAccountEthers(signedDenom, wallet.address, denom, wallet);
```
--------------------------------
### Configuring CosmJS Signing Client with Sei Amino/Proto Types
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmos/README.md
Demonstrates how to initialize a @cosmjs/stargate SigningStargateClient with custom aminoConverters and seiProtoRegistry from @sei-js/cosmos/encoding. This is necessary for the client to correctly handle Sei-specific message types for signing.
```typescript
import { aminoConverters, seiProtoRegistry } from "@sei-js/cosmos/encoding";
import { AminoTypes, SigningStargateClient } from "@cosmjs/stargate";
import { Registry } from "@cosmjs/proto-signing";
const offlineSigner = await window.compass.getOfflineSigner
const signingStargateClient = await SigningStargateClient.connectWithSigner(
"https://rpc-arctic-1.sei-apis.com",
offlineSigner,
{
aminoTypes: new AminoTypes(aminoConverters),
registry: new Registry(seiProtoRegistry),
},
);
```
--------------------------------
### Suggesting Sei Chain to Keplr Wallet
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Shows how to use the `getChainSuggest` function from @sei-js/cosmjs to obtain the necessary chain information and then suggest it to a generic wallet like Keplr using its `suggestChain` API.
```tsx
import { getChainSuggest } from '@sei-js/cosmjs';
const chainSuggest = getChainSuggest();
await window.keplr.suggestChain(chainSuggest); // See the Keplr API docs for more information on chain suggestion.
```
--------------------------------
### Querying Sei User Balances via REST Client
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmos/README.md
Shows how to use the Querier class from @sei-js/cosmos/rest to fetch all balances for a given Sei address. It illustrates accessing the desired endpoint (cosmos.bank.v1beta1.AllBalances) and providing necessary parameters like the address and REST URL prefix.
```typescript
import { Querier } from '@sei-js/cosmos/rest';
// Follow the path to the desired module and message type
const { balances } = await Querier.cosmos.bank.v1beta1.AllBalances({ address: seiAddress }, { pathPrefix: chainConfig.restUrl });
```
--------------------------------
### Using SeiLedgerOfflineAminoSigner.signAmino
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/ledger/README.md
Demonstrates calling the signAmino method on a SeiLedgerOfflineAminoSigner instance to sign a StdSignDoc object using the Ledger device.
```typescript
import { SeiLedgerOfflineAminoSigner } from '@sei-js/ledger';
import { StdSignDoc } from '@cosmjs/amino';
const signDoc: StdSignDoc = { /* your StdSignDoc object */ };
const signResponse = await ledgerSigner.signAmino('sei123...', signDoc);
console.log(signResponse.signed, signResponse.signature);
```
--------------------------------
### Configuring ESLint for Type-Aware Linting (JavaScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/templates/vite-cosmos-template/README.md
This configuration snippet for ESLint's parserOptions enables type-aware linting rules by specifying the project's tsconfig files and the root directory. This is recommended for production applications to catch type-related issues during linting.
```javascript
export default {
// other rules...
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig.node.json'],
tsconfigRootDir: __dirname,
},
}
```
--------------------------------
### Using getAddresses
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/ledger/README.md
Imports and calls the getAddresses function with the Ledger app instance and derivation path to retrieve the EVM and native Cosmos addresses.
```typescript
import { getAddresses } from '@sei-js/ledger';
const { evmAddress, nativeAddress } = await getAddresses(app, "m/44'/60'/0'/0/0");
console.log(evmAddress, nativeAddress);
```
--------------------------------
### Creating TokenFactory Messages (MsgCreateDenom, MsgMint) with @sei-js/cosmos/types (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmos/README.md
Illustrates how to import and create objects conforming to the MsgCreateDenom and MsgMint types from the @sei-js/cosmos/types/tokenfactory module. It shows the structure for defining messages to create a new token denomination and mint tokens.
```typescript
// Import the MsgCreateDenom and MsgMint types from tokenfactory module
import type { MsgCreateDenom, MsgMint } from "@sei-js/cosmos/types/tokenfactory";
// Create an object that conforms to the MsgCreateDenom type
const msgCreateDenom: MsgCreateDenom = {
sender: accounts[0].address,
subdenom: "mytoken",
allow_list: {
addresses: ["sei123..."]
}
}
// Create an object that conforms to the MsgMint type
const msgMint: MsgMint = {
sender: accounts[0].address,
amount: { denom: "usei", amount: "100000" }
}
// Do what you want with the messages
```
--------------------------------
### Signing and Verifying Arbitrary Strings using @sei-js/cosmjs
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Demonstrates how to sign an arbitrary string using a wallet's `signArbitrary` function and then verify the resulting `StdSignature` using the `verifyArbitrary` function from `@sei-js/cosmjs` to prove account ownership off-chain.
```tsx
import { verifyArbitrary } from "@sei-js/cosmjs";
const SEI_ADDRESS = "sei1...";
const message = "Message to sign";
const stdSignature = await window.compass.signArbitrary('atlantic-2', SEI_ADDRESS, message); // or FIN_WALLET, KEPLR_WALLET, LEAP_WALLET
const isValid = await verifyArbitrary(SEI_ADDRESS, message, stdSignature);
```
--------------------------------
### Configuring ESLint for Type-Aware Rules (JS)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/create-sei/templates/vite-wagmi-template/README.md
Configuration snippet for an ESLint configuration file (.eslintrc.js or similar) to enable type-aware linting rules. It sets parserOptions to include project information for TypeScript checking.
```js
export default {
// other rules...
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig.node.json'],
tsconfigRootDir: __dirname,
},
}
```
--------------------------------
### Depositing into Confidential Account (Ethers)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Shows how to initiate a confidential deposit of a specified amount into the account using `depositToPrivateBalanceEthers`. Requires the denom, the deposit amount (specified in the native decimal place, e.g., 6 decimals for `usei`), and the Ethers wallet.
```Typescript
import { depositToPrivateBalanceEthers } from "confidential-ts";
const depositAmount = 1000000 // 1 SEI
await depositToPrivateBalanceEthers(denom, depositAmount, wallet);
```
--------------------------------
### Querying Smart Contract State using CosmWasmClient
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Demonstrates how to query the state of a smart contract using the `queryContractSmart` method of the `CosmWasmClient`. The structure of the `queryMsg` must conform to the specific contract's query interface.
```tsx
// Create the query msg json based on contract specific query specifications
const queryMsg = {
tokens: {
owner: address,
},
};
// Query a smart contract state
const queryResponse = cosmWasmClient.queryContractSmart(CONTRACT_ADDR, queryMsg);
```
--------------------------------
### Sending Tokens (Bank Send) with Sei-js Cosmjs (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Demonstrates the process of sending tokens using the bank module's sendTokens message via @sei-js/cosmjs. This involves connecting to a wallet, obtaining an offline signer, creating a signing client, calculating transaction fees, specifying the transfer amount, and executing the send transaction. It requires a connected wallet or a wallet created from a mnemonic.
```tsx
import { calculateFee } from '@cosmjs/stargate';
import { getSigningStargateClient } from '@sei-js/cosmjs';
// Don't forget to connect if using a wallet extension
// or create a wallet from a mnemonic (See above)
await window.compass.connect(chainId);
const offlineSigner = await window.compass.getOfflineSigner(chainId);
const signingClient = await getSigningStargateClient(RPC_URL, offlineSigner);
const fee = calculateFee(100000, "0.1usei");
const amount = { amount: SEND_AMOUNT, denom: TOKEN_DENOM };
const sendResponse = await signingClient.sendTokens(SENDER_ADDRESS, DESTINATION_ADDRESS, [amount], fee);
```
--------------------------------
### Creating Bank Send Message (MsgSend) with @sei-js/cosmos/types (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmos/README.md
Demonstrates importing and creating a MsgSend object for a bank transfer transaction using the types provided by @sei-js/cosmos/types. It shows the required fields (from_address, to_address, amount) and their structure for defining a send message.
```typescript
// Import the MsgSend type from the bank module
import { MsgSend } from '@sei-js/cosmos/types/cosmos/bank/v1beta1';
// Create an object that conforms to the MsgSend type
const msgSend: MsgSend = {
from_address: 'sei1hafptm4zxy5nw8rd2pxyg83c5ls2v62tstzuv2',
to_address: 'sei1v6459sl87jyfkvzmy6y8a6j2fj8k5r6x2n2l9',
amount: [{ denom: 'usei', amount: '100' }]
};
```
--------------------------------
### Create Sei Message using @sei-js/cosmos/types directly (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmos/README.md
Illustrates an optional approach to creating Cosmos SDK message objects for Sei by directly importing and using the types from @sei-js/cosmos/types. It shows how these typed objects can then be encoded and decoded using the Encoder from @sei-js/cosmos/encoding.
```TypeScript
import { MsgSend } from '@sei-js/cosmos/types/cosmos/bank/v1beta1';
import { Encoder } from '@sei-js/cosmos/encoding';
// This type can be used to create the proto message directly
const msgSend: MsgSend = {
from_address: 'sei1hafptm4zxy5nw8rd2pxyg83c5ls2v62tstzuv2',
to_address: 'sei1v6459sl87jyfkvzmy6y8a6j2fj8k5r6x2n2l9',
amount: [{ denom: 'usei', amount: '100' }]
};
// Encode the message
const encoded = Encoder.cosmos.bank.v1beta1.MsgSend.encode(msgSend).finish();
// Or if you have an encoded message, you can decode it
const decoded = Encoder.cosmos.bank.v1beta1.MsgSend.decode(encoded);
// Create the proto message using the typeUrl and encoded message
const protoMsgSend = { typeUrl: `/${MsgSend.$type}`, value: encoded };
```
--------------------------------
### Using SeiLedgerOfflineAminoSigner.getAccounts
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/ledger/README.md
Calls the getAccounts method on a SeiLedgerOfflineAminoSigner instance to retrieve the account data (address and public key).
```typescript
import { SeiLedgerOfflineAminoSigner } from '@sei-js/ledger';
const accounts = await ledgerSigner.getAccounts();
console.log(accounts); // { address: 'sei1...', pubkey: { type: 'tendermint/PubKeySecp256k1', value: '...' } }
```
--------------------------------
### Encoding and Decoding Messages with @sei-js/cosmos/encoding (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmos/README.md
Demonstrates how to use the Encoder from @sei-js/cosmos/encoding to encode a message object (like MsgSend) into a byte array and decode a byte array back into a message object. It also shows how to construct a protobuf message object with the correct type URL. Requires a message object, which can be created using @sei-js/cosmos/types.
```typescript
import { Encoder } from '@sei-js/cosmos/encoding';
// Follow the path to the desired module and message type
const msgSend = Encoder.cosmos.bank.v1beta1.MsgSend.fromPartial({
from_address: 'sei1hafptm4zxy5nw8rd2pxyg83c5ls2v62tstzuv2',
to_address: 'sei1v6459sl87jyfkvzmy6y8a6j2fj8k5r6x2n2l9',
amount: [{ denom: 'usei', amount: '100' }]
});
// Or use @sei-js/cosmos/types to create the message, see below.
// Encode the message
const encoded = Encoder.cosmos.bank.v1beta1.MsgSend.encode(msgSend).finish();
// Or if you have an encoded message, you can decode it
const decoded = Encoder.cosmos.bank.v1beta1.MsgSend.decode(encoded);
// Create the proto message using the typeUrl and encoded message
const protoMsgSend = { typeUrl: `/${MsgSend.$type}`, value: encoded };
```
--------------------------------
### Estimate Gas and Execute Contract Write (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Demonstrates how to use the pre-filled contract parameters returned by Sei JS Viem-compatible functions. It shows estimating the required gas using `publicClient.estimateContractGas` and then executing the contract write operation using `writeContractAsync` with the estimated gas.
```ts
const gas = await publicClient.estimateContractGas(generatedParams);
await writeContractAsync({ ...generatedParams, gas });
```
--------------------------------
### Query Account using Viem/wagmi (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Fetches the encrypted confidential balance and associated metadata for a specific account and denom from the blockchain using a Viem public client.
```ts
import { queryAccountViem } from "sei-confidential";
import { usePublicClient } from "wagmi";
const publicClient = usePublicClient();
const account = await queryAccountViem(publicClient, address, "usei");
```
--------------------------------
### Querying Confidential Account Info (Ethers)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Illustrates how to fetch the full confidential account state from the precompile contract using `queryAccountEthers`. Requires the wallet address, the denom, and the Ethers wallet object. Returns the account state object containing balance commitments.
```Typescript
import { queryAccountEthers } from "confidential-ts";
const account = await queryAccountEthers(wallet.Address, denom, wallet);
```
--------------------------------
### Applying Pending Balance (Ethers)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Demonstrates how to move any pending confidential balance into the available balance for spending using `applyPendingBalanceEthers`. Requires the wallet address, the denom, the `signedDenom` (generated in Step 1), and the Ethers wallet.
```Typescript
import { applyPendingBalanceEthers } from "confidential-ts";
await applyPendingBalanceEthers(wallet.address, denom, signedDenom, wallet);
```
--------------------------------
### Generate Signed Denom using Viem/wagmi (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Derives the unique keypair for a confidential account per denom. This involves appending "ct:" to the denom, hashing it with keccak256, and signing the hash with the user's wallet using wagmi's useSignMessage hook.
```ts
import { getDenomToSignViem } from "sei-confidential";
import { useSignMessage } from "wagmi";
const { signMessageAsync } = useSignMessage();
const denom = "usei";
const ctDenomHash = getDenomToSignViem(denom);
const signedDenom = await signMessageAsync({
message: ctDenomHash,
});
```
--------------------------------
### Parsing Sei Amount to Smallest Unit (uSei)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/evm/README.md
Demonstrates the usage of the `parseSei` utility function from `@sei-js/evm` to convert a string representation of a Sei amount into its equivalent value in uSei (attoSei), which is the smallest denomination.
```ts
import { parseSei } from '@sei-js/evm';
const amount = parseSei('1000000');
console.log(amount); // 1000000000000000000
```
--------------------------------
### Encode/Decode Sei Message using @sei-js/cosmos/encoding (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmos/README.md
Shows the recommended way to create, encode, and decode Cosmos SDK messages for Sei using the Encoder from @sei-js/cosmos/encoding. It highlights that the types are automatically handled, eliminating the need to import types separately in most cases.
```TypeScript
import { Encoder } from '@sei-js/cosmos/encoding';
// Encoder.cosmos.bank.v1beta1.MsgSend is already typed using the `MsgSend` type from the @sei-js/cosmos/types package
const msgSend = Encoder.cosmos.bank.v1beta1.MsgSend.fromPartial({
from_address: 'sei1hafptm4zxy5nw8rd2pxyg83c5ls2v62tstzuv2',
to_address: 'sei1v6459sl87jyfkvzmy6y8a6j2fj8k5r6x2n2l9'
});
// Encode the message
const encoded = Encoder.cosmos.bank.v1beta1.MsgSend.encode(msgSend).finish();
// Or if you have an encoded message, you can decode it
const decoded = Encoder.cosmos.bank.v1beta1.MsgSend.decode(encoded);
// Create the proto message using the typeUrl and encoded message
const protoMsgSend = { typeUrl: `/${Encoder.cosmos.bank.v1beta1.MsgSend.$type}`, value: encoded };
```
--------------------------------
### Aggregating Signatures and Broadcasting on Sei
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Collect all the individual signatures, aggregate them into a multi-signed transaction byte array, and broadcast the final transaction using a StargateClient.
```TypeScript
const broadcaster = await StargateClient.connect(rpcUrl);
const multiSigAccount = await broadcaster.getAccount(multiSigAccountAddress);
const multiSigPubkey = multiSigAccount.pubkey as unknown as MultisigThresholdPubkey;
const signatures = new Map([
[firstAddress, firstSignResponse.signatures[0]],
[secondAddress, secondSignResponse.signatures[0]],
// Repeat for however many signatures are required
]);
const multiSignedTxBytes = makeMultisignedTxBytes(
multiSigPubkey,
multiSigAccount.sequence,
TX_FEE,
firstSignResponse.bodyBytes, // or any signature since all signatures sign the same body
signatures
);
const result = await broadcaster.broadcastTx(multiSignedTxBytes);
```
--------------------------------
### Creating KeyPair from Public Key (pubKeyToKeyPair)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Creates a hex-encoded ECC KeyPair object from a given public key provided as a Uint8Array using the `pubKeyToKeyPair` utility function.
```tsx
import { pubKeyToKeyPair } from '@sei-js/cosmjs';
const keyPair = pubKeyToKeyPair(new Uint8Array([/* public key bytes */]));
console.log(keyPair);
```
--------------------------------
### Withdrawing from Confidential Account (Ethers)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Explains how to withdraw a specified amount from the confidential balance using `withdrawFromPrivateBalanceEthers`. Requires the wallet address, the denom, the withdraw amount (in native decimals), and the `signedDenom` (generated in Step 1).
```Typescript
import { withdrawFromPrivateBalanceEthers } from "confidential-ts";
const withdrawAmount = 1000000 // 1 SEI
await withdrawFromPrivateBalanceEthers(wallet.address, denom, withdrawAmount, signedDenom, wallet);
```
--------------------------------
### Querying Multi-sig Account on Sei
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Query the multi-sig account on chain to obtain its sequence and account number, which are necessary for signing transactions. Note that the account must have existed on chain (either received funds or broadcasted a transaction) for this query to succeed.
```TypeScript
import { getStargateClient } from '@sei-js/cosmjs';
const broadcaster = await getStargateClient(rpcUrl);
const multiSigAccount = await broadcaster.getAccount(multiSigAccountAddress);
const multiSigPubkey = account.pubkey as unknown as MultisigThresholdPubkey;
// If the account has not broadcasted any transactions, the pubkey will not be available.
if (!isMultisigThresholdPubkey(multiSigPubkey)) {
console.log('The account address you entered is not a multi-sig account that exists on chain.');
}
```
--------------------------------
### Signing a Denom (Ethers)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Demonstrates how to generate a unique signature for a specific denom using `getDenomToSignEthers` and an Ethers wallet. This signature is derived from a hash of the denom signed by the wallet and is essential for deriving confidential account keys. Requires an initialized Ethers wallet.
```Typescript
import { getDenomToSignEthers } from "confidential-ts";
const denom = "usei";
const denomHash = getDenomToSignEthers(denom);
const signedDenom = await wallet.signMessage(denomHash);
```
--------------------------------
### Transfer Confidential Tokens using Viem/wagmi (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Sends confidential tokens from one confidential account to another. The recipient must have already initialized their confidential account before they can receive a transfer.
```ts
import { getConfidentialTransferViemArgs } from "sei-confidential";
const transferParams = await getConfidentialTransferViemArgs(address, recipient, "usei", 500000, publicClient, signedDenom);
const estimatedGas = await publicClient.estimateContractGas(transferParams);
await writeContractAsync({ ...transferParams, gas: estimatedGas });
```
--------------------------------
### Hashing Compressed Public Key to Address (getAddressHashFromPubKey)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/cosmjs/README.md
Computes the SHA-256 hashed address (Uint8Array) for a given compressed public key (Uint8Array) using the `getAddressHashFromPubKey` utility function.
```tsx
import { getAddressHashFromPubKey } from '@sei-js/cosmjs';
const hashedAddress = getAddressHashFromPubKey(new Uint8Array([/* compressed public key */]));
console.log(hashedAddress);
```
--------------------------------
### Apply Pending Balance using Viem/wagmi (TypeScript)
Source: https://github.com/sei-protocol/sei-js/blob/main/packages/confidential-transfers/README.md
Moves tokens from the pending balance to the available balance within a confidential account. This step is necessary after receiving a deposit or a confidential transfer.
```ts
import { getApplyPendingBalancesViemArgs } from "sei-confidential";
const applyParams = await getApplyPendingBalancesViemArgs(address, "usei", publicClient, signedDenom);
const estimatedGas = await publicClient.estimateContractGas(applyParams);
await writeContractAsync({ ...applyParams, gas: estimatedGas });
```