@paxoslabs/earn-sdk
Version:
Paxos Labs Earn SDK
503 lines (405 loc) • 14 kB
Markdown
```
_ __ __ ___ _ _ __ ____
/ |/ /_ ______/ /__ __ _____ / _ )___ ____(_)__ ___ | | / /__ ___ __/ / /_
/ / // / __/ / -_) // (_-< / _ / _ \/ __/ / _ \/ _ `/ |/ / _ `/ // / / __/
/_/|_/\_,_/\__/_/\__/\_,_/___/ /____/\___/_/ /_/_//_/\_, /|___/\_,_/\_,_/_/\__/
____ __ __ _______ __/___/
/ __/______ ___ / /____ ___ ___/ / / __/ _ \/ //_/
/ _// __/ _ \/ _ \/ __/ -_) _ \/ _ / _\ \/ // / ,<
/_/ /_/ \___/_//_/\__/\__/_//_/\_,_/ /___/____/_/|_|
```
# Paxos Labs Earn SDK
A TypeScript SDK for interacting with Paxos Labs Earn Vaults, providing type-safe functions for discovering vaults, depositing assets, and withdrawing across multiple blockchain networks.
[](https://www.npmjs.com/package/@paxoslabs/earn-sdk)
[](https://opensource.org/licenses/MIT)
## Table of Contents
- [Features](#features)
- [Quick Start (5 Minutes)](#quick-start-5-minutes)
- [Documentation](#documentation)
- [Complete Guides](#-complete-guides)
- [Example Projects](#-example-projects)
- [Core API Overview](#core-api-overview)
- [Vault Discovery](#vault-discovery)
- [Cache Management](#cache-management)
- [Deposits](#deposits)
- [Permit Deposits (Gas-Optimized)](#permit-deposits-gas-optimized)
- [Withdrawals](#withdrawals)
- [TypeScript Support](#typescript-support)
- [Error Handling](#error-handling)
- [Supported Networks](#supported-networks)
- [Requirements](#requirements)
- [API Configuration](#api-configuration)
- [Available Vault Keys](#available-vault-keys)
- [Contributing](#contributing)
- [License](#license)
## Features
- **Vault Discovery** - Query available vaults and supported assets via API
- **Deposits** - Deposit assets into vaults with slippage protection
- **Withdrawals** - Withdraw assets from vaults with deadline protection
- **Permit Deposits** - Gas-optimized deposits using EIP-2612 permit signatures
- **Cache Management** - Optimize API calls with built-in caching
- **Multi-Chain Support** - Seamless operations across 7+ blockchain networks
- **Full TypeScript Support** - Complete type definitions and autocomplete
- **React Ready** - Works with viem (vanilla) and wagmi (React hooks)
## Quick Start (5 Minutes)
### 1. Installation
```bash
# npm
npm install @paxoslabs/earn-sdk viem
# yarn
yarn add @paxoslabs/earn-sdk viem
# pnpm
pnpm add @paxoslabs/earn-sdk viem
# For React apps, also install wagmi
pnpm add wagmi @tanstack/react-query
```
### 2. Discover Available Vaults
```typescript
import { fetchVaults } from "@paxoslabs/earn-sdk";
// Fetch all available vaults
const allVaults = await fetchVaults();
// Or filter by chain and yield type
const primeVaults = await fetchVaults({
chainId: 1, // Ethereum mainnet
yieldType: "PRIME",
});
console.log(`Found ${primeVaults.length} PRIME vaults on Ethereum`);
```
### 3. Find Supported Deposit Assets
```typescript
import { fetchSupportedAssets } from "@paxoslabs/earn-sdk";
// Fetch assets supported for deposits
const assets = await fetchSupportedAssets({
chainId: 1, // Ethereum mainnet
});
// Find USDC
const usdc = assets.find((asset) => asset.symbol === "USDC");
console.log(`USDC address: ${usdc?.address}`);
```
### 4. Deposit into a Vault (Viem)
```typescript
import { createWalletClient, http } from "viem";
import { mainnet } from "viem/chains";
import { privateKeyToAccount } from "viem/accounts";
import {
prepareApproveDepositToken,
prepareDepositTransactionData,
isDepositSpendApproved,
} from "@paxoslabs/earn-sdk";
// Setup viem client
const account = privateKeyToAccount("0x...");
const client = createWalletClient({
account,
chain: mainnet,
transport: http(),
});
async function deposit() {
const vaultKey = "op-nTBILL"; // T-Bill vault
const tokenSymbol = "USDC";
const amount = "1000.0"; // $1000 USDC
const chainId = 1;
// 1. Check if approval needed
const isApproved = await isDepositSpendApproved({
vaultKey,
userAddress: account.address,
depositTokenSymbol: tokenSymbol,
depositAmount: amount,
chainId,
});
// 2. Approve if needed
if (!isApproved) {
const approvalTx = await prepareApproveDepositToken({
vaultKey,
depositTokenSymbol: tokenSymbol,
depositAmount: amount,
chainId,
});
const approvalHash = await client.writeContract(approvalTx);
console.log(`Approval tx: ${approvalHash}`);
// Wait for approval confirmation...
}
// 3. Prepare and execute deposit
const depositTx = await prepareDepositTransactionData({
vaultKey,
userAddress: account.address,
depositTokenSymbol: tokenSymbol,
depositAmount: amount,
chainId,
slippage: 100, // 1% slippage (100 basis points)
});
const depositHash = await client.writeContract(depositTx);
console.log(`Deposit tx: ${depositHash}`);
}
deposit();
```
### 5. Deposit into a Vault (Wagmi + React)
```tsx
import { useAccount, useWriteContract } from "wagmi";
import {
prepareApproveDepositToken,
prepareDepositTransactionData,
isDepositSpendApproved,
} from "@paxoslabs/earn-sdk";
function DepositComponent() {
const { address } = useAccount();
const { writeContract } = useWriteContract();
const handleDeposit = async () => {
if (!address) return;
const vaultKey = "op-nTBILL";
const tokenSymbol = "USDC";
const amount = "1000.0";
const chainId = 1;
try {
// Check approval
const isApproved = await isDepositSpendApproved({
vaultKey,
userAddress: address,
depositTokenSymbol: tokenSymbol,
depositAmount: amount,
chainId,
});
// Approve if needed
if (!isApproved) {
const approvalTx = await prepareApproveDepositToken({
vaultKey,
depositTokenSymbol: tokenSymbol,
depositAmount: amount,
chainId,
});
await writeContract(approvalTx);
}
// Execute deposit
const depositTx = await prepareDepositTransactionData({
vaultKey,
userAddress: address,
depositTokenSymbol: tokenSymbol,
depositAmount: amount,
chainId,
slippage: 100, // 1%
});
await writeContract(depositTx);
} catch (error) {
console.error("Deposit failed:", error);
}
};
return <button onClick={handleDeposit}>Deposit $1000 USDC</button>;
}
```
**That's it!** You've discovered vaults and executed your first deposit. ✨
## Documentation
### 📚 Complete Guides
- **[Getting Started Guide](./docs/getting-started.md)** - Detailed setup and first API call
- **[API Reference: Vault Discovery](./docs/api-reference/vault-discovery.md)** - Fetch vaults and assets
- **[API Reference: Deposits](./docs/api-reference/deposits.md)** - Standard deposit flows
- **[API Reference: Permit Deposits](./docs/api-reference/deposits-permit.md)** - Gas-optimized deposits
- **[API Reference: Withdrawals](./docs/api-reference/withdrawals.md)** - Withdrawal flows
- **[API Reference: Caching](./docs/api-reference/caching.md)** - Performance optimization
- **[API Reference: Types](./docs/api-reference/types.md)** - TypeScript type definitions
- **[Guide: Error Handling](./docs/guides/error-handling.md)** - Error patterns and recovery
- **[Guide: React Integration](./docs/guides/react-integration.md)** - React patterns and hooks
- **[Guide: Multi-Chain Operations](./docs/guides/multi-chain.md)** - Cross-chain deposits/withdrawals
### 💻 Example Projects
- **[Viem Deposit Example](./docs/examples/viem-deposit/)** - Executable viem deposit example
- **[Wagmi Deposit Example](./docs/examples/wagmi-deposit/)** - React wagmi deposit component
- **[Wagmi Withdrawal Example](./docs/examples/wagmi-withdraw/)** - React wagmi withdrawal component
## Core API Overview
### Vault Discovery
```typescript
import {
fetchVaults,
fetchSupportedAssets,
getWithdrawSupportedAssets,
} from "@paxoslabs/earn-sdk";
// Discover vaults
const vaults = await fetchVaults({
chainId: 1,
yieldType: "PRIME", // or "TBILL", "LENDING"
});
// Discover deposit assets
const depositAssets = await fetchSupportedAssets({
chainId: 1,
symbol: "USDC",
});
// Discover withdrawal assets
const withdrawAssets = await getWithdrawSupportedAssets();
```
### Cache Management
```typescript
import {
initializeCache,
getVaultsFromCache,
getAssetsFromCache,
refreshVaultCache,
} from "@paxoslabs/earn-sdk";
// Initialize cache (recommended at app startup)
await initializeCache();
// Use cached data (80% faster than API calls)
const cachedVaults = await getVaultsFromCache({ chainId: 1 });
const cachedAssets = await getAssetsFromCache({ symbol: "USDC" });
// Refresh cache periodically
await refreshVaultCache();
```
### Deposits
```typescript
import {
prepareDepositTransactionData,
prepareApproveDepositToken,
isDepositSpendApproved,
} from "@paxoslabs/earn-sdk";
// Check approval status
const isApproved = await isDepositSpendApproved({
vaultKey: "op-nTBILL",
userAddress: "0x...",
depositTokenSymbol: "USDC",
depositAmount: "1000.0",
chainId: 1,
});
// Prepare approval transaction
const approvalTx = await prepareApproveDepositToken({
vaultKey: "op-nTBILL",
depositTokenSymbol: "USDC",
depositAmount: "1000.0",
chainId: 1,
});
// Prepare deposit transaction
const depositTx = await prepareDepositTransactionData({
vaultKey: "op-nTBILL",
userAddress: "0x...",
depositTokenSymbol: "USDC",
depositAmount: "1000.0",
chainId: 1,
slippage: 100, // 1% (100 basis points)
});
```
### Permit Deposits (Gas-Optimized)
```typescript
import {
prepareDepositWithPermitTransactionData,
type PrepareDepositWithPermitTransactionDataParams,
} from "@paxoslabs/earn-sdk";
// Sign permit message off-chain (using viem or wagmi)
const signature = await signTypedData({
/* permit EIP-2612 typed data */
});
// Execute deposit with permit in single transaction
const permitDepositTx = await prepareDepositWithPermitTransactionData({
vaultKey: "op-nTBILL",
userAddress: "0x...",
depositTokenSymbol: "USDC",
depositAmount: "1000.0",
chainId: 1,
permitSignature: signature,
deadline: Math.floor(Date.now() / 1000) + 3600, // 1 hour
});
```
### Withdrawals
```typescript
import {
prepareWithdrawTransactionData,
prepareApproveWithdrawToken,
isWithdrawalSpendApproved,
} from "@paxoslabs/earn-sdk";
// Check if vault shares are approved
const isApproved = await isWithdrawalSpendApproved({
vaultKey: "op-nTBILL",
userAddress: "0x...",
withdrawAmount: "100.0", // vault shares
chainId: 1,
});
// Approve vault shares
const approvalTx = await prepareApproveWithdrawToken({
vaultKey: "op-nTBILL",
withdrawAmount: "100.0",
chainId: 1,
});
// Withdraw assets
const withdrawTx = await prepareWithdrawTransactionData({
vaultKey: "op-nTBILL",
chainId: 1,
userAddress: "0x...",
wantTokenSymbol: "USDC",
offerAmount: "100.0", // vault shares to redeem
deadline: Math.floor(Date.now() / 1000) + 3600, // 1 hour
slippage: 100, // 1%
});
```
## TypeScript Support
Full type definitions with autocomplete:
```typescript
import type {
EarnVault,
SupportedAsset,
VaultFilterOptions,
VaultKey,
ChainId,
DepositTransactionData,
WithdrawTransactionData,
PrepareDepositTransactionDataParams,
} from "@paxoslabs/earn-sdk";
// All functions have full TypeScript support
const depositData: DepositTransactionData =
await prepareDepositTransactionData({
// TypeScript provides autocomplete and validation
});
```
## Error Handling
```typescript
import { APIError } from "@paxoslabs/earn-sdk";
try {
const vaults = await fetchVaults({ chainId: 1 });
} catch (error) {
if (error instanceof APIError) {
console.error(`API Error: ${error.message}`);
console.error(`Endpoint: ${error.context?.endpoint}`);
console.error(`Status: ${error.context?.status}`);
} else {
console.error("Unexpected error:", error);
}
}
```
## Supported Networks
| Network | Chain ID | Status |
| ------------------ | ---------- | ------ |
| Ethereum Mainnet | 1 | ✅ |
| HyperEVM | 999 | ✅ |
| Boba Network | 288 | ✅ |
| Sei Network | 713715 | ✅ |
| Plume Mainnet | 98866 | ✅ |
| Form Network | 478 | ✅ |
| Swell Mainnet | 1923 | ✅ |
| Rari Chain | 1380012617 | ✅ |
## Requirements
- **Node.js** >= 20
- **TypeScript** >= 4.9.0 (optional but recommended)
- **viem** >= 2.0.0 (required)
- **wagmi** >= 2.0.0 (for React applications)
- **@tanstack/react-query** >= 5.0.0 (for React applications)
## API Configuration
The SDK connects to the Earn API at `http://localhost:8500` by default. This is suitable for development environments. For production deployments, you'll need to configure the API endpoint according to your backend setup.
**Note**: All API calls have a 10-second timeout. Network requests that exceed this timeout will throw an `APIError`.
## Available Vault Keys
```typescript
import { VaultKeys } from "@paxoslabs/earn-sdk";
console.log(VaultKeys);
// {
// OPNALPHA: "op-nALPHA",
// OPNBASIS: "op-nBASIS",
// OPNETF: "op-nETF",
// OPNPAYFI: "op-nPAYFI",
// OPNPLUME: "op-PLUME",
// OPNRWA: "op-nRWA",
// OPNTBILL: "op-nTBILL",
// OPPUSD: "op-pUSD",
// XLHYPE: "XLHYPE",
// CAMPUSD: "campUSD"
// }
```
## Contributing
Contributions are welcome! Please read our [Contributing Guide](./CONTRIBUTING.md) for details on our code of conduct and the process for submitting pull requests.
## License
MIT © Paxos Labs
---
**Need Help?**
- 📖 [Full Documentation](./docs/getting-started.md)
- 🐛 [Report Issues](https://github.com/Ion-Protocol/earn-sdk/issues)
- 💬 [GitHub Discussions](https://github.com/Ion-Protocol/earn-sdk/discussions)