# Caishen SDK

Free multichain wallets for you, and agents

<figure><img src="https://1771091613-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbTXu7G9HOQOOI3HjOA4N%2Fuploads%2FXi0NirZiulTLCQ1ASqC4%2Fimage.png?alt=media&amp;token=5fa465ac-59a0-4b12-b7ca-67bb23f527af" alt=""><figcaption></figcaption></figure>

\
The Caishen SDK provides developers with seamless access to **unlimited** multi-chain crypto wallets. It offers a unified interface for interacting with various blockchain networks and managing crypto assets.

## Why Caishen?

Creating wallets or agents for your users traditionally requires you to pay into SaaS, with monthly subscriptions, additional per wallet fees, and limited support. Here's what Caishen offers:

* Unlimited wallets without the need for managing sensitive private keys
* Multi-chain support for EVM, Bitcoin, Solana, SUI, and XRP
* Cash, for agent-to-agent gasless payments and global stablecoin remittance

## Pricing

<figure><img src="https://1771091613-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbTXu7G9HOQOOI3HjOA4N%2Fuploads%2FpSuxqgeyKNgxvV2AeRKR%2Fimage.png?alt=media&amp;token=9414c9dd-7723-4cf6-b1d7-92e4d0044a30" alt=""><figcaption><p>Look familiar? Not with Caishen! Try it out for free today with zero limitations!</p></figcaption></figure>

## **It's Free.**&#x20;

We earn fees when developers choose to use our swaps, which contain our referral ID. But feel free to leave a tip!\ <br>


# Registration

Create wallets in minutes, with Caishen

*We've built the simplest wallet creation tool imaginable, and we're happy to share it with you.*

To get started with Caishen, register your account with an email and confirm the six-digit auth code that was sent. Upon your first time logging in to the Caishen dashboard you'll see an empty Projects page. This is where you will get your Project Key (Client ID) and Secret. It should take less than a minute to create a Project.&#x20;

<figure><img src="https://1771091613-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbTXu7G9HOQOOI3HjOA4N%2Fuploads%2FfTLOoM8osL2I1qAp8FvB%2FCaishen_register.gif?alt=media&amp;token=82cc3f33-f9cd-4e2a-b5de-0ca127f03a25" alt=""><figcaption><p>All you need is an email to get started</p></figcaption></figure>

Once you've created a project, you can start creating wallets!

***

<table data-view="cards"><thead><tr><th></th><th></th><th data-type="content-ref"></th><th data-hidden data-card-cover data-type="files"></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td>Typescript SDK</td><td>Create wallets via JS in seconds</td><td></td><td><a href="https://1771091613-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbTXu7G9HOQOOI3HjOA4N%2Fuploads%2FmZAeOHmpo7PiSZA9pnow%2Fcaishen-typescript.png?alt=media&amp;token=1d28fba4-a183-4e55-848b-b7cde8d1b968">caishen-typescript.png</a></td><td><a href="/installation">Installation</a></td></tr><tr><td>Python SDK</td><td>Create wallets cia Python in seconds</td><td></td><td><a href="https://1771091613-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbTXu7G9HOQOOI3HjOA4N%2Fuploads%2FjiATKO8u5A40tpemw0Nw%2Fcaishen-python.png?alt=media&amp;token=c97ee0f1-81c8-417e-9725-a65fd2bd99da">caishen-python.png</a></td><td><a href="/python-sdk/installation">Installation</a></td></tr><tr><td>React SDK (Coming Soon)</td><td></td><td></td><td><a href="https://1771091613-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbTXu7G9HOQOOI3HjOA4N%2Fuploads%2FELMNV3Q9UyDXyFT82UWF%2Fcaishen-react.png?alt=media&amp;token=c58c0ba4-2840-4cce-a6b2-02e8ecc7d65d">caishen-react.png</a></td><td></td></tr></tbody></table>


# Installation

## Caishen SDK – Plug & Play SDK JS&#x20;

The Caishen SDK provides developers with seamless access to multichain wallets and gasless payment tools. With built-in support for **Ethereum**, **Solana**, **Bitcoin**, **Sui**, and **XRP**, you can integrate wallets, automate agents, and send cash instantly using only a few lines of code.

Caishen supports **Typescript** (for browser and Node.js) and [**Python** ](/installation)(for backend automation and bots). You can build wallet-aware apps, agent-based bots, or embedded finance experiences with no seed phrases or infrastructure costs.

***

### Requirements

#### For Typescript (Node.js / Browser)

* Node.js v16+
* Basic understanding of Promises and async/await
* Supports React, Next.js, Vite, Vanilla JS, etc.

***

### Resources

* [**Example Applications**](/build-spotlight): View working wallet + cash agent integrations.
* [**Troubleshooting**](/support/faq): Common setup issues and sandbox tips.
* [**Source Code**](https://github.com/CaishenTech/caishen-sdk): Full SDK code and dev toolkits.
* [**Support Portal**:](https://discord.gg/tybyS3xSDz) Get help directly from the Caishen team or join the community.

### 📦 Installation

```
npm install @caishen/sdk
# or
yarn add @caishen/sdk
# or
pnpm add @caishen/sdk
```

> ⚠️ Requires Node.js ≥ 14.x and TypeScript ≥ 4.x

***

### 🚀 Quick Start

```
import { CaishenSDK, createAgentTools } from "@caishen/sdk";

const sdk = new CaishenSDK({ projectKey: "your-project-key" });
const tools = createAgentTools(sdk);
```

***

### 🔑 Authentication

You can authenticate as either a **user** or an **agent**.

#### Connect as User

```
await sdk.connectAsUser({
  token: 'USER TOKEN',
  provider: 'USER PROVIDER',
});
```

**✅ Supported Providers**

* `google`, `facebook`, `twitter`, `discord`, `github`, `linkedin`
* `reddit`, `line`, `kakao`, `weibo`, `farcaster`, `custom`

***

#### 🔐 Custom Authentication

If you want to authenticate users **from your own backend**, you can use the `custom` provider.

In this case:

* You must **encrypt a JWT** on your backend using your `projectSecret` (found in your Caishen developer dashboard).
* That encrypted token must contain an object like `{ id: string }`, where `id` is the user identifier in your system.
* You then pass this encrypted token into `connectAsUser`.

**💡 Example**

**Backend-side (Node.js):**

```
import jwt from 'jsonwebtoken';

const payload = { id: 'user-123' };
const token = jwt.sign(payload, projectSecret);
```

**Frontend-side:**

```
await sdk.connectAsUser({
  provider: 'custom',
  token: 'ENCRYPTED_JWT_TOKEN',
});
```

On the Caishen backend, this token is decrypted with your `projectSecret` using:

```
jwt.verify(token, projectSecret); // -> { id: string }
```

> ⚠️ Never share your `projectSecret` publicly. Only your server should have access to it.

***

#### Connect as Agent

```
await sdk.connectAsAgent({
  agentId: 'AGENT ID',
  userId: 'USER ID',
});
```

> Different values for `agentId` and `userId` will generate different wallet scopes.


# Creating Wallets

In order to get wallets, please ensure that you have [registered and installed the Caishen SDK](/registration).

With the Caishen SDK, you can create wallets for:

* EVM
* Bitcoin
* Solana
* SUI
* XRP

{% hint style="info" %}
All Caishen wallets come with support for crosschain swaps and sending&#x20;
{% endhint %}

<figure><img src="https://1771091613-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbTXu7G9HOQOOI3HjOA4N%2Fuploads%2FH1Gl5v311cuImMgD6FXf%2FAnimation.gif?alt=media&amp;token=c1c83ea8-1f21-4963-ad88-acd0292eabe3" alt=""><figcaption><p>It's this easy to create your multichain wallets</p></figcaption></figure>

#### 🔍 Get Wallet Info

> ⚠️ The `privateKey` is only returned if `allowPrivateKeyAccess` is enabled in your developer dashboard.\
> You do **not** need to send the private key back to the server. All you need is `{ account, chainType }`.

**📥 Parameters**

| Name        | Type   | Required | Description                                  |
| ----------- | ------ | -------- | -------------------------------------------- |
| `chainType` | string | ✅        | Blockchain type (`ETHEREUM`, `SOLANA`, etc.) |
| `chainId`   | number | ❌        | Optional chain ID (e.g., 1 for Ethereum)     |
| `account`   | number | ✅        | Account index or identifier                  |

**✅ Supported chainTypes:**

* `BITCOIN`, `SOLANA`, `ETHEREUM`, `SUI`, `APTOS`, `TON`
* `TRON`, `NEAR`, `XRP`, `CARDANO`, `COSMOS`

***

**📘 Example**

```
const wallet = await sdk.crypto.getWallet({
  chainType: 'ETHEREUM',
  chainId: 1,
  account: 0,
});
```

**📚 Type: `IWalletAccount`**

```
interface IWalletAccount {
  address: string;
  chainType: string;
  account: number;
  publicKey: string;
  privateKey?: string; // Only returned if access is enabled in the dashboard
}
```

<figure><img src="https://1771091613-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FbTXu7G9HOQOOI3HjOA4N%2Fuploads%2FEPLOoyJwsVJA2xnyHTUb%2Fimage.png?alt=media&amp;token=382e9259-c0de-4649-9543-07eed0b4d267" alt=""><figcaption><p>Copy your Project Key </p></figcaption></figure>

<details>

<summary>Example 1: Creating Wallets on EVM, Bitcoin, Solana, SUI &#x26; XRP</summary>

```
const { CaishenSDK } = require('@caishen/sdk');
const jwt = require('jsonwebtoken');
require('dotenv').config();

// 👤 One user
const userId = 'user-123'; // You can change this

// 🌐 Supported chains
const chains = [
  { name: 'Ethereum', chainType: 'ETHEREUM', chainId: 1 },
  { name: 'Solana', chainType: 'SOLANA', chainId: 101 },
  { name: 'Bitcoin', chainType: 'BITCOIN', chainId: 0 },
  { name: 'Sui', chainType: 'SUI', chainId: 1 },
  { name: 'XRP', chainType: 'XRP', chainId: 1 },
];

(async () => {
  try {
    const token = jwt.sign({ id: userId }, process.env.CAISHEN_PROJECT_SECRET);

    const sdk = new CaishenSDK({ projectKey: process.env.CAISHEN_PROJECT_KEY });
    await sdk.connectAsUser({
      provider: 'custom',
      token,
    });

    console.log(`✅ Connected as ${userId}\n`);

    for (const chain of chains) {
      try {
        const wallet = await sdk.crypto.getWallet({
          chainType: chain.chainType,
          chainId: chain.chainId,
          account: 0,
        });
        console.log(`✅ ${chain.name} Wallet:\n`, wallet, '\n');
      } catch (err) {
        console.error(`❌ Failed to create ${chain.name} wallet: ${err.message}\n`);
      }
    }
  } catch (err) {
    console.error('❌ Failed to connect user:', err.message);
  }
})();

```

</details>

<details>

<summary>Example 2: Creating Multiple Wallets for a Single User</summary>

```
const { CaishenSDK } = require('@caishen/sdk');
const jwt = require('jsonwebtoken');
require('dotenv').config();

// 👤 One user ID
const userId = 'user-123';

(async () => {
  try {
    // 🔐 Create JWT for this user
    const token = jwt.sign({ id: userId }, process.env.CAISHEN_PROJECT_SECRET);

    // 🔌 Create SDK instance + connect as user once
    const sdk = new CaishenSDK({ projectKey: process.env.CAISHEN_PROJECT_KEY });
    await sdk.connectAsUser({
      provider: 'custom',
      token,
    });

    // 🔁 Create 10 wallets (account 0 → 9)
    for (let i = 0; i < 10; i++) {
      try {
        const wallet = await sdk.crypto.getWallet({
          chainType: 'ETHEREUM',
          chainId: 1,
          account: i,
        });
        console.log(`✅ Wallet #${i} for ${userId}:`, wallet);
      } catch (err) {
        console.error(`❌ Failed to create wallet #${i}:`, err.message);
      }
    }
  } catch (err) {
    console.error(`❌ Failed to connect user:`, err.message);
  }
})();

```

</details>

<details>

<summary>Example 3: Creating EVM Wallets for 10 Users</summary>

```
const { CaishenSDK } = require('@caishen/sdk');
const jwt = require('jsonwebtoken');
require('dotenv').config();

// 🔁 Generate 10 user IDs
const users = Array.from({ length: 10 }, (_, i) => `user-${i + 1}`);

(async () => {
  for (const userId of users) {
    // Wrap the logic inside a try/catch for this user
    try {
      // 🔐 Create JWT
      const token = jwt.sign({ id: userId }, process.env.CAISHEN_PROJECT_SECRET);

      // 🆕 New SDK instance for each user
      const sdk = new CaishenSDK({ projectKey: process.env.CAISHEN_PROJECT_KEY });

      // 🚪 Connect user
      await sdk.connectAsUser({
        provider: 'custom',
        token,
      });

      // 👛 Create Ethereum wallet
      const wallet = await sdk.crypto.getWallet({
        chainType: 'ETHEREUM',
        chainId: 1,
        account: 0,
      });

      console.log(`✅ Wallet for ${userId}:`);
      console.log(`   Address: ${wallet.address}`);
      console.log(`   Public Key: ${wallet.publicKey}\n`);

    } catch (err) {
      console.error(`❌ Failed for ${userId}: ${err.message}\n`);
    }
  }
})();

```

</details>

<details>

<summary>Example 4: Creating EVM Wallets for 10 Users</summary>

```
const { CaishenSDK } = require('@caishen/sdk');
const jwt = require('jsonwebtoken');
require('dotenv').config();

// 🔁 Generate 10 user IDs
const users = Array.from({ length: 10 }, (_, i) => `user-${i + 1}`);

(async () => {
  for (const userId of users) {
    // Wrap the logic inside a try/catch for this user
    try {
      // 🔐 Create JWT
      const token = jwt.sign({ id: userId }, process.env.CAISHEN_PROJECT_SECRET);

      // 🆕 New SDK instance for each user
      const sdk = new CaishenSDK({ projectKey: process.env.CAISHEN_PROJECT_KEY });

      // 🚪 Connect user
      await sdk.connectAsUser({
        provider: 'custom',
        token,
      });

      // 👛 Create Ethereum wallet
      const wallet = await sdk.crypto.getWallet({
        chainType: 'ETHEREUM',
        chainId: 1,
        account: 0,
      });

      console.log(`✅ Wallet for ${userId}:`);
      console.log(`   Address: ${wallet.address}`);
      console.log(`   Public Key: ${wallet.publicKey}\n`);

    } catch (err) {
      console.error(`❌ Failed for ${userId}: ${err.message}\n`);
    }
  }
})();

```

</details>

<details>

<summary>Example 5: Creating Wallets on EVM, Bitcoin, Solana, SUI &#x26; XRP for 10 Users</summary>

```
const { CaishenSDK } = require('@caishen/sdk');
const jwt = require('jsonwebtoken');
require('dotenv').config();

// 🔁 10 users
const users = Array.from({ length: 10 }, (_, i) => `user-${i + 1}`);

// 🌐 Chain setup
const chains = [
  { name: 'Ethereum', chainType: 'ETHEREUM', chainId: 1 },
  { name: 'Solana', chainType: 'SOLANA', chainId: 101 },
  { name: 'Bitcoin', chainType: 'BITCOIN', chainId: 0 },
  { name: 'Sui', chainType: 'SUI', chainId: 1 },
  { name: 'XRP', chainType: 'XRP', chainId: 1 },
];

(async () => {
  for (const userId of users) {
    try {
      const token = jwt.sign({ id: userId }, process.env.CAISHEN_PROJECT_SECRET);
      const sdk = new CaishenSDK({ projectKey: process.env.CAISHEN_PROJECT_KEY });

      await sdk.connectAsUser({
        provider: 'custom',
        token,
      });

      console.log(`\n🧑 Creating wallets for ${userId}`);

      for (const chain of chains) {
        try {
          const wallet = await sdk.crypto.getWallet({
            chainType: chain.chainType,
            chainId: chain.chainId,
            account: 0,
          });

          console.log(`✅ ${chain.name} Wallet`);
          console.log(`   Address: ${wallet.address}`);
          console.log(`   Public Key: ${wallet.publicKey}\n`);
        } catch (err) {
          console.error(`❌ Failed to create ${chain.name} wallet for ${userId}: ${err.message}`);
        }
      }

    } catch (err) {
      console.error(`❌ Failed to connect ${userId}: ${err.message}`);
    }
  }
})();

```

</details>

#### Minimal WalletInput

```
interface MinimalWalletInput {
  account: number;
  chainType: string;
  address: string;
}
```

Used for all `cash` and `swap` functions to avoid sending sensitive data.

***

### 💸 Token Operations

> 🚫 Use `MinimalWalletInput` when possible to reduce sensitive data exposure.

#### ➕ Send Token

```
const txHash = await sdk.crypto.send({
  wallet,
  payload: {
    token: '0xTokenAddress...', // omit for native
    amount: '0.5',
    toAddress: '0xRecipient...',
  },
});
```

#### 📊 Get Balance

```
const native = await sdk.crypto.getBalance({ wallet, payload: {} });
const dai = await sdk.crypto.getBalance({
  wallet,
  payload: { token: '0x6B1754...' },
});
```

***

### 🔁 Token Swap

> 🚫 Do not send the full wallet object. Use only `{ account, chainType }`.

#### 🔍 Get Swap Route

```
const route = await sdk.crypto.getSwapRoute({
  wallet: { account: 0 },
  payload: {
    amount: '1000000000000000000',
    from: { tokenAddress: '0x...', chainType: 'ETHEREUM' },
    to: { tokenAddress: '0x...', chainType: 'ETHEREUM' },
  },
});
```

#### 🔄 Execute Swap

```
const result = await sdk.crypto.swap({
  wallet: { account: 0, chainType: 'ETHEREUM' },
  payload: { confirmationCode: 'abc123' },
});
```

<br>


# Using Agent Cash

Caishen SDK provides the only wallets which support gasless stablecoin swaps, powered by Agent Cash.&#x20;

### 🏦 Cash Accounts

> **Cash** is a chain-abstracted, gasless stablecoin system designed to make stablecoin transfers seamless, fast, and free.

#### 🔍 What is Cash?

**Cash** is an internal ERC-20-compatible asset that abstracts away the complexity of stablecoins across chains. It enables instant, gasless transfers between wallets without needing users to worry about:

* Native gas tokens (e.g., ETH, MATIC)
* Stablecoin formats (e.g., USDC vs USDT)
* Blockchain networks (e.g., Arbitrum, Base, Solana)

#### 🧪 How It Works

* **Deposit**: Users deposit supported stablecoins (e.g., USDC, USDT) from chains like Arbitrum, Base, or Solana.
* **Issue**: The system issues equivalent **Cash** tokens 1:1, held in an abstracted balance.
* **Send**: These Cash tokens can be sent to any wallet address instantly with zero gas cost.
* **Withdraw**: When users withdraw, their Cash tokens are burned and they receive the original stablecoin on the selected chain.

> ⚠️ Different combinations of `agentId` and `userId` result in separate Cash balances.

#### ✅ Benefits

* 💸 Gasless transfers (no ETH/SOL required)
* ⚡ Cross-chain abstraction
* 🔄 Simple send/receive interface
* 🔐 Fully backed, 1:1 redeemable

***

#### 💱 Supported Stablecoins

| Chain    | Token | Symbol | Address          |
| -------- | ----- | ------ | ---------------- |
| Arbitrum | USDC  | USDC   | `0xaf88...5831`  |
| Arbitrum | USDT  | USDT   | `0xFd08...cbb9`  |
| Base     | USDC  | USDC   | `0x8335...2913`  |
| Solana   | USDC  | USDC   | `EPjFWd...TDt1v` |

> See `CASH_SUPPORTED_TOKENS` for full details.

#### 💰 Get Account Balance

Get current balance of all tokens for a specific account.

**Parameters**

| Name    | Type   | Description            |
| ------- | ------ | ---------------------- |
| account | number | The account identifier |

**Returns**

```
Promise<BalanceResponse>
```

**📘 Example**

```
const balance = await sdk.cash.getBalance({ account: 1 });
```

#### 💵 Deposit

Deposit a supported token into the account.

**Parameters**

| Name   | Type                | Description           |
| ------ | ------------------- | --------------------- |
| params | `DepositCashParams` | Token and amount info |

**Returns**

```
Promise<TransactionResponse>
```

**📘 Example**

```
await sdk.cash.deposit({
  account: 1,
  tokenAddress: '0x...',
  amount: '1000000000000000000',
});
```

#### 💸 Withdraw

Withdraw a supported token from the account.

**Parameters**

| Name   | Type                 | Description           |
| ------ | -------------------- | --------------------- |
| params | `WithdrawCashParams` | Token and amount info |

**Returns**

```
Promise<TransactionResponse>
```

**📘 Example**

```
await sdk.cash.withdraw({
  account: 1,
  tokenAddress: '0x...',
  amount: '1000000000000000000',
});
```

#### 🔁 Send

Send supported tokens between accounts.

**Parameters**

| Name   | Type                    | Description          |
| ------ | ----------------------- | -------------------- |
| params | `SendTransactionParams` | Token, to/from, etc. |

**Returns**

```
Promise<TransactionResponse>
```

**📘 Example**

```
await sdk.cash.send({
  fromAccount: 1,
  toAccount: 2,
  tokenAddress: '0x...',
  amount: '1000000000000000000',
});
```

#### 🪙 Get Supported Tokens

```
const tokens = await sdk.cash.getSupportedTokens();
```

***

### 🛠 Types

```
type TokenWithPrice = Token & {
  priceUSD: string;
};
```


# Installation

## Caishen SDK – Plug & Play SDK Python

The Caishen SDK enables Python developers to easily connect to wallets, agents, and cash accounts across multiple chains including Ethereum, Solana, Bitcoin, Sui, and XRP. With just a few lines of code, you can automate balance checks, initiate transfers, and power AI-driven finance tools — all without managing seed phrases or wallet infrastructure.

Caishen's Python SDK is designed for backend services, bots, agents, and batch automation tasks. Whether you're building a DeFi app, running AI finance agents, or integrating payments into your backend, Caishen makes it simple and secure.

***

### Requirements

**For Python (Backend/Automation)**

* [Python 3.8 or newer](https://www.python.org/downloads/)
* `httpx`, `requests`, or a similar HTTP client
* Familiarity with environment variables and JWT authentication
* Access to your [Caishen project key and secret](https://dashboard.caishen.tech/auth)
  * `PROJECT_KEY`: from your Caishen dashboard
  * `PROJECT_SECRET`: used to generate JWTs
  * `USER_ID`: can be any string that uniquely identifies your user in your system

***

### Resources

* [**Example Applications**](/build-spotlight): View working wallet + cash agent integrations.
* [**Troubleshooting**](/support/faq): Common setup issues and sandbox tips.
* [**Source Code**](https://github.com/CaishenTech/caishen-sdk): Full SDK code and dev toolkits.
* [**Support Portal**:](https://discord.gg/tybyS3xSDz) Get help directly from the Caishen team or join the community.

***

### Features

* 🔗 Multi-chain wallet support
* 🌐 Supports major blockchains:
  * Ethereum
  * Bitcoin
  * Solana
  * Cardano
  * Sui, NEAR, Ripple, Tron, TON, Aptos
* 🔒 Secure wallet management
* 🐍 Typed Python API interfaces
* 💸 Token operations: Send, Balance, Swap, Deposit, Withdraw

***

### 🛠️ Install Caishen SDK (Latest Version)

```
pip install --upgrade caishen_sdk_python
> ⚠️ Requires Python ≥ 3.8
```

{% hint style="info" %}
We recommend using `--upgrade` to ensure you're always using the latest stable version with full hosted API support and bug fixes.
{% endhint %}

Having trouble with finding the package? Another option is to install it from Git. You'll need to [install Git](https://git-scm.com/downloads).&#x20;

```
pip install git+https://github.com/CaishenTech/caishen_sdk_python.git@dev
```

```
pip install pyjwt python-dotenv
```

***

### 🚀 Quick Start

```
from caishen_sdk_python import CaishenSDK

sdk = CaishenSDK("your-project-key")
```

***

### 🔑 Authentication

You can authenticate as either a **user** or an **agent**.

#### Connect as User

```
await sdk.connect_as_user(
  'USER PROVIDER',
  'USER TOKEN'
)
```

#### Connect as Agent

```
await sdk.connect_as_agent(
  'AGENT_ID',
  'USER_ID'
)

```

<details>

<summary>Example: Authenticate as a User</summary>

```
import jwt
import asyncio
from caishen_sdk_python import CaishenSDK

# 🔧 Replace with your actual credentials
PROJECT_KEY = "your-project-key"
PROJECT_SECRET = "your-project-secret"
USER_ID = "user-123"

# 🔐 Generate a JWT for the user
token = jwt.encode({ "id": USER_ID }, PROJECT_SECRET, algorithm="HS256")

# 🚀 Initialize the Caishen SDK
sdk = CaishenSDK(PROJECT_KEY)

# 👤 Connect as user with token
async def main():
    await sdk.connect_as_user("custom", token)
    print(f"✅ Connected as {USER_ID}")

asyncio.run(main())

```

</details>

Once connected, you can create wallets, check balances, send payments, and more.

***

### 🧱 Build from Source

```
# Clone & install
pip install setuptools wheel twine

# Build SDK
python setup.py sdist bdist_wheel

# Install locally for development
pip install .
```

<br>


# Creating Wallets

Creating Wallets

In order to get wallets, please ensure that you have [registered and installed the Caishen SDK](/registration).

With the Caishen SDK, you can create wallets for:

* EVM
* Bitcoin
* Solana
* SUI
* XRP

{% hint style="info" %}
All Caishen wallets come with support for crosschain swaps and sending&#x20;
{% endhint %}

#### 🔍 Get Wallet Info

Fetch a wallet associated with a user or agent for a specific chain.

> ⚠️ Note: The privateKey will only be returned if the developer dashboard has explicitly allowed access. With it, you can construct your own signer. If not enabled, the SDK will only return the public data needed to interact via Caishen.

**📥 Parameters**

| Name        | Type   | Required | Description                                  |
| ----------- | ------ | -------- | -------------------------------------------- |
| `chainType` | string | ✅        | Blockchain type (`ETHEREUM`, `SOLANA`, etc.) |
| `chainId`   | number | ❌        | Optional chain ID (e.g., 1 for Ethereum)     |
| `account`   | number | ✅        | Account index or identifier                  |

**📘 Example**

```
wallet = await sdk.crypto.get_wallet({
    "chainType": "ETHEREUM",
    "chainId": 1,
    "account": 0
})
```

**📚 Type: `IWalletAccount`**

```
class IWalletAccount:
  address: str
  chainType: str
  publicKey: str
  privateKey: Optional(str)  # Only returned if access is enabled in the dashboard
  account: int
```

> ⚠️ Private key is optional and only available if explicitly enabled in the dashboard.

#### MinimalWalletInput

```
class MinimalWalletInput:
  account: int
  chainType: str
  address: str
```

Used for all `cash` and `swap` functions to avoid sending sensitive data.

#### 🌐 Supported Chains

Returns the list of all chain types supported by the backend for wallet creation.

**📦 Returns**

```
List[str] // e.g., ['evm', 'solana']
```

**📘 Example**

```
chains = await sdk.crypto.get_supported_chain_types()
```

#### 🔗 Get EVM RPC URL

Returns the public RPC endpoint URL for a given EVM-compatible chain ID.

#### 📥 Parameters

| Name      | Type     | Required | Description         |
| --------- | -------- | -------- | ------------------- |
| `chainId` | ChainIds | ✅        | Chain ID enum value |

#### 📦 Returns

```
rpc_url = await sdk.crypto.get_rpc(1)
```

***

### 💸 Token Operations

#### ➕ Send Token

Send a token or native coin (like ETH, MATIC, SOL) to another address.

**📥 Parameters**

| Name      | Type                                                                   | Required | Description                               |
| --------- | ---------------------------------------------------------------------- | -------- | ----------------------------------------- |
| `wallet`  | `IWalletAccount`                                                       | ✅        | Wallet object returned from `getWallet()` |
| `payload` | `{ token?: string; amount: string; toAddress: string; memo?: number }` | ✅        | Transfer details                          |

> 🚫 Do not pass the full `IWalletAccount` into this function — only `MinimalWalletInput` is required and safer.

* If `payload.token` is **undefined**, the function sends the **native gas token** (e.g. ETH, MATIC).
* If `payload.token` is provided, it sends that **ERC20 or token** instead.

**📦 Returns**

```
'transaction_hash'
```

**📘 Example**

```
tx_hash = await sdk.crypto.send({
    "wallet": wallet,
    "payload": {
        "token": "0xTokenAddress",  # Optional
        "amount": "0.5",
        "toAddress": "0xRecipientAddress"
    }
})
```

#### 📊 Get Balance

Fetch the balance of a wallet for either the **native coin** or a specific **token**.

**📥 Parameters**

| Name      | Type                 | Required | Description                                                               |
| --------- | -------------------- | -------- | ------------------------------------------------------------------------- |
| `wallet`  | `IWalletAccount`     | ✅        | Wallet object                                                             |
| `payload` | `{ token?: string }` | ❌        | If `token` is provided, fetch its balance; otherwise fetch native balance |

> 🚫 Do not pass the full `IWalletAccount` into this function — only `MinimalWalletInput` is required and safer.

**📦 Returns**

```
'Balance (in decimal format)'
```

**Native Balance**

```
native = await sdk.crypto.get_balance({"wallet": wallet, "payload": {}})
```

**Token Balance**

```
token = await sdk.crypto.get_balance({
    "wallet": wallet,
    "payload": {"token": "0xTokenAddress"}
})
```

***

### 🔁 Token Swap

#### 🔍 Get Swap Route

Fetch a possible token swap route across chains.

**📥 Parameters**

| Field     | Type                              | Description                                   |
| --------- | --------------------------------- | --------------------------------------------- |
| `wallet`  | `Pick<IWalletAccount, 'account'>` | Wallet account info                           |
| `payload` | `object`                          | Swap details including amount, from/to tokens |

> 🚫 Do not pass the full `IWalletAccount` into this function — only `MinimalWalletInput` is required and safer.

**`payload` structure:**

```
{
  amount: str; // in smallest unit (e.g. wei)
  from: {
    tokenAddress: str;
    chainType: ChainType;
    chainId: Optional(int);
  };
  to: {
    tokenAddress: str;
    chainType: ChainType;
    chainId: Optional(int);
  };
}
```

**📦 Returns**

```
class RouteOutput(TypeDict):
  id: str
  fromChainId: int
  fromAmountUSD: str
  fromAmount: str
  fromToken: TokenWithPrice
  fromAddress: Optional(str)
  toChainId: int
  toAmountUSD: str
  toAmount: str
  toAmountMin: str
  toToken: TokenWithPrice
  toAddress: Optional(str)
  confirmationCode: str
```

**📘 Example**

```
route = await sdk.crypto.get_swap_route({
    "wallet": {"account": 0},
    "payload": {
        "amount": "1000000000000000000",
        "from": {
            "tokenAddress": "0x...",
            "chainType": "ETHEREUM"
        },
        "to": {
            "tokenAddress": "0x...",
            "chainType": "ETHEREUM"
        }
    }
})
```

#### 🔄 Execute Swap

Execute the swap route using a confirmation code.

**📥 Parameters**

| Field     | Type                                           | Description                               |
| --------- | ---------------------------------------------- | ----------------------------------------- |
| `wallet`  | `Pick<IWalletAccount, 'account', 'chainType'>` | Wallet info                               |
| `payload` | `object`                                       | Swap payload including `confirmationCode` |

> 🚫 Do not pass the full `IWalletAccount` into this function — only `MinimalWalletInput` is required and safer.

**`payload` structure:**

```
{
  confirmationCode: str; # from getSwapRoute()
}
```

**📦 Returns**

```
class RouteExecutedResponse(TypeDict):
  transactionStatus: str
  transactionHash: Optional(str)
  fees: Optional(str)
  error: Optional(str)
```

**📘 Example**

```
result = await sdk.crypto.swap({
    "wallet": {"account": 0, "chainType": "ETHEREUM"},
    "payload": {"confirmationCode": "abc123"}
})
```

***


# Using Agent Cash

Caishen SDK provides the only wallets which support gasless stablecoin swaps, powered by Agent Cash.&#x20;

> **Cash** is a chain-abstracted, gasless stablecoin system designed to make stablecoin transfers seamless, fast, and free.

#### 🔍 What is Cash?

**Cash** is an internal ERC-20-compatible asset that abstracts away the complexity of stablecoins across chains. It enables instant, gasless transfers between wallets without needing users to worry about:

* Native gas tokens (e.g., ETH, MATIC)
* Stablecoin formats (e.g., USDC vs USDT)
* Blockchain networks (e.g., Arbitrum, Base, Solana)

#### 🧪 How It Works

* **Deposit**: Users deposit supported stablecoins (e.g., USDC, USDT) from chains like Arbitrum, Base, or Solana.
* **Issue**: The system issues equivalent **Cash** tokens 1:1, held in an abstracted balance.
* **Send**: These Cash tokens can be sent to any wallet address instantly with zero gas cost.
* **Withdraw**: When users withdraw, their Cash tokens are burned and they receive the original stablecoin on the selected chain.

> ⚠️ Different combinations of `agentId` and `userId` result in separate Cash balances.

#### ✅ Benefits

* 💸 Gasless transfers (no ETH/SOL required)
* ⚡ Cross-chain abstraction
* 🔄 Simple send/receive interface
* 🔐 Fully backed, 1:1 redeemable

### 🏦 Cash Accounts

#### 💰 Get Account Balance

Get current balance of all tokens for a specific account.

**Parameters**

| Name    | Type   | Description            |
| ------- | ------ | ---------------------- |
| account | number | The account identifier |

**Returns**

```
'BalanceResponse'
```

**📘 Example**

```
balance = await sdk.cash.get_balance({"account": 1})
```

#### 💵 Deposit

Deposit a supported token into the account.

**Parameters**

| Name   | Type                | Description           |
| ------ | ------------------- | --------------------- |
| params | `DepositCashParams` | Token and amount info |

**Returns**

```
TransactionResponse
```

**📘 Example**

```
await sdk.cash.deposit({
    "account": 1,
    "tokenAddress": "0x...",
    "amount": "1000000000000000000"
})
```

#### 💸 Withdraw

Withdraw a supported token from the account.

**Parameters**

| Name   | Type                 | Description           |
| ------ | -------------------- | --------------------- |
| params | `WithdrawCashParams` | Token and amount info |

**Returns**

```
TransactionResponse
```

**📘 Example**

```
await sdk.cash.withdraw({
    "account": 1,
    "tokenAddress": "0x...",
    "amount": "1000000000000000000"
})
```

#### 🔁 Send

Send supported tokens between accounts.

**Parameters**

| Name   | Type                    | Description          |
| ------ | ----------------------- | -------------------- |
| params | `SendTransactionParams` | Token, to/from, etc. |

**Returns**

```
TransactionResponse
```

**📘 Example**

```
await sdk.cash.send({
    "fromAccount": 1,
    "toAccount": 2,
    "tokenAddress": "0x...",
    "amount": "1000000000000000000"
})
```

#### 🪙 Get Supported Tokens

```
tokens = await sdk.cash.get_supported_tokens()
```

***

### 🛠 Types

#### `TokenWithPrice`

```
type TokenWithPrice = Token & {
  priceUSD: str;
}
```


# Security

## 🔐 Wallet Creation & Security

Caishen's wallet infrastructure is built from the ground up with **user sovereignty and security** at its core. While inspired by modern cryptographic techniques, we intentionally avoid disclosing implementation specifics to reduce attack surface awareness.

***

### 🚫 No Centralized Private Key Storage

Caishen **never stores complete private keys—anywhere**.

Our architecture ensures that no single system, service, or entity can ever reconstruct a user's full private key independently.

***

### 🧩 Key Sharding and Secure Assembly

Wallet keys are generated using a **secure, distributed process** and then cryptographically split into multiple independent **key shares**.

These shares are distributed across multiple trusted factors, which may include:

* User-controlled elements
* Device-resident data
* Confidential authentication vectors

***

### 🔐 Threshold-Based Access

To use a wallet for a transaction:

* A **minimum threshold of shares** is required
* Shares are **securely reassembled just-in-time**
* The key only exists **ephemerally**, during the operation
* Nothing is stored or cached after use

***

### 👤 Self-Custodial by Design

Caishen is designed so that:

* **Only the user or agent** can trigger key reassembly
* Even with backend access, **no one (including Caishen)** can unilaterally recreate or use a private key
* All wallet actions are initiated and approved **by the user or agent** exclusively


# Infrastructure

## 🏗️ Infrastructure

Caishen's platform is composed of several core components working in unison to deliver a **scalable**, **secure**, and **developer-friendly** wallet experience.

***

### 🧠 Wallet Server & Microservices

The **wallet server** is the core of secure key orchestration, responsible for:

* Secure key generation and recovery
* Session-based wallet operation routing
* Transaction signing orchestration

Surrounding microservices support:

* Identity management
* Auditing and logging
* Transaction broadcasting
* Metrics and analytics

***

### 🧰 Caishen SDK

The **Caishen SDK** provides a streamlined interface for developers to integrate multi-chain functionality with minimal overhead.

With the SDK, you can:

* Create wallets for users or agents
* Sign and send transactions
* Retrieve on-chain and cash balances
* Perform swaps and cross-chain operations

It abstracts complex backend processes while preserving robust cryptographic guarantees.

***

### 🧬 MCP & Data Registry *(Coming Soon)*

Our upcoming **MCP (Multi-Chain Protocol) integration** will enable:

* Access to decentralized data feeds
* Agent-level decision-making with verified off-chain inputs
* On-chain proof validation and verifiable registries
* Secure off-chain enrichment with cryptographic guarantees

***

### 🧱 Unified Agent Foundation

Together, these layers make Caishen a **powerful foundation for applications and agents** requiring:

* Secure wallet access
* Dynamic agent logic
* Fully programmable and composable crypto automation


# Brand Kit

For those looking to co-market with Caishen, below you can find our most suitable brand assets

{% file src="/files/4E0aQfQQTt6Cf03BqFzR" %}

{% file src="/files/G5h6MlpN6wPABmnr3Ur3" %}

{% file src="/files/37GVTuyyUheR3wMIT0Ga" %}


# Support

Contact us on Discord, Telegram, or Github for support.

[Discord](https://discord.gg/tybyS3xSDz)

Telegram (coming soon)

[Github](https://github.com/CaishenTech/caishen-sdk/)


# FAQ


# Contracts


# Build Spotlight


