DocumentationOpen App

Positions

Manage positions — open, adjust, close, and monitor — using the SDK vNext. The SDK builds transactions but never signs them. Your agent or wallet client handles signing and submission.

Transaction Lifecycle

Every position action follows the same five-step flow:

StepMethodWhat Happens
PrepareprepareDeposit() / prepareOpen()Build a RawTx with calldata
PreviewpreviewDeposit() / previewOpen()Simulate the transaction against current state
ValidateCheck preview resultVerify HF, slippage, warnings
ExecutewalletClient.sendTransaction(rawTx)Sign and submit on-chain
Monitorsdk.accounts.getStatus()Track position health post-execution

The RawTx Type

All prepare methods return a RawTx — a ready-to-sign transaction object:

TypeScript
interface RawTx { to: `0x${string}`; // Target contract address calldata: `0x${string}`; // Encoded function call value: bigint; // ETH value (usually 0n) }

The SDK builds, never signs. You submit the transaction using your wallet client:

TypeScript
const txHash = await walletClient.sendTransaction({ to: rawTx.to, data: rawTx.calldata, value: rawTx.value, });

Depositing into a Pool

Prepare a Deposit

TypeScript
import { GearboxSDK } from "@gearbox-protocol/sdk/official"; const sdk = await GearboxSDK.init({ chains: [1], startFromCache: true, }); const rawTx = await sdk.positions.prepareDeposit({ pool: poolAddress, chainId: 1, amount: 10_000n * 10n ** 6n, // 10,000 USDC receiver: walletAddress, });

Preview a Deposit

Before submitting, simulate to verify expected outcomes:

TypeScript
const preview = await sdk.positions.previewDeposit({ pool: poolAddress, chainId: 1, amount: 10_000n * 10n ** 6n, receiver: walletAddress, }); console.log(`Shares received: ${preview.sharesReceived}`); console.log(`Share price: ${preview.sharePrice}`); console.log(`Breakeven: ${preview.breakevenDays} days`); console.log(`Warnings: ${preview.warnings.join(", ") || "none"}`);

Full Deposit Flow

TypeScript
// 1. Prepare const rawTx = await sdk.positions.prepareDeposit({ pool: poolAddress, chainId: 1, amount: depositAmount, receiver: walletAddress, }); // 2. Preview const preview = await sdk.positions.previewDeposit({ pool: poolAddress, chainId: 1, amount: depositAmount, receiver: walletAddress, }); // 3. Validate if (!preview.success || preview.warnings.length > 0) { console.error("Deposit preview failed:", preview.warnings); return; } // 4. Execute (SDK builds, you sign) const txHash = await walletClient.sendTransaction({ to: rawTx.to, data: rawTx.calldata, value: rawTx.value, }); await publicClient.waitForTransactionReceipt({ hash: txHash });

Opening a Leveraged Position

Prepare an Open

TypeScript
const rawTx = await sdk.positions.prepareOpen({ creditManager: cmAddress, chainId: 1, collateralToken: wstETHAddress, collateralAmount: 10n * 10n ** 18n, // 10 wstETH targetLeverage: 3.0, });

Preview an Open

TypeScript
const preview = await sdk.positions.previewOpen({ creditManager: cmAddress, chainId: 1, collateralToken: wstETHAddress, collateralAmount: 10n * 10n ** 18n, targetLeverage: 3.0, }); console.log(`Health Factor: ${preview.healthFactor}`); console.log(`Net APY: ${preview.netApy}%`); console.log(`Actual leverage: ${preview.actualLeverage}x`); console.log(`Debt: ${preview.debtAmount}`); console.log(`Swap impact: ${preview.swapImpactBps} bps`);

Full Open Flow

TypeScript
// 1. Prepare the transaction const rawTx = await sdk.positions.prepareOpen({ creditManager: cmAddress, chainId: 1, collateralToken: wstETHAddress, collateralAmount: collateralAmount, targetLeverage: 3.0, }); // 2. Preview and validate const preview = await sdk.positions.previewOpen({ creditManager: cmAddress, chainId: 1, collateralToken: wstETHAddress, collateralAmount: collateralAmount, targetLeverage: 3.0, }); if (!preview.success) { console.error("Position open failed simulation"); return; } if (preview.healthFactor < 1.5) { console.warn(`Health factor ${preview.healthFactor} is below safety threshold`); return; } if (preview.warnings.length > 0) { console.warn("Warnings:", preview.warnings); } // 3. Execute const txHash = await walletClient.sendTransaction({ to: rawTx.to, data: rawTx.calldata, value: rawTx.value, }); const receipt = await publicClient.waitForTransactionReceipt({ hash: txHash }); console.log(`Position opened: ${receipt.transactionHash}`);

Universal Transaction Preview

Use sdk.previewTransaction() to simulate any raw transaction against current chain state. This works for transactions built outside the SDK as well.

TypeScript
const result = await sdk.previewTransaction({ to: targetAddress, calldata: encodedCalldata, value: 0n, }, { chainId: 1, from: walletAddress, }); console.log(`Success: ${result.success}`); console.log(`Health factor: ${result.healthFactor}`); console.log(`Actions: ${result.actions.map(a => a.type).join(", ")}`); console.log(`Balance changes:`, result.balanceChanges); console.log(`Warnings: ${result.warnings.join(", ") || "none"}`);

Preview Result Fields

FieldTypeDescription
successbooleanWhether the simulation succeeded
healthFactornumber | nullProjected health factor after execution
actionsAction[]Decoded actions the transaction performs
balanceChangesBalanceChange[]Token balance deltas
warningsstring[]Human-readable risk warnings

Listing Credit Accounts

Retrieve all credit accounts owned by a wallet:

TypeScript
const accounts = await sdk.accounts.list({ owner: walletAddress, chainId: 1, }); for (const account of accounts) { console.log(`Account: ${account.address}`); console.log(` CM: ${account.creditManager}`); console.log(` Health Factor: ${account.healthFactor}`); console.log(` Total Value: $${account.totalValueUsd}`); }

Position Health and Status

Get detailed status for a specific credit account:

TypeScript
const status = await sdk.accounts.getStatus({ account: creditAccountAddress, chainId: 1, }); console.log(`Health Factor: ${status.healthFactor}`); console.log(`Leverage: ${status.leverage}x`); console.log(`Total Value: $${status.totalValueUsd}`); console.log(`Total Debt: $${status.totalDebtUsd}`); // Token composition for (const token of status.tokens) { console.log(` ${token.symbol}: ${token.balance} ($${token.valueUsd})`); } // Active bots for (const bot of status.bots) { console.log(` Bot: ${bot.address}${bot.permissions.join(", ")}`); }

Status Fields

FieldTypeDescription
healthFactornumberCurrent HF. Below 1 means liquidatable
totalValueUsdnumberPosition total value in USD
totalDebtUsdnumberOutstanding debt in USD
leveragenumberCurrent leverage ratio
tokensTokenPosition[]Per-token balances, values, and LT info
botsBotInfo[]Attached bots and their permissions
isPausedbooleanWhether the credit manager is paused
expirationDatestring | nullAccount expiration, if applicable

Monitoring Alerts

Use sdk.monitor.getAlerts() to check for active warnings on your positions:

TypeScript
const alerts = await sdk.monitor.getAlerts({ owner: walletAddress, chainId: 1, }); for (const alert of alerts) { console.log(`[${alert.severity}] ${alert.account}: ${alert.message}`); }

Alert Types

SeverityConditionSuggested Action
"warning"Health factor below 1.3Add collateral or reduce debt
"critical"Health factor below 1.1Immediate deleveraging or exit
"info"LT ramp activePlan scheduled adjustment
"info"Account nearing expirationClose or migrate before deadline

Position Lifecycle Example

A complete flow from discovery through monitoring:

TypeScript
import { GearboxSDK, Asset } from "@gearbox-protocol/sdk/official"; // 1. Initialize const sdk = await GearboxSDK.init({ chains: [1], startFromCache: true }); // 2. Discover const strategies = await sdk.strategies.list({ chainId: 1, asset: Asset.ETH, minNetApy: 3, }); const strategy = strategies[0]; // 3. Prepare const rawTx = await sdk.positions.prepareOpen({ creditManager: strategy.id, chainId: 1, collateralToken: wstETHAddress, collateralAmount: 10n * 10n ** 18n, targetLeverage: 3.0, }); // 4. Preview const preview = await sdk.positions.previewOpen({ creditManager: strategy.id, chainId: 1, collateralToken: wstETHAddress, collateralAmount: 10n * 10n ** 18n, targetLeverage: 3.0, }); if (!preview.success || preview.healthFactor < 1.5) { throw new Error("Preview failed safety checks"); } // 5. Execute (you sign) const txHash = await walletClient.sendTransaction({ to: rawTx.to, data: rawTx.calldata, value: rawTx.value, }); await publicClient.waitForTransactionReceipt({ hash: txHash }); // 6. Monitor const accounts = await sdk.accounts.list({ owner: walletAddress, chainId: 1 }); const status = await sdk.accounts.getStatus({ account: accounts[0].address, chainId: 1, }); console.log(`Position HF: ${status.healthFactor}`);

Method Reference

MethodReturnsDescription
sdk.positions.prepareDeposit(params)RawTxBuild a pool deposit transaction
sdk.positions.previewDeposit(params)DepositPreviewSimulate a pool deposit
sdk.positions.prepareOpen(params)RawTxBuild a leveraged position open
sdk.positions.previewOpen(params)OpenPreviewSimulate a position open
sdk.previewTransaction(rawTx, opts)TransactionPreviewUniversal simulation for any raw tx
sdk.accounts.list(params)CreditAccount[]List credit accounts for a wallet
sdk.accounts.getStatus(params)AccountStatusFull position health and composition
sdk.monitor.getAlerts(params)Alert[]Active warnings across positions

Learn More