marginfi について
marginfi Development Guideは、Marginfiプロトコルを使うSolana開発者向けのガイドです。SDKによる口座管理や貸借操作に加え、フラッシュローン、レバレッジポジション、口座の健全性計算を扱います。
主な機能
- 01預け入れ、借入、返済、引き出し
- 02複数の独立口座の管理
- 03口座健全性と借入可能額の計算
- 04フラッシュローンの実行
- 05単一トランザクションでのレバレッジ構築
- 06低レベルのトランザクション命令の構築
活用シーン
- 01Solanaの融資アプリの開発
- 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 では、以下を利用できます。
- 貸し借り:担保を預け入れて利回りを得たり、預け入れた資産を担保に借り入れたりできます
- 複数のアカウント:ウォレットごとに、独立したポジションを持つ複数のアカウントを作成できます
- リスク管理:資産と負債のウェイトを使用した高度な健全性計算を行います
- フラッシュローン:1 つのトランザクション内で実行する、無担保のアトミックな貸し付けです
- ルーピング:1 つのトランザクション内で預け入れと借り入れを行い、レバレッジポジションを構築できます
- マルチアセット対応: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 | サーバーサイドで使用するウォレットアダプター |
クライアントの初期化
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;
}
ルーピング(レバレッジ)
1 つのトランザクション内で預け入れと借り入れを行い、レバレッジポジションを構築します。
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 対応