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
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#

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 after grace 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)
force_close_positionForce-close a lender position after maturity + grace (borrower)
claim_haircutClaim haircut recovery tokens (lender)
force_claim_haircutForce-claim haircut on behalf of lender (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)
totalDepositedu64Mutable capacity tracker (+deposits, -withdraw payout)
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
haircutAccumulatoru64Distressed-withdrawal haircut gap reserved from later sweeps

Lender Position#

FieldTypeDescription
versionu8Account schema version
marketPublicKeyAssociated market address
lenderPublicKeyLender wallet address
scaledBalanceu128Shares held (multiply by scale factor for value)
bumpu8PDA bump seed
haircutOwedu64Unclaimed haircut recovery tokens owed to lender
withdrawalSfu128 (WAD)Settlement factor at last withdrawal/claim (for recovery calc)

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

Haircut State#

FieldTypeDescription
versionu8Account schema version
marketPublicKeyAssociated market address
claimWeightSumu128Sum of per-position claim weights
claimOffsetSumu128Sum of per-position claim offsets
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 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#

FunctionPurpose
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);
}

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';