npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

granite-math-sdk

v1.1.11

Published

Granite math sdk

Downloads

269

Readme

Granite Math SDK

A comprehensive SDK for interacting with Granite Protocol's smart contracts. This library provides utility functions for calculating positions, liquidations, rewards, and more.

Table of Contents

  1. Installation
  2. Account Management
  3. Borrowing & Lending
  4. Liquidations
  5. Liquidity Provider (LP) Functions
  6. LP Rewards
  7. Safety Module
  8. BTC Leverage
  9. Error Handling

Installation

npm install granite-math-sdk

Account Management

Functions for managing and monitoring account health and positions.

Account Health

import {
  calculateAccountHealth,
  calculateAccountLTV,
  calculateAccountMaxLTV,
  calculateAccountLiqLTV,
  calculateTotalCollateralValue,
  calculateMaxWithdrawAmount,
} from "granite-math-sdk";

// Get total value of collateral
const totalValue = calculateTotalCollateralValue(collaterals);

// Check account health (> 1 is healthy, < 1 needs attention)
const healthFactor = calculateAccountHealth(collaterals, currentDebt);

// Get current LTV ratio
const currentLTV = calculateAccountLTV(totalDebt, collaterals);

// Get maximum allowed LTV
const maxLTV = calculateAccountMaxLTV(collaterals);

// Get liquidation threshold LTV
const liqLTV = calculateAccountLiqLTV(collaterals);

// Calculate maximum amount that can be withdrawn for a specific collateral
const maxWithdraw = calculateMaxWithdrawAmount(
  collateralToWithdraw,
  allCollaterals,
  debtShares,
  openInterest,
  totalDebtShares,
  totalAssets,
  irParams,
  timeDelta,
  decimals,
  futureDeltaSeconds, // Optional: seconds to add for future debt calculation (default: 600)
);

When to use:

  • Monitor position health
  • Check if close to liquidation
  • Calculate available borrowing capacity
  • Calculate maximum withdrawal amounts
  • Assess risk levels

Borrowing & Lending

Functions for calculating borrowing capacity, interest rates, and debt conversions.

Borrowing Calculations

import {
  calculateBorrowCapacity,
  userAvailableToBorrow,
  calculateBorrowAPY,
  convertDebtAssetsToShares,
  convertDebtSharesToAssets,
} from "granite-math-sdk";

// Check how much you can borrow
const borrowCapacity = calculateBorrowCapacity(collaterals);
const availableToBorrow = userAvailableToBorrow(
  collaterals,
  freeLiquidity,
  reserveBalance,
  currentDebt,
);

// Get current borrow APY
const borrowAPY = calculateBorrowAPY(utilizationRate, irParams);

// Convert between debt shares and assets
const debtShares = convertDebtAssetsToShares(
  debtAssets,
  totalDebtShares,
  totalAssets,
  openInterest,
  protocolReservePercentage,
  irParams,
  timeDelta,
);

const debtAssets = convertDebtSharesToAssets(
  debtShares,
  openInterest,
  totalDebtShares,
  totalAssets,
  irParams,
  timeDelta,
);

When to use:

  • Before taking a loan to check capacity
  • To monitor borrowing costs
  • To convert between debt shares and actual debt amounts

Liquidations

Functions for liquidators to calculate opportunities and rewards.

Liquidation Calculations

import {
  liquidatorMaxRepayAmount,
  calculateCollateralToTransfer,
} from "granite-math-sdk";

// Check if and how much can be liquidated
const maxRepay = liquidatorMaxRepayAmount(
  debtShares,
  openInterest,
  totalDebtShares,
  totalAssets,
  irParams,
  timeDelta,
  collateralToLiquidate,
  allCollaterals,
);

if (maxRepay > 0) {
  // Calculate collateral you'll receive
  const collateralToReceive = calculateCollateralToTransfer(
    maxRepay,
    collateralToLiquidate,
  );

  // Calculate expected profit
  const profit = collateralToReceive * collateralToLiquidate.price - maxRepay;
}

When to use:

  • To check if a position can be liquidated
  • To calculate liquidation profitability
  • To determine how much collateral you'll receive

Liquidity Provider Functions

Functions for liquidity providers to manage their positions.

LP Calculations

import {
  convertLpAssetsToShares,
  convertLpSharesToAssets,
  calculateLpAPY,
  computeTotalEarning,
} from "granite-math-sdk";

// Convert between LP tokens and underlying assets
const lpShares = convertLpAssetsToShares(
  assets,
  totalShares,
  totalAssets,
  openInterest,
  protocolReservePercentage,
  irParams,
  timeDelta,
);

const assets = convertLpSharesToAssets(
  shares,
  totalShares,
  totalAssets,
  openInterest,
  protocolReservePercentage,
  irParams,
  timeDelta,
);

// Check current APY
const apy = calculateLpAPY(
  utilizationRate,
  irParams,
  protocolReservePercentage,
);

// Calculate earnings
const earnings = computeTotalEarning(
  shares,
  totalShares,
  totalAssets,
  openInterest,
  protocolReservePercentage,
  irParams,
  reserveBalance,
  timeDelta,
);

When to use:

  • When providing or removing liquidity
  • To track earnings
  • To evaluate LP returns

LP Rewards

Functions for calculating liquidity provider rewards.

Reward Calculations

import { earnedRewards, totalLpRewards } from "granite-math-sdk";

// Calculate rewards for current epoch
const rewards = earnedRewards(epoch, snapshots);

// Calculate total rewards for all LPs
const totalRewards = totalLpRewards(epoch);

When to use:

  • To track earned rewards
  • To calculate expected rewards
  • To monitor reward distribution

Safety Module

Functions for managing the safety module, the junior tranche of the protocol that absorbs losses before senior tranches.

BTC Leverage

Manage the math behind computing the max multiplier for leveraged BTC positions and the required collateral to swap.

Error Handling

Most functions will throw errors if required parameters are undefined or invalid. Always wrap SDK calls in try-catch blocks:

try {
  const result = someSDKFunction(params);
} catch (error) {
  console.error("SDK Error:", error.message);
}

Common errors to handle:

  • "LiquidationLTV is not defined"
  • "MaxLTV is not defined"
  • "Current debt cannot be zero"
  • "Insufficient data to compute rewards"
  • "Invalid epoch duration"