SDK Guide

Coalesce Finance provides SDKs for building applications on the permissioned lending protocol.

Available SDKs

LanguagePackageUse CaseGuide
TypeScript@coalescefi/sdkWeb apps, Node.js backendsTypeScript SDK
Pythoncoalescefi-sdkScripts, data analysis, backend servicesPython SDK
Rustcoalescefi-sdkOn-chain programs, high-performance backendsRust SDK

PDA Reference

All account addresses in Coalesce Finance are Program Derived Addresses (PDAs). Each SDK provides helpers for deriving these addresses.

PDA TypeSeedsDescription
Protocol Config["protocol_config"]Singleton protocol configuration
Market["market", borrower, nonce_le_bytes]Lending market (unique per borrower + nonce)
Market Authority["market_authority", market]Signs vault token transfers
Vault["vault", market]Token account holding market deposits
Lender Position["lender", market, lender]Lender's position in a specific market
Borrower Whitelist["borrower_whitelist", borrower]Borrower's whitelisted status and capacity
Blacklist Check["blacklist", address]External compliance check account PDA

Language-specific derivation code: TypeScript | Python | Rust


Available Instructions

InstructionDescription
initialize_protocolInitialize protocol configuration (admin only)
set_fee_configUpdate fee settings (admin only)
create_marketCreate a new lending market (whitelisted borrower)
depositDeposit tokens into a market (lender)
borrowBorrow deposited funds from a market (borrower)
repayRepay borrowed principal (anyone can repay on behalf)
repay_interestRepay accrued interest (anyone can repay on behalf)
withdrawWithdraw after maturity (first withdraw triggers settlement)
collect_feesCollect accrued protocol fees (fee authority)
re_settleRecalculate settlement factor after late repayments (anyone)
close_lender_positionClose empty position to reclaim rent (lender)
withdraw_excessWithdraw excess funds from vault (borrower)
set_borrower_whitelistAdd/remove borrowers from whitelist (whitelist manager)
set_pausePause or unpause the protocol (admin)
set_blacklist_modeConfigure blacklist settings (admin)
set_adminTransfer admin role (admin)
set_whitelist_managerSet whitelist manager address (admin)

Language-specific instruction building: TypeScript | Python | Rust


Account Structures

Market

FieldTypeDescription
versionu8Account schema version
borrowerPublicKeyMarket creator/borrower address
mintPublicKeyToken mint (USDC)
vaultPublicKeyVault token account PDA
marketAuthorityBumpu8PDA bump for market authority
annualInterestBpsu16Interest rate in basis points
maturityTimestampi64Unix timestamp when market matures
maxTotalSupplyu64Maximum deposit capacity
marketNonceu64Unique nonce per borrower
scaledTotalSupplyu128Sum of all lender scaled balances (shares)
scaleFactoru128 (WAD)Deposit-to-shares conversion factor
accruedProtocolFeesu64Uncollected protocol fees (normalized USDC)
totalDepositedu64Cumulative total deposits (counter)
totalBorrowedu64Cumulative total borrowed (counter)
totalRepaidu64Cumulative total repaid (counter)
totalInterestRepaidu64Cumulative interest repaid (does not affect capacity)
lastAccrualTimestampi64Last interest accrual Unix timestamp
settlementFactorWadu128 (WAD)Post-settlement payout factor (0 = not settled)
bumpu8Market PDA bump seed

Lender Position

FieldTypeDescription
versionu8Account schema version
marketPublicKeyAssociated market address
lenderPublicKeyLender wallet address
scaledBalanceu128Shares held (multiply by scale factor for value)
bumpu8PDA bump seed

Borrower Whitelist

FieldTypeDescription
versionu8Account schema version
borrowerPublicKeyBorrower wallet address
isWhitelistedboolWhether borrower is currently whitelisted
maxBorrowCapacityu64Maximum borrow capacity across all markets
currentBorrowedu64Current total borrowed across all markets
bumpu8PDA bump seed

Protocol Config

FieldTypeDescription
versionu8Account schema version
adminPublicKeyProtocol admin address
feeRateBpsu16Protocol fee rate in basis points
feeAuthorityPublicKeyAddress authorized to collect fees
whitelistManagerPublicKeyKeypair authorized to manage borrower whitelist
blacklistProgramPublicKeyExternal program for blacklist lookups
isInitializedboolWhether protocol has been initialized
bumpu8PDA bump seed
isPausedboolWhether protocol is paused
isBlacklistFailClosedboolBlacklist mode (false = fail-open, true = fail-closed)

Language-specific account decoding: TypeScript | Python | Rust


Shared Core

The @coalescefi/shared-core package provides shared utilities for calculations across all Coalesce Finance applications.

Installation

npm install @coalescefi/shared-core

Note: This is typically installed as a dependency of @coalescefi/sdk.

Overview

shared-core ensures consistent calculations across:

  • SDK (client-side)
  • API (server-side)
  • Indexer (processing)
  • Web/Mobile apps (display)

Core Math Helpers

FunctionPurpose
calculateScaledAmount(amount, scaleFactor)Convert token amount to scaled shares
calculateNormalizedAmount(scaledAmount, scaleFactor)Convert scaled shares to token amount
calculateSettlementPayout(normalizedAmount, settlementFactorWad)Apply settlement factor haircut to a normalized amount
estimateInterestAccrual(market, now)Preview new scale factor and accrual deltas
calculateTotalSupply(scaledTotalSupply, scaleFactor)Convert scaled supply to token supply
calculateUtilizationRate(market)Compute utilization in BPS and decimal
import {
  calculateScaledAmount,
  calculateNormalizedAmount,
  calculateSettlementPayout,
  estimateInterestAccrual,
  formatTokenAmount,
} from '@coalescefi/shared-core';

const scaled = calculateScaledAmount(1_000_000_000n, 1_020_000_000_000_000_000n);
const value = calculateNormalizedAmount(scaled, 1_020_000_000_000_000_000n);
const payout = calculateSettlementPayout(value, 980_000_000_000_000_000n);

const { newScaleFactor } = estimateInterestAccrual(market, BigInt(Math.floor(Date.now() / 1000)));
console.log('Display value:', formatTokenAmount(value, 6));
console.log('Next scale factor:', newScaleFactor.toString());

Note: full withdraw payout is a two-step calculation: normalizedAmount = calculateNormalizedAmount(scaledBalance, scaleFactor) then payout = calculateSettlementPayout(normalizedAmount, settlementFactorWad).

Validation Helpers

FunctionPurpose
validateDepositAmount(amount, market, now)Validate lender deposit
validateBorrowAmount(amount, market, whitelist, now)Validate borrower draw
validateRepayAmount(amount, market)Validate repayment amount
validateWithdrawAmount(amount, position, market, now)Validate lender withdrawal
import { validateDepositAmount, validateBorrowAmount } from '@coalescefi/shared-core';

const depositCheck = validateDepositAmount(
  1_000_000n,
  market,
  BigInt(Math.floor(Date.now() / 1000))
);
if (!depositCheck.isValid) {
  console.error(depositCheck.error);
}

const borrowCheck = validateBorrowAmount(
  500_000_000n,
  market,
  whitelist,
  BigInt(Math.floor(Date.now() / 1000))
);
if (!borrowCheck.isValid) {
  console.error(borrowCheck.errorCode);
}

Formatting Helpers

FunctionPurpose
formatTokenAmount(amount, decimals)Human-readable token amount
formatUSD(amount, decimals)USD currency formatting
formatBps(bps)BPS to percent string
formatPercent(decimal)Decimal ratio to percent string
import { formatTokenAmount, formatUSD, formatBps, formatPercent } from '@coalescefi/shared-core';

console.log(formatTokenAmount(10_500_000_000n, 6)); // "10,500.00"
console.log(formatUSD(10_500_000_000n, 6)); // "$10,500.00"
console.log(formatBps(800)); // "8%"
console.log(formatPercent(0.75)); // "75%"

Shared Types and Constants

import type {
  ValidationResult,
  Market,
  LenderPosition,
  BorrowerWhitelist,
} from '@coalescefi/shared-core';
import { WAD, USDC_DECIMALS, SECONDS_PER_YEAR } from '@coalescefi/shared-core';