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 |
| Haircut State | ["haircut_state", market] | Tracks haircut recovery state for distressed markets |
| 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 after grace 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) |
force_close_position | Force-close a lender position after maturity + grace (borrower) |
claim_haircut | Claim haircut recovery tokens (lender) |
force_claim_haircut | Force-claim haircut on behalf of lender (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 | Mutable capacity tracker (+deposits, -withdraw payout) |
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 |
haircutAccumulator | u64 | Distressed-withdrawal haircut gap reserved from later sweeps |
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 |
haircutOwed | u64 | Unclaimed haircut recovery tokens owed to lender |
withdrawalSf | u128 (WAD) | Settlement factor at last withdrawal/claim (for recovery calc) |
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 |
Haircut State#
| Field | Type | Description |
|---|
version | u8 | Account schema version |
market | PublicKey | Associated market address |
claimWeightSum | u128 | Sum of per-position claim weights |
claimOffsetSum | u128 | Sum of per-position claim offsets |
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 validation, formatting, and resilience utilities shared across all Coalesce Finance TypeScript applications (web, mobile, API, indexer).
Installation#
npm install @coalescefi/shared-core
Note: This is typically installed as a dependency of @coalescefi/sdk.
Math Functions#
Math functions (WAD arithmetic, interest accrual, utilization, etc.) are maintained in @coalescefi/sdk and re-exported by shared-core for convenience. See the TypeScript SDK Math Reference for the full API.
// Preferred: import math directly from the SDK
import { calculateNormalizedAmount, estimateInterestAccrual } from '@coalescefi/sdk';
// Also works: shared-core re-exports all SDK math functions
import { calculateNormalizedAmount, estimateInterestAccrual } from '@coalescefi/shared-core';
Validation Helpers#
| Function | Purpose |
|---|
validateDepositAmount(amount, market, now) | Validate lender deposit |
validateBorrowAmount(amount, market, whitelist, now, vaultBalance?) | Validate borrower draw |
validateRepayAmount(amount, market) | Validate repayment amount |
validateWithdrawAmount(amount, position, market, now, vaultBalance?) | Validate lender withdrawal |
Typescript (23 lines)
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 liveVaultBalance = await readVaultBalance(connection, market.vault);
const borrowCheck = validateBorrowAmount(
500_000_000n,
market,
whitelist,
BigInt(Math.floor(Date.now() / 1000)),
liveVaultBalance // read from the vault token account via RPC for exactness
);
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';