@silo-finance/core
v0.0.1
Published
Core SDK for Silo Finance - calculations, services, and contract definitions
Readme
@silo-finance/core
Core SDK and pure functional library for Silo Finance. Contains the main SiloSdk class and all calculation logic.
Note: This package provides the SDK interface and calculations. For blockchain connectivity, you need an adapter:
@silo-finance/adapter-viem- Viem adapter for blockchain reads/writes@silo-finance/indexer- GraphQL client for indexed data
Installation
npm install @silo-finance/corepnpm add @silo-finance/coreSiloSdk Class
The main entry point for interacting with Silo protocol. Uses an adapter for blockchain connectivity.
import { SiloSdk } from "@silo-finance/core";
import { ViemAdapter } from "@silo-finance/adapter-viem";
import { createPublicClient, http } from "viem";
import { arbitrum } from "viem/chains";
const publicClient = createPublicClient({ chain: arbitrum, transport: http() });
const adapter = new ViemAdapter({ provider: publicClient });
const sdk = new SiloSdk({ chain: "arbitrum", adapter });
// Namespaced API
const apr = await sdk.markets.getBorrowAPR(siloAddress);
const position = await sdk.positions.get(market, userAddress);
const balance = await sdk.tokens.getBalance(tokenAddress, userAddress);
const apy = sdk.calc.getApy({ apr, periods: 365n });SDK Modules
| Module | Description |
|--------|-------------|
| sdk.markets | Fetch market data, APRs, utilization, liquidity |
| sdk.positions | Fetch user positions, LTV, solvency |
| sdk.tokens | Token balances, allowances, metadata |
| sdk.actions | Write operations (deposit, withdraw, borrow, repay) |
| sdk.calc | Pure calculations (APY, risk level, LTV analysis) |
Calculation Modules
The SDK provides focused modules for different calculation domains:
| Module | Import | Description |
|--------|--------|-------------|
| apr | @silo-finance/core/apr | APR/APY calculations, rewards, leverage rates |
| ltv | @silo-finance/core/ltv | Loan-to-value analysis, health factors |
| health | @silo-finance/core/health | Position health and risk assessment |
| silo | @silo-finance/core/silo | ERC4626 vault operations, interest accrual |
| market | @silo-finance/core/market | Market utilities and token helpers |
| position | @silo-finance/core/position | User position management |
APR Module
Calculate deposit and borrow rates, rewards, and leverage APR.
import {
getCollateralBaseApr,
getCollateralBaseAprByUtilization,
getApy,
calculateRewardsApr,
calculateLeverageApr,
calculateSimpleInterest,
getProjectionsState,
getAprState,
} from "@silo-finance/core/apr";Calculate Supply APR
import { getCollateralBaseApr, getApy } from "@silo-finance/core";
// Calculate supply APR from accrued assets
const supplyApr = getCollateralBaseApr({
collateralAccruedAssets: 1000000n * 10n ** 18n,
debtAccruedAssets: 500000n * 10n ** 18n,
debtBaseApr: 50000000000000000n, // 5% as 1e18
daoFee: 10000000000000000n, // 1%
deployerFee: 5000000000000000n, // 0.5%
});
// Convert APR to APY (daily compounding)
const supplyApy = getApy({ apr: supplyApr, periods: 365n });Calculate Leverage APR
import { calculateLeverageApr } from "@silo-finance/core";
import { makePercent, PERCENT_FACTOR } from "@silo-finance/primitives";
const leverageApr = calculateLeverageApr({
leverage: makePercent(300n * PERCENT_FACTOR / 100n), // 3x
supplyBaseApr: makePercent(50000000000000000n), // 5%
supplyUnderlyingApy: makePercent(0n),
supplyRewardsApr: makePercent(10000000000000000n), // 1%
borrowBaseApr: makePercent(80000000000000000n), // 8%
borrowUnderlyingApy: makePercent(0n),
borrowRewardsApr: makePercent(5000000000000000n), // 0.5%
});APR Trend Analysis
import { getProjectionsState, getAprState } from "@silo-finance/core";
const projection = getProjectionsState({
baseApr: currentApr,
baseApr3d: threeDayAvgApr,
}); // "increasing" | "decreasing" | "stable"
const aprState = getAprState({
projectionsState: projection,
utilizationState: "aboveOptimal",
}); // "stable" | "increasingSlowly" | "increasingRapidly" | "decreasing"LTV Module
Comprehensive loan-to-value analysis for position health.
import {
calculateLtv,
getMaxBorrowWithBuffer,
getMaxWithdrawWithBuffer,
convertToken,
BORROW_LTV_BUFFER,
WITHDRAW_LTV_BUFFER,
} from "@silo-finance/core/ltv";Calculate Position LTV
import { calculateLtv } from "@silo-finance/core/ltv";
const ltvResult = calculateLtv({
collateralSilo: {
tokenAddress: "0x...",
decimals: 18,
protectedBalance: 0n,
collateralBalance: 100n * 10n ** 18n,
maxLtv: 800000000000000000n, // 80%
lt: 850000000000000000n, // 85% liquidation threshold
lendingQuote: 3000n * 10n ** 8n,
solvencyQuote: 3000n * 10n ** 8n,
},
debtSilo: {
tokenAddress: "0x...",
decimals: 6,
debtBalance: 150000n * 10n ** 6n,
lendingQuote: 10n ** 8n,
solvencyQuote: 10n ** 8n,
},
});
// Access results
console.log(ltvResult.lendingLtv); // Current LTV
console.log(ltvResult.healthFactor); // Health factor (100% = safe)
console.log(ltvResult.borrowPowerUsed); // % of borrow capacity used
console.log(ltvResult.riskFactor); // Distance to liquidation
console.log(ltvResult.isAtRiskOfLiquidation);
console.log(ltvResult.maxBorrow); // Remaining borrow capacity
console.log(ltvResult.maxWithdraw); // Max safe withdrawalSafe Borrow/Withdraw Limits
import { getMaxBorrowWithBuffer, getMaxWithdrawWithBuffer } from "@silo-finance/core/ltv";
// Apply safety buffers to prevent tx failures from price fluctuations
const safeBorrow = getMaxBorrowWithBuffer(ltvResult); // -0.25% buffer
const safeWithdraw = getMaxWithdrawWithBuffer(ltvResult); // -0.5% bufferHealth Module
Position risk assessment and health factor calculations.
import {
calculateHealthFactor,
calculateLTV,
analyzeHealth,
getRiskLevel,
isLiquidatable,
calculateMaxBorrow,
calculateRequiredCollateral,
} from "@silo-finance/core/health";Analyze Position Health
import { analyzeHealth, RiskLevel } from "@silo-finance/core/health";
const health = analyzeHealth(position, prices);
console.log(health.healthFactor); // 1.5 = 150% collateralized
console.log(health.ltv); // Current LTV ratio
console.log(health.riskLevel); // RiskLevel enum
console.log(health.isLiquidatable); // boolean
// Risk levels
// RiskLevel.Safe - HF >= 1.5
// RiskLevel.Medium - HF >= 1.2
// RiskLevel.High - HF >= 1.05
// RiskLevel.Critical - HF >= 1.0
// RiskLevel.Insolvent - HF < 1.0Silo Module
ERC4626 vault operations and interest calculations.
import {
convertToShares,
convertToAssets,
maxWithdraw,
sharesForWithdraw,
getExchangeRate,
calculateUtilization,
accrueInterest,
calculateSupplyAPR,
} from "@silo-finance/core/silo";ERC4626 Conversions
import { convertToShares, convertToAssets } from "@silo-finance/core/silo";
const silo = {
totalAssets: 1000000n * 10n ** 18n,
totalShares: 900000n * 10n ** 18n,
};
const shares = convertToShares(silo, 100n * 10n ** 18n);
const assets = convertToAssets(silo, shares);Interest Accrual
import { accrueInterest, calculateUtilization, calculateSupplyAPR } from "@silo-finance/core/silo";
import { makePercent, PERCENT_FACTOR } from "@silo-finance/primitives";
// Calculate utilization
const utilization = calculateUtilization(
1000000n * 10n ** 18n, // deposited
500000n * 10n ** 18n // borrowed
); // 50%
// Calculate supply APR from borrow APR
const supplyAPR = calculateSupplyAPR(
makePercent(80000000000000000n), // 8% borrow APR
utilization,
makePercent(10000000000000000n) // 1% protocol fee
);
// Accrue interest over time
const newPrincipal = accrueInterest(
1000n * 10n ** 18n, // principal
makePercent(50000000000000000n), // 5% APR
86400 // 1 day in seconds
);Market Module
Utilities for working with Silo markets.
import {
getCollateralSilo,
getDebtSilo,
isValidToken,
getOtherToken,
getTokens,
} from "@silo-finance/core/market";Market Navigation
import { getCollateralSilo, getDebtSilo, getOtherToken } from "@silo-finance/core/market";
// Get the silo address for depositing collateral
const collateralSilo = getCollateralSilo(market, tokenAddress);
// Get the silo address for borrowing (opposite silo)
const debtSilo = getDebtSilo(market, tokenAddress);
// Get the paired token in the market
const otherToken = getOtherToken(market, tokenAddress);Type Safety
All functions use branded types from @silo-finance/primitives to prevent mixing incompatible values:
import type { Amount, Percent, USD } from "@silo-finance/primitives";
import { makePercent, makeAmount, PERCENT_FACTOR } from "@silo-finance/primitives";
// Create typed values
const apr: Percent = makePercent(50000000000000000n); // 5%
const amount: Amount = makeAmount(100n * 10n ** 18n);
// Values use 18 decimal precision (1e18 = 100%)
const fivePercent = (5n * PERCENT_FACTOR) / 100n;