@defindex/sdk

中文文档
0.3.0发布于 2026/04/09MITTypeScriptCommonJS近 30 天下载 3709

Official TypeScript SDK for DeFindex API

原始使用文档
文档目录26 节
  1. 🌟 Features
  2. 🚀 Installation
  3. 📖 Quick Start
  4. 🚀 Running the Example
  5. 🔧 Configuration
  6. SDK Configuration Options
  7. Environment Variables
  8. ✅ Current Status
  9. Recent Updates
  10. 📚 API Reference
  11. System Operations
  12. Factory Operations
  13. Vault Operations
  14. Vault Management (Admin Operations)
  15. Transaction Management
  16. System Operations
  17. 🔐 Security Best Practices
  18. 🔒 Vault Management Roles
  19. 🏗️ Development
  20. Building
  21. Testing
  22. Code Quality
  23. 📊 Type Definitions
  24. 🌐 Frontend Integration
  25. 📖 Documentation
  26. 🔗 Links

DeFindex SDK

Ask DeepWiki npm version License: MIT

Official TypeScript SDK for DeFindex - A decentralized vault management system built on Stellar using Soroban smart contracts.

🌟 Features

  • 🔐 API Key Authentication: Secure API key authentication with Bearer tokens (recommended)
  • 🏦 Vault Operations: Create, deposit, withdraw, and manage decentralized vaults
  • 🏭 Factory Operations: Deploy new vaults with custom configurations
  • 👑 Admin Operations: Emergency rescue, strategy management for vault operators
  • 📊 Real-time Data: Vault balances, APY tracking, and comprehensive vault information
  • 🔒 Server-Side Focused: Secure handling of credentials and sensitive operations
  • 📝 TypeScript Support: Full type safety with comprehensive interfaces
  • ⚡ Lightweight: Simple authentication and comprehensive error handling
  • 🧪 Well Tested: Comprehensive unit and integration test coverage
  • 📚 Complete Examples: Functional TypeScript examples and comprehensive documentation

🚀 Installation

pnpm install @defindex/sdk

📖 Quick Start

import { DefindexSDK, SupportedNetworks } from '@defindex/sdk';

// Initialize with API key
const sdk = new DefindexSDK({
  apiKey: 'sk_your_api_key_here',
  baseUrl: 'https://api.defindex.io'
});

// Check API health
const health = await sdk.healthCheck();
console.log('API Status:', health.status.reachable);

// Get factory address
const factory = await sdk.getFactoryAddress(SupportedNetworks.TESTNET);
console.log('Factory Address:', factory.address);

// Get vault information
const vaultAddress = 'CVAULT_CONTRACT_ADDRESS...';
const vaultInfo = await sdk.getVaultInfo(vaultAddress, SupportedNetworks.TESTNET);
console.log(`Vault: ${vaultInfo.name} (${vaultInfo.symbol})`);

// Deposit to vault
const depositResponse = await sdk.depositToVault(vaultAddress, {
  amounts: [1000000], // Amount for each asset (considering decimals)
  caller: 'GUSER_ADDRESS...',
  invest: true,
  slippageBps: 100 // 1% slippage tolerance
}, SupportedNetworks.TESTNET);

// Sign the XDR with your wallet and submit
const signedXdr = await yourWallet.sign(depositResponse.xdr);
const result = await sdk.sendTransaction(signedXdr, SupportedNetworks.TESTNET);

🚀 Running the Example

The SDK includes a comprehensive functional example:

# Install dependencies
pnpm install

# Copy environment configuration
cp .env.example .env

# Edit .env with your credentials
# DEFINDEX_API_KEY=sk_your_api_key_here

# Run the example
pnpm run example

The example demonstrates:

  • SDK initialization and authentication
  • API health checking
  • Factory operations
  • Vault creation, deposits, and withdrawals
  • Administrative vault management
  • Error handling and best practices

🔧 Configuration

SDK Configuration Options

interface DefindexSDKConfig {
  apiKey?: string;         // API key for authentication (recommended)
  baseUrl?: string;        // Custom API base URL (defaults to 'https://api.defindex.io')
  timeout?: number;        // Request timeout in ms (defaults to 30000)
}

Environment Variables

For better security, use environment variables:

// Using API key (recommended)
const sdk = new DefindexSDK({
  apiKey: process.env.DEFINDEX_API_KEY,
  baseUrl: process.env.DEFINDEX_API_URL || 'https://api.defindex.io'
});

✅ Current Status

Great News! The DeFindex API is now fully operational on testnet:

  • ✅ Health Check: Working correctly
  • ✅ SDK Authentication: API key authentication implemented
  • ✅ Factory Operations: Factory deployed and working on testnet
  • ✅ Vault Creation: Create vaults with custom configurations
  • ✅ Vault Operations: Full deposit, withdrawal, and balance operations
  • ✅ Vault Management: Administrative operations (pause/unpause strategies, emergency rescue)
  • ✅ Transaction Building: All operations return signed XDR for wallet integration
  • ⚠️ APY Calculation: Working but some fields may be undefined for new vaults

Recent Updates

  1. ✅ Factory Deployed: Factory contract now available on testnet
  2. ✅ Full Vault Operations: Create, manage, and interact with vaults
  3. ✅ Complete Example: Run pnpm run example to see all functionality
  4. ✅ Ready for Production: All core functionality is operational

📚 API Reference

System Operations

Health Check

const health = await sdk.healthCheck();
if (health.status.reachable) {
  console.log('API is healthy');
}

Factory Operations

Get Factory Address

const factory = await sdk.getFactoryAddress(SupportedNetworks.TESTNET);
console.log('Factory address:', factory.address);

Create Vault

const vaultConfig: CreateVaultParams = {
  roles: {
    emergencyManager: "GEMERGENCY_MANAGER_ADDRESS...",
    feeReceiver: "GFEE_RECEIVER_ADDRESS...",
    manager: "GVAULT_MANAGER_ADDRESS...",
    rebalanceManager: "GREBALANCE_MANAGER_ADDRESS..."
  },
  vaultFeeBps: 100, // 1% fee
  assets: [{
    address: "CXLM_CONTRACT_ADDRESS...",
    strategies: [{
      address: "GSTRATEGY_CONTRACT_ADDRESS...",
      name: "XLM Strategy",
      paused: false
    }]
  }],
  name: "My DeFi Vault",
  symbol: "MDV",
  upgradable: true,
  caller: "GCREATOR_ADDRESS..."
};

const response = await sdk.createVault(vaultConfig, SupportedNetworks.TESTNET);
console.log('Vault XDR:', response.xdr);

Vault Operations

Get Vault Information

const vaultInfo = await sdk.getVaultInfo(vaultAddress, SupportedNetworks.TESTNET);
console.log(`Total Assets: ${vaultInfo.totalAssets}`);
console.log(`Vault Fee: ${vaultInfo.feesBps.vaultFee / 100}%`);

Get Vault Balance

const balance = await sdk.getVaultBalance(
  vaultAddress, 
  userAddress, 
  SupportedNetworks.TESTNET
);
console.log(`Vault Shares: ${balance.dfTokens}`);

Deposit to Vault

const depositResponse = await sdk.depositToVault(vaultAddress, {
  amounts: [1000000, 2000000],
  caller: 'GUSER_ADDRESS...',
  invest: true,
  slippageBps: 100
}, SupportedNetworks.TESTNET);

Withdraw from Vault

// Withdraw specific amounts
const withdrawResponse = await sdk.withdrawFromVault(vaultAddress, {
  amounts: [500000, 1000000],
  caller: 'GUSER_ADDRESS...',
  slippageBps: 100
}, SupportedNetworks.TESTNET);

// Withdraw by shares
const shareResponse = await sdk.withdrawShares(vaultAddress, {
  shares: 1000000,
  caller: 'GUSER_ADDRESS...',
  slippageBps: 100
}, SupportedNetworks.TESTNET);

Get Vault APY

const apy = await sdk.getVaultAPY(vaultAddress, SupportedNetworks.TESTNET);
console.log(`Current APY: ${apy.apyPercent}%`);

Vault Management (Admin Operations)

Emergency Rescue

// Requires Emergency Manager role
const response = await sdk.emergencyRescue(vaultAddress, {
  strategy_address: 'GSTRATEGY_TO_RESCUE...',
  caller: 'GEMERGENCY_MANAGER_ADDRESS...'
}, SupportedNetworks.TESTNET);

Pause/Unpause Strategy

// Requires Strategy Manager role
await sdk.pauseStrategy(vaultAddress, {
  strategy_address: 'GSTRATEGY_TO_PAUSE...',
  caller: 'GSTRATEGY_MANAGER_ADDRESS...'
}, SupportedNetworks.TESTNET);

await sdk.unpauseStrategy(vaultAddress, {
  strategy_address: 'GSTRATEGY_TO_UNPAUSE...',
  caller: 'GSTRATEGY_MANAGER_ADDRESS...'
}, SupportedNetworks.TESTNET);

Transaction Management

Send Transaction

// Submit signed transaction to the Stellar network
const response = await sdk.sendTransaction(
  signedXDR,
  SupportedNetworks.TESTNET
);

System Operations

Health Check

const health = await sdk.healthCheck();
if (health.status.reachable) {
  console.log('API is healthy');
}

🔐 Security Best Practices

  1. Environment Variables: Store credentials in environment variables, not in code
  2. Server-Side Only: This SDK is designed for server-side use only
  3. Credential Security: Keep credentials secure and never commit them to version control
  4. Error Handling: Always wrap API calls in try-catch blocks
  5. Token Management: Use refresh tokens for long-running applications
try {
  const vaultInfo = await sdk.getVaultInfo(vaultAddress, network);
  // Handle success
} catch (error) {
  console.error('Operation failed:', error.message);
  // Handle error appropriately
}

🔒 Vault Management Roles

The SDK supports different operational roles:

  • Vault Managers: Can create and configure vaults
  • Emergency Managers: Can execute emergency rescues
  • Strategy Managers: Can pause/unpause individual strategies
  • Regular Users: Can deposit, withdraw, and view vault information

🏗️ Development

Building

pnpm run build

Testing

Unit Tests (Mocked)

# Run unit tests
pnpm test

# Run with coverage
pnpm run test:coverage

# Watch mode
pnpm run test:watch

# Run integration tests
pnpm run test:integration

# Run all tests
pnpm run test:all

Code Quality

pnpm run lint
pnpm run lint:fix

📊 Type Definitions

The SDK exports comprehensive TypeScript types:

import {
  DefindexSDK,
  DefindexSDKConfig,
  SupportedNetworks,
  CreateVaultParams,
  DepositParams,
  WithdrawParams,
  WithdrawSharesParams,
  VaultInfo,
  VaultBalance,
  VaultAPY,
  // ... and many more
} from '@defindex/sdk';

🌐 Frontend Integration

While server-side focused, you can create secure frontend integrations:

// Backend API endpoint using API key
app.post('/api/vault-info', async (req, res) => {
  try {
    const sdk = new DefindexSDK({
      apiKey: process.env.DEFINDEX_API_KEY
    });
    
    const vaultInfo = await sdk.getVaultInfo(req.body.vaultAddress, req.body.network);
    res.json(vaultInfo);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

📖 Documentation

For comprehensive examples and detailed API documentation, see:


Built with ❤️ by the PaltaLabs team.

版本与发布记录

@defindex/sdk 共发布 8 个版本,首次发布于 2025/07/30;过去 12 个月发布了 6 个版本。

版本发布日期距今
0.3.0latest2026/04/097 个月前
0.3.0-alpha.1alpha2026/02/119 个月前
0.3.0-alpha.02026/02/119 个月前
0.2.1-alpha.02026/02/109 个月前
0.2.0-alpha.02026/02/109 个月前
0.1.22025/11/2811 个月前

关于 @defindex/sdk 的常见问题

@defindex/sdk 是什么?

Official TypeScript SDK for DeFindex API

如何安装 @defindex/sdk?

在项目目录运行 npm install @defindex/sdk,或使用 pnpm add / yarn add / bun add。

@defindex/sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@defindex/sdk 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@defindex/sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=16.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@defindex/sdk 可以商用吗?

@defindex/sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@defindex/sdk 的下载量有多少?

根据 npm 官方下载统计,@defindex/sdk 在 2026/10/12 – 2026/11/10 这 30 天内被下载 3,709 次,日均约 124 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@defindex/sdk 还在维护吗?

最新版本 0.3.0 发布于 2026/04/09(7 个月前);至今共发布 8 个版本,其中过去 12 个月发布了 6 个;首次发布于 2025/07/30。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。