SDK Guide
Coalesce Finance provides SDKs for building applications on the permissioned lending protocol.
Available SDKs
| Language | Package | Use Case | Guide |
|---|
| TypeScript | @coalescefi/sdk | Web apps, Node.js backends | TypeScript SDK |
| Python | coalescefi-sdk | Scripts, data analysis, backend services | Python SDK |
| Rust | coalescefi-sdk | On-chain programs, high-performance backends | Rust SDK |
PDA Reference
All account addresses in Coalesce Finance are Program Derived Addresses (PDAs). Each SDK provides helpers for deriving these addresses.
| PDA Type | Seeds | Description |
|---|
| 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
| Instruction | Description |
|---|
initialize_protocol | Initialize protocol configuration (admin only) |
set_fee_config | Update fee settings (admin only) |
create_market | Create a new lending market (whitelisted borrower) |
deposit | Deposit tokens into a market (lender) |
borrow | Borrow deposited funds from a market (borrower) |
repay | Repay borrowed principal (anyone can repay on behalf) |
repay_interest | Repay accrued interest (anyone can repay on behalf) |
withdraw | Withdraw after maturity (first withdraw triggers settlement) |
collect_fees | Collect accrued protocol fees (fee authority) |
re_settle | Recalculate settlement factor after late repayments (anyone) |
close_lender_position | Close empty position to reclaim rent (lender) |
withdraw_excess | Withdraw excess funds from vault (borrower) |
set_borrower_whitelist | Add/remove borrowers from whitelist (whitelist manager) |
set_pause | Pause or unpause the protocol (admin) |
set_blacklist_mode | Configure blacklist settings (admin) |
set_admin | Transfer admin role (admin) |
set_whitelist_manager | Set whitelist manager address (admin) |
Language-specific instruction building: TypeScript | Python | Rust
Account Structures
Market
| Field | Type | Description |
|---|
version | u8 | Account schema version |
borrower | PublicKey | Market creator/borrower address |
mint | PublicKey | Token mint (USDC) |
vault | PublicKey | Vault token account PDA |
marketAuthorityBump | u8 | PDA bump for market authority |
annualInterestBps | u16 | Interest rate in basis points |
maturityTimestamp | i64 | Unix timestamp when market matures |
maxTotalSupply | u64 | Maximum deposit capacity |
marketNonce | u64 | Unique nonce per borrower |
scaledTotalSupply | u128 | Sum of all lender scaled balances (shares) |
scaleFactor | u128 (WAD) | Deposit-to-shares conversion factor |
accruedProtocolFees | u64 | Uncollected protocol fees (normalized USDC) |
totalDeposited | u64 | Cumulative total deposits (counter) |
totalBorrowed | u64 | Cumulative total borrowed (counter) |
totalRepaid | u64 | Cumulative total repaid (counter) |
totalInterestRepaid | u64 | Cumulative interest repaid (does not affect capacity) |
lastAccrualTimestamp | i64 | Last interest accrual Unix timestamp |
settlementFactorWad | u128 (WAD) | Post-settlement payout factor (0 = not settled) |
bump | u8 | Market PDA bump seed |
Lender Position
| Field | Type | Description |
|---|
version | u8 | Account schema version |
market | PublicKey | Associated market address |
lender | PublicKey | Lender wallet address |
scaledBalance | u128 | Shares held (multiply by scale factor for value) |
bump | u8 | PDA bump seed |
Borrower Whitelist
| Field | Type | Description |
|---|
version | u8 | Account schema version |
borrower | PublicKey | Borrower wallet address |
isWhitelisted | bool | Whether borrower is currently whitelisted |
maxBorrowCapacity | u64 | Maximum borrow capacity across all markets |
currentBorrowed | u64 | Current total borrowed across all markets |
bump | u8 | PDA bump seed |
Protocol Config
| Field | Type | Description |
|---|
version | u8 | Account schema version |
admin | PublicKey | Protocol admin address |
feeRateBps | u16 | Protocol fee rate in basis points |
feeAuthority | PublicKey | Address authorized to collect fees |
whitelistManager | PublicKey | Keypair authorized to manage borrower whitelist |
blacklistProgram | PublicKey | External program for blacklist lookups |
isInitialized | bool | Whether protocol has been initialized |
bump | u8 | PDA bump seed |
isPaused | bool | Whether protocol is paused |
isBlacklistFailClosed | bool | Blacklist 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
| Function | Purpose |
|---|
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
| Function | Purpose |
|---|
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);
}
| Function | Purpose |
|---|
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';