Skip to main content

Types

Complete type reference for the SatsTerminal Borrow SDK.

Enums

ChainType

Supported blockchain networks.
enum ChainType {
  BASE = 'BASE',
  BITCOIN = 'BITCOIN',
  ETHEREUM = 'ETHEREUM',
  POLYGON = 'POLYGON',
  OPTIMISM = 'OPTIMISM',
  ARBITRUM = 'ARBITRUM',
  BSC = 'BNB_SMART_CHAIN',
  BASE_SEPOLIA = 'BASE_SEPOLIA',
  HYPERLIQUID = 'HYPERLIQUID-PERPS',
  LIGHTER = 'LIGHTER'
}

SessionScope

Session permission levels.
enum SessionScope {
  READ = 'read',
  DEFI = 'defi',
  FULL = 'full'
}

ErrorCode

Error classification codes.
enum ErrorCode {
  WALLET_NOT_CONNECTED = 'WALLET_NOT_CONNECTED',
  SMART_ACCOUNT_ERROR = 'SMART_ACCOUNT_ERROR',
  API_ERROR = 'API_ERROR',
  CONFIG_ERROR = 'CONFIG_ERROR',
  QUOTE_ERROR = 'QUOTE_ERROR',
  WORKFLOW_ERROR = 'WORKFLOW_ERROR',
  STORAGE_ERROR = 'STORAGE_ERROR',
  NETWORK_ERROR = 'NETWORK_ERROR',
  VALIDATION_ERROR = 'VALIDATION_ERROR'
}

Configuration

BorrowSDKConfig

SDK configuration options.
interface BorrowSDKConfig {
  // Required
  apiKey: string;
  wallet: WalletProvider;

  // Optional
  rpcUrl?: string;
  bundlerUrl?: string;
  storage?: StorageProvider;
  workflowPollInterval?: number;
  sessionValiditySeconds?: number;
  autoTrackWorkflows?: boolean;
  quoteSelector?: (quotes: Quote[]) => Quote;
  retryConfig?: RetryConfig;
  logger?: Logger;
}

WalletProvider

Wallet integration interface.
interface WalletProvider {
  address: string;
  publicKey?: string;
  signMessage: (message: string) => Promise<string>;
  sendBitcoin?: (toAddress: string, satoshis: number) => Promise<string>;
}

StorageProvider

Storage abstraction interface.
interface StorageProvider {
  getItem(key: string): string | null;
  setItem(key: string, value: string): void;
  removeItem(key: string): void;
  clear(): void;
}

RetryConfig

Request retry configuration.
interface RetryConfig {
  maxRetries: number;
  retryDelay: number;
  retryableStatusCodes: number[];
}

Logger

Logging interface.
interface Logger {
  debug: (message: string) => void;
  info: (message: string) => void;
  warn: (message: string) => void;
  error: (message: string) => void;
}

User & Session

UserStatus

Current user status.
interface UserStatus {
  isConnected: boolean;
  btcAddress?: string;
  smartAccountAddress?: string;
  isDeployed?: boolean;
  hasActiveSession: boolean;
  sessionExpiry?: number;
}

ActiveSession

Active session details.
interface ActiveSession {
  sessionKeyAddress?: string;
  sessionPrivateKey?: string;
  validUntil: number;
  authorizationSignature?: string;
  scope?: SessionScope;
}

Loan & Quote

QuoteRequest

Parameters for requesting quotes.
interface QuoteRequest {
  collateralAmount: string;
  loanAmount: string;
  filter?: {
    chains?: ChainType[];
    excludeChains?: ChainType[];
  };
}

Quote

Loan quote from a protocol. Use getQuoteFees() to fetch the fee breakdown for a selected quote.
interface Quote {
  collateralAmount: string;
  loanAmount: string;
  protocol: string;
  chain: ChainType;
  /** Chain on which the loan is issued. */
  loanChain?: ChainType;
  /** Source chain of the bridged collateral. */
  sourceChain?: ChainType;
  /** Bridge-destination asset symbol (e.g. "WBTC", "cbBTC", "BTCB"). Required when building `QuoteFeesRequestData`. */
  collateralAssetSymbol?: string;
  /** Loan asset symbol (e.g. "USDC"). Required when building `QuoteFeesRequestData`. */
  loanAssetSymbol?: string;
  borrowApy: {
    variable: string;
    stable: string;
  };
  effectiveApy?: {
    variable: string;
    stable: string;
  };
}

LoanCollateralInfo

Collateral information for a loan.
interface LoanCollateralInfo {
  totalCollateral: string;
  availableCollateral: string;
  maxWithdrawable: string;
  totalDebt: string;
  remainingDebt: string;
}

Webhooks

SdkWebhookEventType

enum SdkWebhookEventType {
  BTC_DEPOSIT_CONFIRMED = 'sdk.borrow.btc_deposit_confirmed'
}

SdkWebhookConfig

interface SdkWebhookConfig {
  enabled: boolean;
  url?: string;
  events: SdkWebhookEventType[];
  createdAt?: string | Date;
  updatedAt?: string | Date;
  secretLastRotatedAt?: string | Date;
}

SdkWebhookConfigUpdateRequest

interface SdkWebhookConfigUpdateRequest {
  enabled?: boolean;
  url?: string;
  events?: SdkWebhookEventType[];
}

SdkWebhookSecretResponse

interface SdkWebhookSecretResponse {
  config: SdkWebhookConfig;
  secret: string;
}

SdkBtcDepositConfirmedWebhookPayload

interface SdkBtcDepositConfirmedWebhookPayload {
  id: string;
  type: SdkWebhookEventType.BTC_DEPOSIT_CONFIRMED;
  apiVersion: string;
  createdAt: string;
  data: {
    transactionId: string;
    workflowId?: string;
    status: 'DEPOSIT_CONFIRMED';
    btcDepositTxHash?: string | null;
    bridgeRedeemTxHash?: string | null;
    depositAddress?: string | null;
  };
}

Transactions

UserTransaction

User transaction record.
interface UserTransaction {
  id: string;
  type: 'borrow' | 'repay' | 'withdraw';
  status: 'pending' | 'active' | 'completed' | 'failed' | 'awaiting_deposit';
  amount: string;
  borrowPrincipalAmount?: string;
  borrowerPayoutAmount?: string;
  platformFeeAmount?: string;
  feeSnapshot?: BorrowFeeSnapshot;
  settlementLegs?: BorrowSettlementLeg[];
  currency: string;
  txHash?: string;
  timestamp: number;
  borrowTransaction?: any;
  repayTransaction?: any;
}

BorrowSettlementLegStatus

Status of a borrow settlement leg.
type BorrowSettlementLegStatus = 'pending' | 'completed' | 'failed';

BorrowFeeDistributionStatus

High-level outcome of fee distribution.
type BorrowFeeDistributionStatus = 'pending' | 'completed' | 'failed';

BorrowFeeSettlementMode

How the borrow fee is settled to treasury.
type BorrowFeeSettlementMode = 'directToBaseTreasury';

BorrowFeeBridgeSource

Which user-owned wallet funded the fee settlement.
type BorrowFeeBridgeSource = 'evmLoanWallet' | 'solanaLoanWallet';

BorrowFeeBridgeStatus

Progress of the fee settlement transfer or bridge.
type BorrowFeeBridgeStatus = 'pending' | 'submitted' | 'settled' | 'failed';

BorrowFeePayoutStatus

Progress of the treasury payout to the referrer.
type BorrowFeePayoutStatus = 'pending' | 'submitted' | 'completed' | 'failed';

BorrowFeeBridgeStatusContext

Persisted context used to resume LI.FI bridge status checks.
interface BorrowFeeBridgeStatusContext {
  txHash: string;
  bridge?: string;
  fromChain: number;
  toChain: number;
  fallbackRawAmount: string;
}

BorrowSettlementLeg

Settlement leg recorded on a borrow transaction.
interface BorrowSettlementLeg {
  kind: 'feeDebit' | string;
  address: string;
  asset: string;
  chain: ChainType | string;
  amount: string;
  txHash?: string;
  status: BorrowSettlementLegStatus;
}

BorrowFeeSnapshot

Snapshot of borrow fee collection, settlement, and referral payout.
interface BorrowFeeSnapshot {
  borrowPrincipalAmount: string;
  borrowerPayoutAmount: string;
  disbursementFeeBps: number;
  disbursementFeeAmount: string;
  platformFeeAmount: string;
  referralFeeAmount: string;
  referrerFeePercentAtOrigination?: number;
  feeAsset: string;
  feeTokenAddress: string;
  feeChain: ChainType | string;
  feeTreasuryAddress: string;
  referrerPayoutAddress?: string;
  settlementMode?: BorrowFeeSettlementMode;
  bridgeSource?: BorrowFeeBridgeSource;
  bridgeProvider?: string;
  bridgeStatus?: BorrowFeeBridgeStatus;
  bridgeFeeUsd?: string;
  settlementAmount?: string;
  platformPayoutAmount?: string;
  referralPayoutAmount?: string;
  feeBridgeTxHash?: string;
  feeBridgeDestinationTxHash?: string;
  referralPayoutTxHash?: string;
  payoutStatus?: BorrowFeePayoutStatus;
  distributionStatus?: BorrowFeeDistributionStatus;
  distributionError?: string;
  bridgeStatusContext?: BorrowFeeBridgeStatusContext;
}

PaginatedResponse

Paginated response wrapper.
interface PaginatedResponse<T> {
  transactions: T[];
  pagination: {
    totalTransactions: number;
    currentPage: number;
    limit: number;
    totalPages: number;
    hasNext: boolean;
    hasPrevious: boolean;
  };
}

RepayTransaction

Repayment transaction details.
interface RepayTransaction {
  _id: string;
  userId: string;
  originalBorrowId: string;
  loanChainAddress: string;
  repayAmount: string;
  withdrawalCollateralAmount: string;
  repayTokenAddress: string;
  isPartialRepay: boolean;
  isPartialWithdrawCollateral: boolean;
  useCollateral: boolean;
  workflowId?: string;
  transactionStatuses: Array<{
    status: string;
    timestamp: Date;
    details?: string;
  }>;
  repayConfig: any;
  userBtcWithdrawAddress?: string;
  bridgeConfig?: any;
  workflowState?: RepayWorkflowState;
  createdAt: Date;
  updatedAt: Date;
}

RepayTransactionStatusResponse

Status response for repay transactions.
interface RepayTransactionStatusResponse {
  transactionDetails: RepayTransaction;
  transactionState?: RepayWorkflowState;
}

Workflow

WorkflowStatus

Current workflow status.
interface WorkflowStatus {
  stage: string;
  step: number;
  label: string;
  description: string;
  depositAddress?: string;
  depositAmount?: number;
  error?: string;
  isComplete: boolean;
  isFailed: boolean;
  rawData: any;
}

WorkflowCallbacks

Callbacks for workflow tracking.
interface WorkflowCallbacks {
  onStatusUpdate?: (status: WorkflowStatus) => void;
  onComplete?: (result: any) => void;
  onError?: (error: string) => void;
  onDepositReady?: (info: DepositInfo) => void;
}

DepositInfo

Deposit information.
interface DepositInfo {
  address: string;
  amount: number;
  amountBTC: number;
}

RepayWorkflowStage

Repay workflow stages.
enum RepayWorkflowStage {
  INITIALIZING = 'INITIALIZING',
  TRANSFERRING_TO_KERNEL = 'TRANSFERRING_TO_KERNEL',
  WITHDRAWING_COLLATERAL = 'WITHDRAWING_COLLATERAL',
  REPAYING_LOAN = 'REPAYING_LOAN',
  TRANSFERRING_TO_PLATFORM_WALLET = 'TRANSFERRING_TO_PLATFORM_WALLET',
  BRIDGE_INITIALIZING = 'BRIDGE_INITIALIZING',
  BRIDGE_QUOTE_READY = 'BRIDGE_QUOTE_READY',
  BRIDGE_SWAP_CREATED = 'BRIDGE_SWAP_CREATED',
  BRIDGE_EXECUTING_APPROVAL = 'BRIDGE_EXECUTING_APPROVAL',
  BRIDGE_APPROVAL_CONFIRMED = 'BRIDGE_APPROVAL_CONFIRMED',
  BRIDGE_EXECUTING_INITIATE = 'BRIDGE_EXECUTING_INITIATE',
  BRIDGE_INITIATE_CONFIRMED = 'BRIDGE_INITIATE_CONFIRMED',
  BRIDGE_AWAITING_BRIDGE_COMPLETION = 'BRIDGE_AWAITING_BRIDGE_COMPLETION',
  BRIDGE_COMPLETED = 'BRIDGE_COMPLETED',
  COMPLETED = 'COMPLETED',
  FAILED = 'FAILED',
  CANCELLED = 'CANCELLED'
}

RepayWorkflowStep

Repay workflow steps.
enum RepayWorkflowStep {
  TRANSFER_TO_KERNEL = 'transferToKernel',
  REPAY = 'repay',
  WITHDRAW = 'withdraw',
  REPAY_AND_WITHDRAW = 'repayAndWithdraw',
  TRANSFER_TO_PLATFORM_WALLET = 'transferToPlatformWallet',
  BRIDGE_COLLATERAL_TO_BITCOIN = 'bridgeCollateralToBitcoin'
}

RepayWorkflowState

Repay workflow state.
interface RepayWorkflowState {
  stage: RepayWorkflowStage;
  currentStep?: RepayWorkflowStep;
  error?: string;
  transferToKernelTx?: string[];
  withdrawCollateralTx?: string[];
  transferToPlatformWalletTx?: string[];
  repayTx?: string[];
  transferAndBridgeCollateralAmount?: string;
  bridgeTx?: string[];
  bridgeQuote?: any;
  bridgeSwap?: any;
  bridgeApprovalTxHash?: string;
  bridgeInitiateTxHash?: string;
  bridgeRedeemTxHash?: string;
}

Wallet & Portfolio

WalletPosition

Token position in wallet.
interface WalletPosition {
  id: string;
  type: string;
  attributes: {
    parent: string | null;
    protocol: string | null;
    name: string;
    position_type: string;
    quantity: {
      int: string;
      decimals: number;
      float: number;
      numeric: string;
    };
    value: number | null;
    price: number;
    changes: {
      absolute_1d: number | null;
      percent_1d: number | null;
    } | null;
    fungible_info: {
      name: string;
      symbol: string;
      icon: { url: string } | null;
      flags: { verified: boolean };
      implementations: Array<{
        chain_id: string;
        address: string;
        decimals: number;
      }>;
    } | null;
    flags: {
      displayable: boolean;
      is_trash: boolean;
    };
    updated_at: string;
    updated_at_block: number;
  };
  relationships: {
    chain: { data: { type: string; id: string } };
  };
}

WalletPositionsResponse

Response for wallet positions.
interface WalletPositionsResponse {
  data: WalletPosition[];
  links?: { self: string };
}

WalletPortfolio

Portfolio summary.
interface WalletPortfolio {
  id: string;
  type: string;
  attributes: {
    positions_distribution_by_type: Record<string, number>;
    positions_distribution_by_chain: Record<string, number>;
    total: { positions: number };
    changes: {
      absolute_1d: number;
      percent_1d: number;
    };
  };
}

WalletPortfolioResponse

Response for wallet portfolio.
interface WalletPortfolioResponse {
  data: WalletPortfolio;
  links?: { self: string };
}

Fees & Withdrawals

FeesRequest

Fee information request.
interface FeesRequest {
  chain: ChainType;
  collateralAmount: string;
}

FeesResponseData

Fee information response.
interface FeesResponseData {
  chain: ChainType;
  collateralAmount: string;
  gardenFeePercent: number;
  affiliateFeePercent: number;
  totalBridgeFeePercentage: number;
  totalBridgeFeeUSD: string;
  gardenFeeUSD: string;
  affiliateFeeUSD: string;
  estimatedGasFee: string;
}

QuoteFeesRequestData

Request body for BorrowSDK.getQuoteFees().
interface QuoteFeesRequestData {
  /** Human-readable BTC amount, for example "0.1". */
  collateralAmount: string;
  /** Loan amount in the loan asset's units, e.g. "5000" USDC. */
  loanAmount: string;
  fromChain: ChainType;
  /** Source asset symbol, e.g. "BTC". */
  fromAssetSymbol: string;
  toChain: ChainType;
  /** Bridge destination asset, e.g. "WBTC", "cbBTC". */
  toAssetSymbol: string;
  loanChain: ChainType;
  /** Loan asset symbol, e.g. "USDC". */
  loanAssetSymbol: string;
}

BorrowQuoteFeesData

Borrow-side fee breakdown for the requested loan. feeSource is 'campaign' when a discount applies, otherwise 'default'.
interface BorrowQuoteFeesData {
  defaultDisbursementFeeBps: number;
  appliedDisbursementFeeBps: number;
  platformFee: string;
  netLoanAmount: string;
  waivedPlatformFee: string;
  feeSource: 'default' | 'campaign';
  campaignSlug?: string;
}

QuoteFeesResponseData

Full fee response returned by BorrowSDK.getQuoteFees(). Combines bridge fees with the borrow-side fee breakdown.
interface QuoteFeesResponseData {
  bridgeFees: FeesResponseData;
  borrowFees: BorrowQuoteFeesData;
}

WithdrawToBitcoinRequest

Cross-chain withdrawal request to Bitcoin.
interface WithdrawToBitcoinRequest {
  chain: ChainType;
  amount: string;
  assetSymbol: string;
  btcAddress: string;
}

WithdrawToEVMRequest

Gasless EVM withdrawal request (sponsored gas).
interface WithdrawToEVMRequest {
  chain: ChainType;
  amount: string;
  destinationAddress: string;
  /** Optional wallet index. Defaults to 0 (platform wallet where borrowed USDC goes). */
  loanIndex?: number;
}

WithdrawToEVMResponse

Response from EVM withdrawal.
interface WithdrawToEVMResponse {
  success: boolean;
  data: {
    transactionId: string;
    transactionHash: string;
    status: string;
    sourceAddress: string;
    destinationAddress: string;
    amount: string;
    chain: ChainType;
  };
}

WithdrawStatusResponse

Withdrawal status response.
interface WithdrawStatusResponse {
  success: boolean;
  data: WithdrawTransaction;
  transactionState?: {
    stage: string;
    redeemTxHash?: string;
    error?: string;
  };
}

Utility Types

Units

Type-safe Bitcoin unit conversion utilities with branded types.
// Branded types for type safety
type Satoshis = number & { readonly __brand: 'satoshis' };
type BTC = string & { readonly __brand: 'btc' };

const Units = {
  // Conversions
  satsToBtc: (sats: number) => BTC;
  btcToSats: (btc: string) => Satoshis;

  // Formatting
  formatBtc: (btc: BTC | string, decimals?: number) => string;
  formatSats: (sats: Satoshis | number) => string;

  // Type constructors
  asBtc: (value: string) => BTC;
  asSatoshis: (value: number) => Satoshis;

  // Smart normalization (handles both sats and BTC inputs)
  normalizeToBtc: (value: string | number) => BTC;
  normalizeToSats: (value: string | number) => Satoshis;

  // Detection
  isLikelySatoshis: (value: number) => boolean;
};

Example

import { Units, type Satoshis, type BTC } from '@satsterminal-sdk/borrow';

// Basic conversions
Units.satsToBtc(10000000);           // "0.10000000" (typed as BTC)
Units.btcToSats("0.1");              // 10000000 (typed as Satoshis)

// Smart normalization (auto-detects units)
Units.normalizeToBtc(10000000);      // "0.10000000" (detected as sats)
Units.normalizeToBtc("0.1");         // "0.10000000" (detected as BTC)

// Formatting for display
Units.formatBtc("0.12345678", 4);    // "0.1235"
Units.formatSats(1234567);           // "1,234,567"

// Type-safe branded values
const sats: Satoshis = Units.asSatoshis(10000000);
const btc: BTC = Units.asBtc("0.1");

ResponseNormalizer

Utilities for handling various API response formats.
const ResponseNormalizer = {
  // Normalize quote responses from various formats
  normalizeQuotes: (response: any) => Quote[];

  // Normalize repay transaction responses
  normalizeRepayTransactions: (response: any) => RepayTransaction[];

  // Extract loan collateral info from response
  extractLoanCollateralInfo: (response: any) => LoanCollateralInfo | null;

  // Normalize borrow transaction to canonical format
  normalizeBorrowTransaction: (raw: any) => NormalizedTransaction | null;
};

Example

import { ResponseNormalizer } from '@satsterminal-sdk/borrow';

// Handle various quote response formats
const quotes = ResponseNormalizer.normalizeQuotes(apiResponse);
// Works with: data[], { allQuotes: [] }, { data: { allQuotes: [] } }, etc.

// Extract collateral info regardless of response structure
const collateralInfo = ResponseNormalizer.extractLoanCollateralInfo(loanData);

BtcUtils (Deprecated)

Legacy Bitcoin utility class. Use Units instead for type-safe conversions.
/** @deprecated Use Units instead */
class BtcUtils {
  static satsToBtc(sats: number): string;
  static btcToSats(btc: string): number;
  /** @deprecated Use Units.normalizeToBtc() instead */
  static formatBtcDisplay(amount: string | number): string;
}

Migration

// Before (deprecated)
import { BtcUtils } from '@satsterminal-sdk/borrow';
BtcUtils.satsToBtc(10000000);
BtcUtils.formatBtcDisplay(amount);

// After (recommended)
import { Units } from '@satsterminal-sdk/borrow';
Units.satsToBtc(10000000);
Units.normalizeToBtc(amount);