关于 marginfi
marginfi Development Guide 是面向 Solana 开发者的 Marginfi 借贷协议开发指南,介绍 SDK 初始化、账户管理和借贷操作。它还涵盖闪电贷、杠杆循环及账户健康度计算。
主要功能
- 01存款、借款、还款与提取
- 02管理多个独立账户
- 03计算账户健康度与借款能力
- 04执行闪电贷
- 05单笔交易构建杠杆仓位
- 06构建底层交易指令
适用场景
- 01开发 Solana 借贷应用
- 02管理协议账户的资产与负债
- 03在单笔交易中执行闪电贷操作
- 04检查仓位健康度与可借额度
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ sendaifun/ skills --skill marginfi安装后在 Claude Code 中输入/marginfi确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
docs/troubleshooting.mdexamples/lending/borrow-repay.mddeposit-withdraw.mdresources/marginfi-sdk-api-reference.mdprogram-addresses.mdtemplates/collateral-borrow-setup.tsfull-integration.tslending-setup.ts详细介绍
Marginfi 开发指南
使用 Marginfi 在 Solana 上构建借贷应用。Marginfi 是一种去中心化、超额抵押的借贷协议,提供存款、借款、闪电贷和杠杆头寸。
概述
Marginfi 提供:
- 借贷:存入抵押品赚取收益,并以存款作为抵押进行借款
- 多个账户:每个钱包可创建多个账户,分别管理独立头寸
- 风险管理:利用资产和负债权重进行高级健康度计算
- 闪电贷:在单笔交易中执行原子化、无抵押借贷
- 循环借贷:在单笔交易中存入并借款,以建立杠杆头寸
- 多资产支持:SOL、USDC、LST(JitoSOL、mSOL)等
快速开始
安装
# Marginfi client SDK
npm install @mrgnlabs/marginfi-client-v2
# Common utilities
npm install @mrgnlabs/mrgn-common
# Required peer dependencies
npm install @solana/web3.js @coral-xyz/anchor
环境设置
# .env file
SOLANA_RPC_URL=https://api.mainnet-beta.solana.com
WALLET_KEYPAIR_PATH=./keypair.json
Marginfi SDK(marginfi-client-v2)
该 SDK 支持与 Marginfi 借贷协议交互,可用于存款、借款、还款、提现和高级操作。
核心类
| 类 | 用途 |
|---|---|
MarginfiClient | 用于加载群组和银行的主客户端 |
MarginfiAccountWrapper | 用户账户管理和借贷操作 |
Bank | 单个借贷池的配置和状态 |
Balance | 账户中的资产或负债头寸 |
NodeWallet | 用于服务端的 Wallet 适配器 |
初始化客户端
import { MarginfiClient, getConfig } from "@mrgnlabs/marginfi-client-v2";
import { NodeWallet } from "@mrgnlabs/mrgn-common";
import { Connection, Keypair } from "@solana/web3.js";
const connection = new Connection("https://api.mainnet-beta.solana.com");
const keypair = Keypair.fromSecretKey(/* your secret key */);
const wallet = new NodeWallet(keypair);
// Get production configuration
const config = getConfig("production");
// Load Marginfi client
const client = await MarginfiClient.fetch(config, wallet, connection);
// Access banks
for (const [address, bank] of client.banks) {
console.log(`${bank.tokenSymbol}: ${address}`);
}
按代币获取银行
// Get bank by token symbol
const solBank = client.getBankByTokenSymbol("SOL");
const usdcBank = client.getBankByTokenSymbol("USDC");
// Get bank by mint address
const usdcMint = new PublicKey("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
const usdcBankByMint = client.getBankByMint(usdcMint);
// Get bank by public key
const bank = client.getBankByPk(new PublicKey("..."));
创建账户
// Create a new Marginfi account
const account = await client.createMarginfiAccount();
console.log("Account address:", account.address.toBase58());
console.log("Authority:", account.authority.toBase58());
获取现有账户
// Get all accounts for a wallet
const accounts = await client.getMarginfiAccountsForAuthority(wallet.publicKey);
for (const account of accounts) {
console.log("Account:", account.address.toBase58());
console.log("Active balances:", account.activeBalances.length);
// Check positions
for (const balance of account.activeBalances) {
const bank = client.getBankByPk(balance.bankPk);
const quantity = balance.computeQuantityUi(bank!);
console.log(` ${bank?.tokenSymbol}: Assets=${quantity.assets}, Liabilities=${quantity.liabilities}`);
}
}
存入抵押品
async function deposit(
account: MarginfiAccountWrapper,
client: MarginfiClient,
tokenSymbol: string,
amount: number // UI-denominated amount (tokens, e.g., 1 for 1 SOL)
) {
const bank = client.getBankByTokenSymbol(tokenSymbol);
if (!bank) throw new Error(`Bank ${tokenSymbol} not found`);
// Execute deposit
const signature = await account.deposit(amount, bank.address);
console.log("Deposit signature:", signature);
return signature;
}
// Example: Deposit 1 SOL
await deposit(account, client, "SOL", 1);
借入资产
async function borrow(
account: MarginfiAccountWrapper,
client: MarginfiClient,
tokenSymbol: string,
amount: number
) {
const bank = client.getBankByTokenSymbol(tokenSymbol);
if (!bank) throw new Error(`Bank ${tokenSymbol} not found`);
// Execute borrow
const signature = await account.borrow(amount, bank.address);
console.log("Borrow signature:", signature);
return signature;
}
// Example: Borrow 100 USDC
await borrow(account, client, "USDC", 100);
偿还债务
async function repay(
account: MarginfiAccountWrapper,
client: MarginfiClient,
tokenSymbol: string,
amount: number,
repayAll: boolean = false
) {
const bank = client.getBankByTokenSymbol(tokenSymbol);
if (!bank) throw new Error(`Bank ${tokenSymbol} not found`);
// Execute repay
const signature = await account.repay(amount, bank.address, repayAll);
console.log("Repay signature:", signature);
return signature;
}
// Partial repay
await repay(account, client, "USDC", 50);
// Repay all (handles accrued interest)
await repay(account, client, "USDC", 0, true);
提取抵押品
async function withdraw(
account: MarginfiAccountWrapper,
client: MarginfiClient,
tokenSymbol: string,
amount: number,
withdrawAll: boolean = false
) {
const bank = client.getBankByTokenSymbol(tokenSymbol);
if (!bank) throw new Error(`Bank ${tokenSymbol} not found`);
// Execute withdraw
const signature = await account.withdraw(amount, bank.address, withdrawAll);
console.log("Withdraw signature:", signature);
return signature;
}
// Partial withdraw
await withdraw(account, client, "SOL", 0.5);
// Withdraw all
await withdraw(account, client, "SOL", 0, true);
高级操作
闪电贷
执行必须在同一笔交易中偿还的无抵押贷款:
import { TransactionInstruction } from "@solana/web3.js";
async function executeFlashLoan(
account: MarginfiAccountWrapper,
customInstructions: TransactionInstruction[]
) {
// Flash loan allows you to borrow without collateral
// as long as you repay in the same transaction
const signature = await account.flashLoan({
ixs: customInstructions
});
console.log("Flash loan signature:", signature);
return signature;
}
循环借贷(杠杆)
在单笔交易中存入并借款,以建立杠杆头寸:
import { AddressLookupTableAccount, TransactionInstruction } from "@solana/web3.js";
async function loop(
account: MarginfiAccountWrapper,
client: MarginfiClient,
depositToken: string,
borrowToken: string,
depositAmount: number,
borrowAmount: number,
swapInstructions: TransactionInstruction[],
swapLookupTables: AddressLookupTableAccount[]
) {
const depositBank = client.getBankByTokenSymbol(depositToken);
const borrowBank = client.getBankByTokenSymbol(borrowToken);
if (!depositBank || !borrowBank) {
throw new Error("Bank not found");
}
const signature = await account.loop(
depositAmount,
borrowAmount,
depositBank.address,
borrowBank.address,
swapInstructions,
swapLookupTables
);
console.log("Loop signature:", signature);
return signature;
}
使用抵押品还款
通过兑换使用已存入的抵押品偿还债务:
async function repayWithCollateral(
account: MarginfiAccountWrapper,
client: MarginfiClient,
repayAmount: number,
withdrawAmount: number,
depositToken: string,
borrowToken: string,
swapInstructions: TransactionInstruction[],
swapLookupTables: AddressLookupTableAccount[]
) {
const depositBank = client.getBankByTokenSymbol(depositToken);
const borrowBank = client.getBankByTokenSymbol(borrowToken);
if (!depositBank || !borrowBank) {
throw new Error("Bank not found");
}
const signature = await account.repayWithCollateral(
repayAmount,
withdrawAmount,
borrowBank.address,
depositBank.address,
swapInstructions,
swapLookupTables
);
return signature;
}
账户健康度
计算健康度组成部分
import { MarginRequirementType } from "@mrgnlabs/marginfi-client-v2";
// Get health components
const health = account.computeHealthComponents(MarginRequirementType.Initial);
console.log("Assets:", health.assets.toString());
console.log("Liabilities:", health.liabilities.toString());
// Get free collateral (borrowing capacity)
const freeCollateral = account.computeFreeCollateral();
console.log("Free collateral:", freeCollateral.toString());
银行信息
获取银行详情
const bank = client.getBankByTokenSymbol("SOL");
if (bank) {
console.log("Address:", bank.address.toBase58());
console.log("Token Symbol:", bank.tokenSymbol);
console.log("Mint:", bank.mint.toBase58());
console.log("Decimals:", bank.mintDecimals);
// Compute rates
const rates = bank.computeInterestRates();
console.log("Lending Rate:", rates.lendingRate.toString());
console.log("Borrowing Rate:", rates.borrowingRate.toString());
// Compute totals
const totalAssets = bank.getTotalAssetQuantity();
const totalLiabilities = bank.getTotalLiabilityQuantity();
const utilization = bank.computeUtilizationRate();
console.log("Total Assets:", totalAssets.toString());
console.log("Total Liabilities:", totalLiabilities.toString());
console.log("Utilization:", utilization.toString());
}
构建指令(底层)
如需更多控制,可分别构建指令:
// Build deposit instruction without executing
const { instructions, keys } = await account.makeDepositIx(
1,
solBank.address
);
// Build borrow instruction
const borrowIx = await account.makeBorrowIx(
100,
usdcBank.address
);
// Build repay instruction
const repayIx = await account.makeRepayIx(
50,
usdcBank.address
);
// Build withdraw instruction
const withdrawIx = await account.makeWithdrawIx(
0.5,
solBank.address
);
环境配置
该 SDK 支持多个环境:
import { getConfig } from "@mrgnlabs/marginfi-client-v2";
// Production (mainnet)
const prodConfig = getConfig("production");
// Program: MFv2hWf31Z9kbCa1snEPYctwafyhdvnV7FZnsebVacA
// Group: 4qp6Fx6tnZkY5Wropq9wUYgtFxXKwE6viZxFHg3rdAG8
// Alpha (mainnet)
const alphaConfig = getConfig("alpha");
// Staging
const stagingConfig = getConfig("staging");
// Development
const devConfig = getConfig("dev");
常量
SDK 导出了实用常量:
import {
PDA_BANK_LIQUIDITY_VAULT_AUTH_SEED,
PDA_BANK_INSURANCE_VAULT_AUTH_SEED,
PDA_BANK_FEE_VAULT_AUTH_SEED,
PYTH_PRICE_CONF_INTERVALS,
SWB_PRICE_CONF_INTERVALS,
MAX_CONFIDENCE_INTERVAL_RATIO,
DEFAULT_ORACLE_MAX_AGE,
USDC_DECIMALS,
ADDRESS_LOOKUP_TABLE_FOR_GROUP,
} from "@mrgnlabs/marginfi-client-v2";
资源
| 资源 | 链接 |
|---|---|
| 官方 SDK 文档 | docs.marginfi.com/ts-sdk |
| 协议文档 | docs.marginfi.com |
| GitHub 仓库 | github.com/mrgnlabs/mrgn-ts |
| SDK 包 | @mrgnlabs/marginfi-client-v2 |
| 常用工具 | @mrgnlabs/mrgn-common |
| SDK 配置 | configs.json (repo) |
| SDK 常量 | constants.ts (repo) |
注意:所链接的
configs.json和constants.ts可能并不完整;请查看官方仓库,获取最新值和其他常量。
相关文件
- marginfi-sdk-api-reference.md - 完整 API 参考
- program-addresses.md - 程序和账户地址
- troubleshooting.md - 常见问题及解决方案
评论
支持 Markdown