Expand description
Keystone DeFi SDK - Unified computation library for Arbitrum protocols.
This crate provides a single integration point for DeFi protocols on Arbitrum, combining precision arithmetic, financial calculations, and risk metrics.
§Quick Start
use keystone_defi::prelude::*;
use core::str::FromStr;
// Lending: Calculate health factor
let collateral = Decimal::from_str("10000").unwrap();
let debt = Decimal::from_str("5000").unwrap();
let threshold = Decimal::from_str("0.8").unwrap();
let health = health_factor(collateral, debt, threshold).unwrap();
// AMM: Calculate swap output
let output = calculate_swap_output(
Decimal::from(1000000i64),
Decimal::from(1000000i64),
Decimal::from(1000i64),
Decimal::from(30i64), // 0.3% fee
).unwrap();
// Vault: Calculate share price
let share_price = calculate_share_price(
Decimal::from(1000000i64),
Decimal::from(950000i64),
).unwrap();
// Derivatives: Calculate liquidation price
let position = PerpPosition {
size: Decimal::from_str("1.5").unwrap(),
entry_price: Decimal::from(2000i64),
is_long: true,
leverage: Decimal::from(10i64),
collateral: Decimal::from(300i64),
};
let liq_price = calculate_liquidation_price(&position, Decimal::from_str("0.01").unwrap()).unwrap();§Modules
precision- Core decimal arithmetic with 28-digit precisionlending- Health factor, liquidation, and borrow calculationsamm- Swap, liquidity, and price impact calculationsvault- ERC4626 share/asset calculations and compoundingderivatives- Perpetual futures, funding rates, and margin calculationsoptions- Black-Scholes pricing and Greeks
§Stylus Integration
All types are no_std compatible and work in Arbitrum Stylus smart contracts:
ⓘ
#![cfg_attr(not(feature = "export-abi"), no_main, no_std)]
use keystone_defi::prelude::*;
use stylus_sdk::prelude::*;
#[public]
impl MyContract {
pub fn calculate_health(&self, collateral: U256, debt: U256) -> Result<U256, Vec<u8>> {
let c = u256_to_decimal(collateral);
let d = u256_to_decimal(debt);
let threshold = Decimal::from_str("0.8").unwrap();
let hf = health_factor(c, d, threshold).map_err(|_| b"calc error".to_vec())?;
Ok(decimal_to_u256(hf))
}
}Modules§
- amm
- AMM and DEX calculations.
- day_
count - Day count conventions for interest calculations.
- derivatives
- Derivatives and perpetual futures calculations.
- interest
- Interest and time value calculations.
- interpolation
- Interpolation methods.
- lending
- Lending protocol calculations.
- options
- Options pricing and Greeks.
- precision
- Core precision arithmetic.
- prelude
- Commonly used imports for DeFi calculations.
- solver
- Numerical solvers.
- term_
structure - Yield curve and term structure.
- vault
- Vault and yield calculations.