@0dotxyz/p0-ts-sdk

中文文档
2.12.0发布于 2026/11/03MITTypeScriptESM + CJS构建来源已验证近 30 天下载 2.1万

TypeScript SDK for P0 Protocol - A Solana DeFi lending protocol

原始使用文档
文档目录33 节
  1. Features
  2. Installation
  3. Quick Start
  4. 1. Initialize the Client
  5. 2. Load Your Account
  6. 3. Find a Bank
  7. 4. Deposit Tokens
  8. 5. Borrow Against Collateral
  9. 6. Monitor Account Health
  10. 📚 Examples
  11. Running Examples
  12. 🏗️ Core Concepts
  13. Project0Client
  14. MarginfiAccount & Wrapper
  15. Bank
  16. Balance
  17. 📦 Package Structure
  18. 🎯 Key Features
  19. Type Safety
  20. Multiple Bank Support
  21. Health Calculations
  22. 🧪 Testing
  23. 🛠️ Development
  24. Prerequisites
  25. Setup
  26. Project Structure
  27. Available Scripts
  28. 📦 Publishing
  29. 🤝 Contributing
  30. Development Workflow
  31. 📄 License
  32. 🙏 Acknowledgments
  33. ⚠️ Disclaimer

Project 0 TypeScript SDK

npm version npm downloads License: MIT TypeScript GitHub

A modern, type-safe TypeScript SDK for interacting with the P0 Protocol on Solana. Lend, borrow, and manage leveraged DeFi positions with a clean, developer-friendly API.

📖 Read the Full Documentation

Features

  • 🔒 Type-safe: Full TypeScript support with comprehensive type definitions
  • 📦 Tree-shakeable: Optimized ESM and CJS builds (<1MB)
  • 🧪 Well-tested: Unit and integration tests with Vitest
  • 📚 Rich examples: 7+ runnable examples covering all core features
  • 🔄 Modern tooling: Built with tsup, ESLint, Prettier
  • 🎯 Solana-native: Built on Anchor with full on-chain integration
  • ⚡ Production-ready: Used in production applications

Installation

npm install @0dotxyz/p0-ts-sdk
# or
yarn add @0dotxyz/p0-ts-sdk
# or
pnpm add @0dotxyz/p0-ts-sdk

Quick Start

1. Initialize the Client

import { Connection, PublicKey } from "@solana/web3.js";
import { Project0Client, getConfig } from "@0dotxyz/p0-ts-sdk";

// Connect to Solana
const connection = new Connection("https://api.mainnet-beta.solana.com", "confirmed");

// Get configuration (mainnet-beta)
const config = getConfig("production");

// Initialize the client (loads all banks and oracle prices)
const client = await Project0Client.initialize(connection, config);

console.log(`Loaded ${client.banks.length} banks`);

2. Load Your Account

import { MarginfiAccount, MarginfiAccountWrapper } from "@0dotxyz/p0-ts-sdk";

const accountAddress = new PublicKey("YOUR_MARGINFI_ACCOUNT_ADDRESS");

// Fetch your account
const account = await MarginfiAccount.fetch(accountAddress, client.program);

// Wrap it for cleaner API
const wrappedAccount = new MarginfiAccountWrapper(account, client);

3. Find a Bank

import { AssetTag } from "@0dotxyz/p0-ts-sdk";

// Option 1: Get bank by address
const bank = client.getBank(new PublicKey("BANK_ADDRESS"));

// Option 2: Get all banks for a mint (e.g., USDC)
const USDC_MINT = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
const usdcBanks = client.getBanksByMint(USDC_MINT);

4. Deposit Tokens

// Build deposit transaction
const depositTx = await wrappedAccount.makeDepositTx(
  usdcBank.address,
  "100" // Amount in UI units (100 USDC)
);

// Simulate (optional, but recommended)
const simulation = await connection.simulateTransaction(depositTx);
console.log(`Compute units: ${simulation.value.unitsConsumed}`);

// Sign and send
// depositTx.sign([wallet]);
// await connection.sendTransaction(depositTx);

5. Borrow Against Collateral

// Check how much you can borrow (account health + bank borrow cap + bank liquidity)
const maxBorrow = wrappedAccount.computeMaxBorrowForBank(usdcBank.address);
console.log(`Max borrow: $${maxBorrow.toString()}`);

// Build borrow transaction
const borrowTx = await wrappedAccount.makeBorrowTx(
  usdcBank.address,
  "100" // Borrow 100 USDC
);

// Send transaction...

6. Monitor Account Health

import { MarginRequirementType } from "@0dotxyz/p0-ts-sdk";

// Get free collateral in USD
const freeCollateral = wrappedAccount.computeFreeCollateral();
console.log(`Free collateral: $${freeCollateral.toString()}`);

// Get health components
const health = wrappedAccount.computeHealthComponents(MarginRequirementType.Initial);

const healthFactor = health.assets.div(health.liabilities);
console.log(`Health factor: ${healthFactor.toString()}`);

📚 Examples

Check out the examples/ directory for complete, runnable examples:

Each example includes:

  • ✅ Full setup instructions
  • ✅ Detailed comments
  • ✅ Error handling
  • ✅ Transaction simulation

Running Examples

cd examples
cp .env.example .env
# Edit .env with your values
tsx 01-deposit.ts

🏗️ Core Concepts

Project0Client

The main SDK client that manages protocol interactions.

const client = await Project0Client.initialize(connection, config);

// Pre-loaded data (fetched once at initialization)
client.banks                // All available banks
client.bankMap              // Banks indexed by address
client.oraclePriceByBank   // Latest oracle prices
client.mintDataByBank      // Token mint metadata
client.addressLookupTables // For transaction optimization

// Methods
client.getBank(address)             // Get bank by address
client.getBanksByMint(mint, tag?)   // Get all banks for a mint

Benefits:

  • Single initialization loads all chain data
  • Reuse throughout your application
  • Automatic oracle price caching
  • Built-in lookup table support

MarginfiAccount & Wrapper

Your lending account on the protocol.

// Fetch raw account
const account = await MarginfiAccount.fetch(address, client.program);

// Wrap for clean API (recommended)
const wrapped = new MarginfiAccountWrapper(account, client);

// All methods have access to banks, oracles, etc.
wrapped.computeMaxBorrowForBank(bankAddress);
wrapped.makeDepositTx(bankAddress, amount);
wrapped.computeFreeCollateral();

Bank

A lending pool for a specific token.

const bank = client.getBank(bankAddress);

bank.mint; // Token mint address
bank.config; // Interest rates, weights, limits
bank.config.assetWeightInit; // Collateral factor (LTV)
bank.config.liabilityWeightInit; // Borrow weight

Balance

Your position in a specific bank.

const balance = account.balances[0];

balance.bankPk; // Bank address
balance.assetShares; // Deposit shares
balance.liabilityShares; // Borrow shares
balance.active; // Is position active?

📦 Package Structure

The SDK provides optimized entry points:

// Main SDK (core functionality)
import { Project0Client, MarginfiAccount, getConfig } from "@0dotxyz/p0-ts-sdk";

// Vendor utilities (oracle integrations, Jupiter, etc.)
import { fetchOracleData, OraclePrice } from "@0dotxyz/p0-ts-sdk/vendor";

Why separate vendor exports?

  • Reduces bundle size for simple use cases
  • Oracle libraries (Pyth, Scope) are large
  • Tree-shake what you don't need

🎯 Key Features

Type Safety

Full TypeScript support with exported types:

import type {
  MarginfiAccountType,
  BankType,
  BalanceType,
  OraclePrice,
  MarginRequirementType,
  Project0Config,
} from "@0dotxyz/p0-ts-sdk";

Multiple Bank Support

Handle cases where multiple banks exist for the same mint:

// Get ALL SOL banks (main + Kamino)
const solBanks = client.getBanksByMint(WSOL_MINT);

// Filter by tag
const mainSolBanks = client.getBanksByMint(WSOL_MINT, AssetTag.SOL);
const kaminoBanks = client.getBanksByMint(WSOL_MINT, AssetTag.KAMINO);

Health Calculations

Built-in account health monitoring:

import { MarginRequirementType } from "@0dotxyz/p0-ts-sdk";

// Free collateral (how much you can still borrow)
const free = wrapped.computeFreeCollateral();

// Health components (assets vs liabilities)
const health = wrapped.computeHealthComponents(
  MarginRequirementType.Initial // or Maintenance
);

// Max amounts — bank-aware:
//   borrow   = min(health-based, remaining borrow cap, available bank liquidity, rate-limit headroom)
//   withdraw = min(health-based, available bank liquidity, rate-limit headroom)
//   deposit  = remaining deposit cap (optionally min'd with your wallet balance)
// (rate-limit headroom = bank net-outflow limiter in tokens + group USD limiter, if enabled)
const maxBorrow = wrapped.computeMaxBorrowForBank(bankAddress);
const maxWithdraw = wrapped.computeMaxWithdrawForBank(bankAddress);
const maxDeposit = wrapped.computeMaxDepositForBank(bankAddress, { walletBalance: 1_000 });

// Pass { ignoreBankLimits: true } to get the purely health-based borrow/withdraw amount

🧪 Testing

The SDK includes comprehensive tests:

# Unit tests (fast, no RPC needed)
pnpm test:unit

# Integration tests (requires RPC)
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com pnpm test:integration

# All tests
pnpm test

# With coverage
pnpm test:coverage

Testing Strategy:

  • Unit tests: Pure calculations, conversions, validations
  • Integration tests: Real chain data, transaction building, simulations

See TESTING.md for details.

🛠️ Development

Prerequisites

  • Node.js >= 18.0.0
  • pnpm (recommended)

Setup

# Install dependencies
pnpm install

# Build the SDK
pnpm build

# Watch mode (for development)
pnpm dev

# Type check
pnpm typecheck

# Lint and format
pnpm lint
pnpm format

Project Structure

p0-ts-sdk/
├── src/
│   ├── index.ts              # Main SDK exports
│   ├── vendor/               # Vendor entry point (oracles, etc.)
│   ├── config.ts             # Network configurations
│   ├── models/               # Core models
│   │   ├── client.ts         # Project0Client
│   │   ├── account.ts        # MarginfiAccount
│   │   ├── account-wrapper.ts # MarginfiAccountWrapper
│   │   ├── bank.ts           # Bank model
│   │   └── ...
│   ├── services/             # Business logic
│   │   ├── account/          # Account operations
│   │   ├── price/            # Oracle price fetching
│   │   └── ...
│   ├── instructions/         # Transaction builders
│   ├── types/                # TypeScript types
│   ├── idl/                  # Anchor IDL
│   └── utils/                # Helpers
├── tests/
│   ├── unit/                 # Unit tests (mocked)
│   ├── integration/          # Integration tests (real RPC)
│   └── fixtures/             # Test data
├── examples/                 # 7+ runnable examples
└── dist/                     # Build output
    ├── index.js              # ESM bundle
    ├── index.cjs             # CJS bundle
    ├── index.d.ts            # Type definitions
    └── vendor.*              # Vendor bundles

Available Scripts

ScriptDescription
pnpm buildBuild ESM + CJS bundles
pnpm devWatch mode for development
pnpm testRun all tests
pnpm test:unitRun unit tests only
pnpm test:integrationRun integration tests
pnpm test:coverageGenerate coverage report
pnpm lintLint with ESLint
pnpm formatFormat with Prettier
pnpm typecheckTypeScript type checking
pnpm cleanRemove build artifacts
pnpm changesetCreate a changeset for releases
pnpm versionBump version from changesets
pnpm releaseBuild and publish to npm

📦 Publishing

This package uses Changesets for version management and npm publishing.

See RELEASING.md for detailed instructions, or .changeset/QUICKSTART.md for a quick reference.

Quick publish:

npm login
pnpm changeset    # Document changes
pnpm version      # Bump version
pnpm release      # Publish to npm
git push --follow-tags

🤝 Contributing

We welcome contributions! Please see our contributing guidelines:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes with tests
  4. Run pnpm test and pnpm lint
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Development Workflow

# 1. Make changes
vim src/models/client.ts

# 2. Add tests
vim tests/unit/models/client.test.ts

# 3. Run tests
pnpm test:unit

# 4. Build
pnpm build

# 5. Test with examples
cd examples && tsx 01-deposit.ts

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

This SDK is built on top of the marginfi protocol, leveraging its on-chain programs and infrastructure.

Additional thanks to:

⚠️ Disclaimer

This SDK is provided as-is. Always:

  • Understand the risks of DeFi protocols
  • Monitor your account health
  • Use appropriate risk management
  • Audit your integration code

Built for builders 🛠️ by the P0 team

版本与发布记录

@0dotxyz/p0-ts-sdk 共发布 167 个版本,首次发布于 2026/01/15;过去 12 个月发布了 167 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
2.12.0latest2026/11/032 天前
3.0.0-next.3next2026/11/032 天前
2.11.12026/11/032 天前
3.0.0-next.22026/11/032 天前
3.0.0-next.12026/10/2214 天前
3.0.0-next.02026/10/2016 天前

其他发布通道:alpha → 2.10.1-alpha.0,next → 3.0.0-next.3。

关于 @0dotxyz/p0-ts-sdk 的常见问题

@0dotxyz/p0-ts-sdk 是什么?

TypeScript SDK for P0 Protocol - A Solana DeFi lending protocol

如何安装 @0dotxyz/p0-ts-sdk?

在项目目录运行 npm install @0dotxyz/p0-ts-sdk,或使用 pnpm add / yarn add / bun add。

@0dotxyz/p0-ts-sdk 支持 TypeScript 吗?

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

@0dotxyz/p0-ts-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@0dotxyz/p0-ts-sdk 需要什么版本的 Node.js?

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

@0dotxyz/p0-ts-sdk 可以商用吗?

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

@0dotxyz/p0-ts-sdk 的下载量有多少?

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

@0dotxyz/p0-ts-sdk 还在维护吗?

最新版本 2.12.0 发布于 2026/11/03(2 天前);至今共发布 167 个版本,其中过去 12 个月发布了 167 个;首次发布于 2026/01/15。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。