Auto-generated API documentation for @stellar-split/sdk. Total exports: 156
- addRequestInterceptor
- addResponseInterceptor
- applyFilter
- BatcherConfig
- BatchPayment
- builtInNotificationTemplates
- calculateFee
- checkRPCHealth
- CircuitBreakerMonitor
- CircuitBreakerStatus
- clearFeatureCache
- CloneOverrides
- CompiledFilter
- compileFilter
- ComplianceReport
- CompressedPayload
- CompressionAlgorithm
- CompressionConfig
- CompressionPayload
- compressPayload
- connectWallet
- ContractFeatures
- createCompressionRequestInterceptor
- createCompressionResponseInterceptor
- CreateInvoiceParams
- createRequestSigningInterceptor
- DeadlineEngine
- deadlineFromDays
- DeadlinePassedError
- decompressPayload
- Deduplicator
- defaultCircuitBreakerMonitor
- detectContractFeatures
- DIContainer
- diffInvoice
- diffSimulations
- EndpointState
- EnrichedInvoice
- enrichInvoice
- ExpiryCallback
- ExpiryEvent
- ExportPipeline
- FallbackChain
- FallbackExhaustedError
- FeeBreakdown
- FilterCriteria
- FilterIndex
- formatAmount
- generateFlowDiagram
- generateGraphQLSchema
- generateMerkleProof
- getInvoiceAtTime
- getOptimisticInvoice
- getPublicKey
- getSDKHealth
- groupInvoicesByPattern
- HistoricalInvoice
- ICacheStore
- initPoller
- InvalidTransitionError
- Invoice
- InvoiceCluster
- InvoiceDiff
- InvoiceEvent
- InvoiceEventCallbacks
- InvoiceEventType
- InvoiceExt
- InvoiceFlowFetcher
- InvoiceFrozenError
- InvoiceNotFoundError
- InvoiceNotPendingError
- InvoiceReceipt
- InvoiceStatus
- InvoiceTemplate
- IRPCClient
- isExpired
- isValidAddress
- IWalletAdapter
- LoadBalancer
- LoadBalancerOptions
- MerkleProof
- MultiplexedClient
- MultiTenantClient
- negotiateVersion
- NetworkConfig
- NotificationCenter
- OverflowBehavior
- PaginatedResult
- PaginationOptions
- parseAmount
- parseSorobanError
- Payment
- PaymentAggregator
- PaymentExceedsRemainingError
- PaymentLedger
- PaymentProof
- PaymentSnapshot
- PaymentSnapshotPayer
- PaymentSnapshotPayment
- PaymentSummary
- PaymentValidation
- PayParams
- PipelineSink
- PipelineStage
- pollUSDCBalance
- ProfileReport
- ProfilerSession
- Recipient
- registerInvoiceFetcher
- registerInvoiceFlowFetcher
- registerWebhook
- renderTemplate
- replayEvents
- RequestBatcher
- RequestInterceptor
- resetSDKHealth
- resolveToken
- ResourceDelta
- ResponseInterceptor
- RPCRequest
- RPCResponse
- ScheduledPayment
- ScheduledPaymentManager
- SDK_CONTRACT_VERSION
- SDKHealth
- signTransaction
- SimpleCache
- SimulateCreateInvoiceResult
- SimulatePayResult
- SimulationDiff
- SimulationDiffNotComparable
- SimulationDiffSuccess
- StellarSplitClient
- StellarSplitClientConfig
- StellarSplitError
- StellarSplitTxBuilder
- telemetry
- TelemetryCollector
- TelemetryReport
- TokenInfo
- TopPayer
- triggerWebhook
- truncateAddress
- TxQueue
- TxResult
- validateTransition
- validateWebhookSignature
- verifyMerkleProof
- VersionInfo
- WalletAdapter
- WalletConnectAdapter
- watchContractUpgrade
- watchExpiry
- WebhookConfig
- WebhookEvent
- WeightedEndpoint
Kind: function
export function addRequestInterceptor(fn: RequestInterceptor): void {
requestInterceptors.push(fn);
}Kind: function
export function addResponseInterceptor(fn: ResponseInterceptor): void {
responseInterceptors.push(fn);
}Kind: function
export function applyFilter(invoices: Invoice[], filter: CompiledFilter): Invoice[] {
return invoices.filter(filter.predicate);
}Kind: interface
Configuration for the request batcher. /
export interface BatcherConfig {
/** Time window in milliseconds to collect requests before batching */
windowMs: number;
/** Maximum number of requests to include in a single batch */
maxBatchSize: number; ...Kind: interface
export interface BatchPayment {
/** Invoice ID to pay toward. */
invoiceId: string;
/** Amount to pay in stroops. */
amount: bigint; ...Kind: const
builtInNotificationTemplates: Record<InvoiceEventType, string> = {
created: "Invoice {{invoiceId}} was created by {{creator}} for {{amount}}.",
payment: "Payment of {{amount}} received for invoice {{invoiceId}}.",
released: "Invoice {{invoiceId}} has been released to recipients.",
refunded: "Invoice {{invoiceId}} has been refunded by {{creator}}.", ...Kind: function
Calculate the protocol fee for a given amount. Fetches the current fee basis points from the contract and computes the fee and net amounts.
export async function calculateFee(
amount: bigint,
config: StellarSplitClientConfig
): Promise<FeeBreakdown> {
const rpcUrl = Array.isArray(config.rpcUrl) ? config.rpcUrl[0]! : config.rpcUrl; ...| Name | Description |
|---|---|
amount |
Gross amount in stroops |
config |
Client configuration |
Fee breakdown with gross, fee, net, and feeBps /
Kind: function
Check the health of the configured RPC endpoint.
export async function checkRPCHealth(server: SorobanRpc.Server): Promise<RPCHealth> {
const startTime = Date.now();
try {
const ledger = await server.getLatestLedger(); ...| Name | Description |
|---|---|
server |
Soroban RPC server instance |
Health status with latency and block height /
Kind: class
export class CircuitBreakerMonitor extends EventEmitter {
private _breakers = new Map<string, BreakerEntry>();
constructor() {
super(); ...Kind: interface
export interface CircuitBreakerStatus {
endpoint: string;
state: CircuitState;
failureCount: number;
lastFailure: number | null; ...Kind: function
export function clearFeatureCache(): void {
_cached = null;
}Kind: interface
export interface CloneOverrides {
newDeadline?: number;
newAmounts?: bigint[];
newRecipients?: string[];
newOverflowBehavior?: OverflowBehavior; ...Kind: interface
export interface CompiledFilter {
predicate: (invoice: Invoice) => boolean;
criteria: FilterCriteria;
}Kind: function
export function compileFilter(criteria: FilterCriteria): CompiledFilter {
return { predicate: buildPredicate(criteria), criteria };
}Kind: interface
export interface ComplianceReport {
passed: boolean;
violations: string[];
}Kind: interface
export interface CompressedPayload {
compressed: true;
algorithm: CompressionAlgorithm;
body: Uint8Array;
originalBytes: number; ...Kind: type
export type CompressionAlgorithm = "gzip" | "deflate";Kind: interface
export interface CompressionConfig {
enabled: boolean;
algorithm: CompressionAlgorithm;
}Kind: type
export type CompressionPayload = string | Uint8Array;Kind: function
export async function compressPayload(
payload: CompressionPayload,
algorithm: CompressionAlgorithm = "gzip"
): Promise<CompressedPayload> {
const bytes = toBytes(payload); ...Kind: function
export async function connectWallet(): Promise<string> {
const { isConnected: connected } = await isConnected();
if (!connected) {
throw new Error(
"Freighter wallet is not installed. Please install it from https://freighter.app" ...Kind: interface
Feature detection result indicating which contract features are available. Each field is true if the deployed contract supports the corresponding method. /
export interface ContractFeatures {
batchPay: boolean;
cloneInvoice: boolean;
invoiceGroups: boolean;
templates: boolean; ...Kind: function
export function createCompressionRequestInterceptor(config: CompressionConfig): RequestInterceptor {
return async (req) => {
if (!config.enabled) {
return req;
} ...Kind: function
export function createCompressionResponseInterceptor(_config: CompressionConfig): ResponseInterceptor {
return async (res) => {
if (!isCompressedPayload(res.result)) {
return res;
} ...Kind: interface
export interface CreateInvoiceParams {
/** Stellar address of the creator (must sign). */
creator: string;
/** Recipients and their owed amounts. */
recipients: Recipient[]; ...Kind: function
export function createRequestSigningInterceptor(keypair: Keypair): RequestInterceptor {
return async (req: RPCRequest): Promise<RPCRequest> => {
const timestamp = Date.now();
const message = `stellar-split:${timestamp}`;
// Keypair.sign accepts Uint8Array / Buffer ...Kind: class
export class DeadlineEngine {
private interval: TimeoutLike | null = null;
private readonly intervalMs: number;
private destroyed = false; ...Kind: function
Return a Unix timestamp (seconds) for a date that is days from now.
/
export function deadlineFromDays(days: number): number {
return Math.floor(Date.now() / 1000) + days * 86_400;
}Kind: class
export class DeadlinePassedError extends StellarSplitError {
readonly invoiceId: string;
constructor(invoiceId: string, raw?: string) {
super(`Invoice deadline has passed: ${invoiceId}`, raw); ...Kind: function
export async function decompressPayload(payload: CompressedPayload): Promise<Uint8Array> {
return isDecompressionStreamAvailable()
? await decompressInBrowser(payload.body, payload.algorithm)
: await decompressInNode(payload.body, payload.algorithm);
}Kind: class
export class Deduplicator<T> {
private _inflight = new Map<string, Promise<T>>();
private _hits = 0;
private _misses = 0;
...Kind: const
defaultCircuitBreakerMonitor = new CircuitBreakerMonitor()Kind: function
Detect which optional features the deployed Soroban contract supports.
The result is cached for 5 minutes. Call clearFeatureCache() to reset.
export async function detectContractFeatures(
config: StellarSplitClientConfig,
source?: string,
): Promise<ContractFeatures> {
// Return cached result if still valid ...| Name | Description |
|---|---|
config |
StellarSplit client configuration (must include rpcUrl, contractId, networkPassphrase). |
source |
A valid Stellar public key (G...) to use as the simulation source. Defaults to a well-known testnet address if omitted. |
A ContractFeatures object with booleans for each optional feature. /
Kind: class
export class DIContainer {
private rpcClient?: IRPCClient;
private cacheStore?: ICacheStore<Invoice>;
private walletAdapter?: IWalletAdapter;
...Kind: function
export function diffInvoice(oldInvoice: Invoice, newInvoice: Invoice): InvoiceDiff {
const changed: InvoiceDiff["changed"] = [];
for (const key of INVOICE_KEYS) {
const oldVal = oldInvoice[key]; ...Kind: function
Diff two SimulateTransactionResponse objects.
If either response is an error or a restore response, returns
{ comparable: false } instead of throwing.
/
export function diffSimulations(
before: SorobanRpc.Api.SimulateTransactionResponse,
after: SorobanRpc.Api.SimulateTransactionResponse,
): SimulationDiff {
if (SorobanRpc.Api.isSimulationError(before)) { ...Kind: interface
export interface EndpointState {
url: string;
healthy: boolean;
averageLatencyMs: number | null;
consecutiveFailures: number; ...Kind: interface
export interface EnrichedInvoice extends Invoice {
metadata: Record<string, unknown> | null;
}Kind: function
export async function enrichInvoice(
invoiceId: string,
getInvoice?: InvoiceFetcher
): Promise<EnrichedInvoice> {
const fetcher = getInvoice ?? invoiceFetcher; ...Kind: type
export type ExpiryCallback = (event: ExpiryEvent) => void;Kind: interface
export interface ExpiryEvent {
/** Invoice ID. */
invoiceId: string;
/** Unix timestamp deadline (seconds). */
deadline: number; ...Kind: class
export class ExportPipeline {
private filters: Array<PipelineStage<Invoice[]>> = [];
private transforms: Array<PipelineStage<Invoice[]>> = [];
private formatters: Array<PipelineStage<Invoice[]>> = [];
private sinks: PipelineSink[] = []; ...Kind: class
export class FallbackChain {
private readonly urls: string[];
private readonly logger: FallbackFailureLogger;
constructor(urls: string[], options?: { logger?: FallbackFailureLogger }) { ...Kind: class
export class FallbackExhaustedError extends Error {
public readonly attempts: FallbackAttemptLog[];
constructor(attempts: FallbackAttemptLog[]) {
super(`Fallback chain exhausted after ${attempts.length} attempts.`); ...Kind: interface
export interface FeeBreakdown {
/** Gross amount before fee deduction. */
gross: bigint;
/** Protocol fee amount. */
fee: bigint; ...Kind: interface
export interface FilterCriteria {
and?: FilterCriteria[];
or?: FilterCriteria[];
status?: InvoiceStatus;
creator?: string; ...Kind: class
export class FilterIndex {
private statusIndex = new Map<string, Set<Invoice>>();
private creatorIndex = new Map<string, Set<Invoice>>();
private tokenIndex = new Map<string, Set<Invoice>>();
private invoicesRef: Invoice[] | null = null; ...Kind: function
Format a stroop amount as a human-readable USDC string.
export function formatAmount(stroops: bigint): string {
const whole = stroops / STROOPS_PER_UNIT;
const frac = stroops % STROOPS_PER_UNIT;
return `${whole}.${frac.toString().padStart(7, "0")}`;
}formatAmount(10_000_000n) // "1.0000000"
/Kind: function
export async function generateFlowDiagram(
invoiceId: string,
getInvoice?: InvoiceFlowFetcher
): Promise<string> {
const fetcher = getInvoice ?? invoiceFlowFetcher; ...Kind: function
generateGraphQLSchema — builds a GraphQL SDL string from SDK TypeScript interfaces. Type mapping: bigint → String (GraphQL has no native 64-bit int) string → String number → Int boolean → Boolean /
export function generateGraphQLSchema(): string {
return `
type Recipient {
address: String!
amount: String! ...Kind: function
Generate a Merkle proof for a specific payment within an invoice.
export async function generateMerkleProof(
invoiceId: string,
paymentIndex: number
): Promise<MerkleProof> {
// In a real implementation, this would: ...| Name | Description |
|---|---|
invoiceId |
The invoice ID |
paymentIndex |
The index of the payment in the invoice's payments array |
A Merkle proof object /
Kind: function
export async function getInvoiceAtTime(
server: SorobanRpc.Server,
contractId: string,
invoiceId: string,
timestamp: number ...Kind: function
Get an optimistically updated invoice reflecting a pending payment. Returns a new invoice object with the payment applied immediately, without waiting for on-chain confirmation. Does not mutate the input.
export function getOptimisticInvoice(invoice: Invoice, payment: Payment): Invoice {
const newFunded = invoice.funded + payment.amount;
const newPayments = [...invoice.payments, payment];
const newStatus =
newFunded >= invoice.recipients.reduce((sum, r) => sum + r.amount, 0n) ...| Name | Description |
|---|---|
invoice |
The current invoice state |
payment |
The pending payment to apply |
A new invoice with the payment applied /
Kind: function
export async function getPublicKey(): Promise<string> {
const { isConnected: connected } = await isConnected();
if (!connected) {
throw new Error("Freighter wallet is not connected.");
} ...Kind: function
export async function getSDKHealth(): Promise<SDKHealth> {
const latencyStart = Date.now();
let rpcLatency = 0;
if (serverRef) { ...Kind: function
export function groupInvoicesByPattern(invoices: Invoice[]): InvoiceCluster[] {
if (invoices.length === 0) {
return [];
}
...Kind: interface
export interface HistoricalInvoice {
reconstructedAt: number;
}Kind: interface
export interface ICacheStore<T> {
get(key: string): T | undefined;
set(key: string, value: T): void;
invalidate(key: string): void;
clear(): void; ...Kind: function
Initialize the poller with RPC configuration. Must be called before using pollUSDCBalance. /
export function initPoller(rpcUrl: string, networkPassphrase: string): void {
pollerServer = new SorobanRpc.Server(rpcUrl, {
allowHttp: rpcUrl.startsWith("http://"),
});
}Kind: class
export class InvalidTransitionError extends Error {
constructor(from: InvoiceStatus, to: InvoiceStatus) {
super(`Invalid transition from "${from}" to "${to}"`);
this.name = "InvalidTransitionError";
} ...Kind: interface
export interface Invoice {
/** Invoice ID (u64 from the contract). */
id: string;
/** Address that created the invoice. */
creator: string; ...Kind: interface
export interface InvoiceCluster {
label: string;
invoices: Invoice[];
similarity: number;
}Kind: interface
export interface InvoiceDiff {
changed: Array<{
field: string;
from: unknown;
to: unknown; ...Kind: interface
export interface InvoiceEvent {
type: InvoiceEventType;
invoiceId: string;
amount?: bigint | number | string;
creator?: string; ...Kind: interface
export interface InvoiceEventCallbacks {
/** Fired when a payment event is detected. */
onPayment?: (payment: Payment) => void;
/** Fired when the invoice status changes to Released. */
onReleased?: () => void; ...Kind: type
export type InvoiceEventType = "created" | "payment" | "released" | "refunded" | "expiring";Kind: interface
export interface InvoiceExt {
parentInvoiceId: string | null;
cloneDepth: number;
}Kind: type
export type InvoiceFlowFetcher = (invoiceId: string) => Promise<Invoice>;Kind: class
export class InvoiceFrozenError extends StellarSplitError {
readonly invoiceId: string;
constructor(invoiceId: string, raw?: string) {
super(`Invoice is frozen: ${invoiceId}`, raw); ...Kind: class
export class InvoiceNotFoundError extends StellarSplitError {
readonly invoiceId: string;
constructor(invoiceId: string, raw?: string) {
super(`Invoice not found: ${invoiceId}`, raw ?? `Invoice not found: ${invoiceId}`); ...Kind: class
export class InvoiceNotPendingError extends StellarSplitError {
readonly invoiceId: string;
constructor(invoiceId: string, raw?: string) {
super(`Invoice is not in Pending state: ${invoiceId}`, raw); ...Kind: interface
export interface InvoiceReceipt {
/** Deterministic receipt identifier. */
receiptId: string;
/** Invoice ID this receipt belongs to. */
invoiceId: string; ...Kind: type
export type InvoiceStatus = "Pending" | "Released" | "Refunded" | "Cancelled";Kind: interface
export interface InvoiceTemplate {
/** Template name. */
name: string;
/** Recipients and their owed amounts. */
recipients: Recipient[]; ...Kind: interface
export interface IRPCClient extends SorobanRpc.Server {
getFeeStats(): Promise<SorobanRpc.Api.GetFeeStatsResponse>;
close?(): Promise<void> | void;
}Kind: function
Return true if a Unix timestamp deadline has passed. /
export function isExpired(deadline: number): boolean {
return Math.floor(Date.now() / 1000) > deadline;
}Kind: function
Validate a Stellar public key (G... address). Uses a simple regex; for full validation use stellar-sdk StrKey. /
export function isValidAddress(address: string): boolean {
return /^G[A-Z2-7]{54,55}$/.test(address);
}Kind: interface
export interface IWalletAdapter {
getAddress(): Promise<string>;
signTransaction(xdr: string, network: string): Promise<string>;
}Kind: class
export class LoadBalancer {
private readonly endpoints: MutableEndpointState[];
private readonly maxLatencySamples: number;
private readonly failureThreshold: number;
private readonly reprobeIntervalMs: number; ...Kind: interface
export interface LoadBalancerOptions {
maxLatencySamples?: number;
failureThreshold?: number;
reprobeIntervalMs?: number;
now?: () => number; ...Kind: interface
Merkle proof structure for invoice payment verification. /
export interface MerkleProof {
/** The leaf hash being proven (payment hash) */
leaf: string;
/** Sibling hashes along the path to the root */
path: string[]; ...Kind: class
MultiplexedClient distributes requests across multiple RPC endpoints using weighted round-robin load balancing based on endpoint health scores. /
export class MultiplexedClient {
private endpoints: WeightedEndpoint[];
private currentWeights: number[];
private healthScores: number[];
...Kind: class
export class MultiTenantClient {
private readonly clients = new Map<string, StellarSplitClient>();
private readonly clientFactory: (tenantId: string) => StellarSplitClientConfig;
constructor(clientFactory: (tenantId: string) => StellarSplitClientConfig) { ...Kind: function
Reads the contract's on-chain get_version() and compares it against
{@link SDK_CONTRACT_VERSION}.
compatible: true— major versions match.compatible: false— major versions differ (incompatible ABI).- Logs a warning when minor versions differ (compatible but potentially stale). /
export async function negotiateVersion(
config: StellarSplitClientConfig
): Promise<VersionInfo> {
const rpcUrl = Array.isArray(config.rpcUrl) ? config.rpcUrl[0]! : config.rpcUrl;
const server = new SorobanRpc.Server(rpcUrl, { ...Kind: interface
export interface NetworkConfig {
/** Soroban RPC endpoint URL. */
rpcUrl: string;
/** Stellar network passphrase. */
networkPassphrase: string; ...Kind: class
export class NotificationCenter extends EventEmitter {
private _watchers = new Map<string, NodeJS.Timeout>();
private _fetchInvoice: (invoiceId: string) => Promise<Invoice>;
constructor(fetchInvoice: (invoiceId: string) => Promise<Invoice>) { ...Kind: type
export type OverflowBehavior = "refund" | "rollback" | "escalate";Kind: interface
export interface PaginatedResult<T> {
items: T[];
nextCursor: string | null;
total: number;
}Kind: interface
export interface PaginationOptions {
/** Cursor (invoice ID) to start after. */
cursor?: string;
/** Maximum number of items to return. Defaults to 20. */
limit?: number; ...Kind: function
Parse a human-readable USDC string into stroops.
export function parseAmount(value: string): bigint {
const [whole = "0", frac = ""] = value.split(".");
const fracPadded = frac.padEnd(7, "0").slice(0, 7);
return BigInt(whole) * STROOPS_PER_UNIT + BigInt(fracPadded);
}parseAmount("1.5") // 15_000_000n
/Kind: function
Parse a raw Soroban error string and return the appropriate typed error.
export function parseSorobanError(raw: string, invoiceId: string = ""): StellarSplitError {
for (const { pattern, factory } of ERROR_PATTERNS) {
if (pattern.test(raw)) {
return factory(invoiceId, raw);
} ...| Name | Description |
|---|---|
raw |
The raw error message from the RPC. |
invoiceId |
The invoice ID involved in the operation, if known. |
A typed StellarSplitError subclass, or a generic StellarSplitError. /
Kind: interface
export interface Payment {
/** Stellar address of the payer. */
payer: string;
/** Amount paid in stroops (1 XLM = 10_000_000 stroops). */
amount: bigint; ...Kind: class
export class PaymentAggregator {
public totalFunded: bigint;
public percentFunded: number;
public readonly payerBreakdown: Map<string, bigint>;
public paymentCount: number; ...Kind: class
export class PaymentExceedsRemainingError extends StellarSplitError {
readonly invoiceId: string;
constructor(invoiceId: string, raw?: string) {
super(`Payment exceeds remaining balance for invoice: ${invoiceId}`, raw); ...Kind: type
export type PaymentLedger = Payment & { ledger: number };Kind: interface
export interface PaymentProof {
/** Transaction hash. */
txHash: string;
/** Payer's Stellar address. */
payer: string; ...Kind: interface
export interface PaymentSnapshot {
snapshotId: string;
capturedAt: number;
invoiceId: string;
invoiceTotal: string; ...Kind: interface
export interface PaymentSnapshotPayer {
address: string;
amount: string;
}Kind: interface
export interface PaymentSnapshotPayment {
payer: string;
amount: string;
ledger: number;
timestamp?: number; ...Kind: interface
export interface PaymentSummary {
totalFunded: bigint;
percentFunded: number;
payerBreakdown: Map<string, bigint>;
paymentCount: number; ...Kind: interface
export interface PaymentValidation {
valid: boolean;
errors: string[];
}Kind: interface
export interface PayParams {
/** Stellar address of the payer (must sign). */
payer: string;
/** Invoice ID to pay toward. */
invoiceId: string; ...Kind: type
A sink consumes the final formatted output string. /
export type PipelineSink = (output: string) => void | Promise<void>;Kind: type
A pipeline stage receives an invoice and may return a transformed value (sync or async). /
export type PipelineStage<T> = (input: T) => T | Promise<T>;Kind: function
Poll a wallet's USDC balance and invoke callback when it changes.
export function pollUSDCBalance(
address: string,
callback: (balance: bigint) => void,
intervalMs: number = 10000
): () => void { ...| Name | Description |
|---|---|
address |
Stellar address to monitor |
callback |
Function invoked with new balance when it changes |
intervalMs |
Poll interval in milliseconds (default: 10000) |
Cleanup function to stop polling /
Kind: interface
export interface ProfileReport {
sessions: ProfileSession[];
}Kind: class
export class ProfilerSession {
private sessions: ProfileSession[] = [];
private active = false;
private currentEntries: ProfileEntry[] = [];
private currentStartedAt = 0; ...Kind: interface
export interface Recipient {
/** Stellar address of the recipient. */
address: string;
/** Amount owed in stroops. */
amount: bigint; ...Kind: function
export function registerInvoiceFetcher(fetcher: InvoiceFetcher): void {
invoiceFetcher = fetcher;
}Kind: function
export function registerInvoiceFlowFetcher(fetcher: InvoiceFlowFetcher): void {
invoiceFlowFetcher = fetcher;
}Kind: function
export function registerWebhook(
invoiceId: string,
url: string,
events: WebhookEvent[],
): void { ...Kind: function
export function renderTemplate(event: InvoiceEvent, template?: string): string {
const source = template ?? builtInNotificationTemplates[event.type];
const values: Record<"invoiceId" | "amount" | "creator", string> = {
invoiceId: event.invoiceId,
amount: stringifyTemplateValue(event.amount), ...Kind: function
Replay historical contract events in a ledger range.
export async function replayEvents(
server: SorobanRpc.Server,
contractId: string,
fromLedger: number,
toLedger: number ...| Name | Description |
|---|---|
server |
Soroban RPC server |
contractId |
The contract ID to filter events |
fromLedger |
Starting ledger sequence |
toLedger |
Ending ledger sequence |
Array of contract events in chronological order /
Kind: class
RequestBatcher collects read requests within a configurable time window and submits them as a single batch RPC call. /
export class RequestBatcher {
private pendingRequests: Array<{
invoiceId: string;
resolve: (invoice: Invoice) => void;
reject: (error: Error) => void; ...Kind: type
export type RequestInterceptor = (req: RPCRequest) => RPCRequest | Promise<RPCRequest>;Kind: function
export function resetSDKHealth(): void {
totalCalls = 0;
errorCalls = 0;
startTime = Date.now();
}Kind: function
Resolve token metadata from a SAC contract address. Fetches symbol, name, and decimals from the contract and caches results.
export async function resolveToken(
address: string,
config: StellarSplitClientConfig
): Promise<TokenInfo> {
// Check cache first ...| Name | Description |
|---|---|
address |
Token contract address |
config |
Client configuration |
Token metadata /
Kind: interface
export interface ResourceDelta {
/** Difference in CPU instructions (after − before). */
cpuInstructions: bigint;
/** Difference in read-bytes (after − before). */
readBytes: bigint; ...Kind: type
export type ResponseInterceptor = (res: RPCResponse) => RPCResponse | Promise<RPCResponse>;Kind: interface
export interface RPCRequest {
method: string;
params: unknown[];
}Kind: interface
export interface RPCResponse {
method: string;
result: unknown;
durationMs: number;
}Kind: interface
export interface ScheduledPayment {
id: string;
invoiceId: string;
amount: bigint;
executeAt: number; ...Kind: class
export class ScheduledPaymentManager {
private _payments: ScheduledPayment[] = load();
private _timers = new Map<string, ReturnType<typeof setTimeout>>();
private _pay: PayFn;
...Kind: const
SDK_CONTRACT_VERSION = "1.0.0"Kind: interface
export interface SDKHealth {
rpcLatency: number;
cacheHitRate: number;
errorRate: number;
uptimeMs: number; ...Kind: function
Sign a Stellar transaction XDR string using Freighter.
export async function signTransaction(
xdr: string,
network: string
): Promise<string> {
const result = await freighterSignTransaction(xdr, { networkPassphrase: network }); ...| Name | Description |
|---|---|
xdr |
Base64-encoded transaction XDR. |
network |
Network passphrase (e.g. "Test SDF Network ; September 2015"). |
Signed transaction XDR. /
Kind: class
export class SimpleCache<T> {
private readonly store = new Map<string, CacheEntry<T>>();
private readonly ttlMs: number;
constructor(ttlMs: number) { ...Kind: interface
export interface SimulateCreateInvoiceResult {
/** The invoice ID that would be created. */
invoiceId: string;
/** Estimated fee in stroops. */
fee: string; ...Kind: interface
export interface SimulatePayResult {
/** Estimated fee in stroops. */
fee: string;
}Kind: type
export type SimulationDiff = SimulationDiffSuccess | SimulationDiffNotComparable;Kind: interface
export interface SimulationDiffNotComparable {
comparable: false;
reason: string;
}Kind: interface
export interface SimulationDiffSuccess {
comparable: true;
/** Difference in minResourceFee expressed in stroops (after − before). */
feeDelta: bigint;
/** Number of diagnostic events that appear only in `after`. */ ...Kind: class
export class StellarSplitClient {
private _mainServer!: SorobanRpc.Server;
private _standby: WarmStandby | null = null;
private _queue = new PriorityQueue();
private contract: Contract; ...Kind: interface
export interface StellarSplitClientConfig {
/** Soroban RPC endpoint URL. Pass an array to enable warm-standby failover. */
rpcUrl: string | string[];
/** Stellar network passphrase. */
networkPassphrase: string; ...Kind: class
export class StellarSplitError extends Error {
/** The raw error string from the Soroban RPC, if available. */
readonly raw: string;
constructor(message: string, raw: string = message) { ...Kind: class
export class StellarSplitTxBuilder {
private readonly server: SorobanRpc.Server;
private readonly contract: Contract;
private readonly config: StellarSplitClientConfig;
private readonly sourceAddress: string; ...Kind: const
telemetry = new Telemetry()Kind: class
export class TelemetryCollector {
private startTime = Date.now();
private methods = new Map<string, MethodMetrics>();
private readonly windowSize = 100;
...Kind: interface
export interface TelemetryReport {
period: number;
methods: Record<string, MethodLatencyReport>;
}Kind: interface
export interface TokenInfo {
/** Token contract address. */
address: string;
/** Token symbol (e.g., "USDC"). */
symbol: string; ...Kind: interface
export interface TopPayer {
address: string;
amount: bigint;
}Kind: function
export async function triggerWebhook(
invoiceId: string,
event: WebhookEvent,
data: unknown,
): Promise<void> { ...Kind: function
Truncate a Stellar address for display: "GABC...XYZ". /
export function truncateAddress(address: string, chars = 4): string {
if (address.length <= chars * 2 + 3) return address;
return `${address.slice(0, chars)}...${address.slice(-chars)}`;
}Kind: class
export class TxQueue {
private server: SorobanRpc.Server;
private networkPassphrase: string;
private sourceAddress: string;
private queue: Promise<TxResult> = Promise.resolve({ txHash: "" }); ...Kind: interface
export interface TxResult {
txHash: string;
}Kind: function
export function validateTransition(from: InvoiceStatus, to: InvoiceStatus): boolean {
const allowed = TRANSITIONS[from];
if (!allowed || !allowed.includes(to)) {
throw new InvalidTransitionError(from, to);
} ...Kind: function
export async function validateWebhookSignature(
payload: unknown,
signature: string,
secret: string
): Promise<boolean> { ...Kind: function
Verify a Merkle proof against a given root hash.
export function verifyMerkleProof(proof: MerkleProof): boolean {
// In a real implementation, this would:
// 1. Recompute the root hash from the leaf and path
// 2. Compare the computed root with the provided root
...| Name | Description |
|---|---|
proof |
The Merkle proof to verify |
true if the proof is valid, false otherwise /
Kind: interface
export interface VersionInfo {
contractVersion: string;
sdkVersion: string;
compatible: boolean;
}Kind: interface
export interface WalletAdapter {
/** Return the wallet's public key (G... address). */
getAddress(): Promise<string>;
/**
* Sign a transaction XDR string. ...Kind: class
WalletConnect adapter — routes signing through a WalletConnect session instead of the Freighter browser extension. /
export class WalletConnectAdapter implements WalletAdapter {
private readonly opts: WalletConnectAdapterOptions;
constructor(opts: WalletConnectAdapterOptions) {
this.opts = opts; ...Kind: function
Watch for contract WASM upgrades and invoke callback when detected. Polls the contract's WASM hash every 60 seconds. When a change is detected, invokes the callback with the upgrade event.
export function watchContractUpgrade(
server: SorobanRpc.Server,
contractId: string,
callback: (event: UpgradeEvent) => void
): () => void { ...| Name | Description |
|---|---|
server |
Soroban RPC server instance |
contractId |
The contract ID to watch |
callback |
Function to invoke when upgrade is detected |
Cleanup function that stops polling /
Kind: function
Watch an invoice for expiry and fire a callback when approaching deadline. Polls the invoice deadline and fires the callback when the deadline is within the warning window or has passed.
export function watchExpiry(
invoiceId: string,
client: StellarSplitClient,
callback: ExpiryCallback,
warningSeconds: number = 3600 ...| Name | Description |
|---|---|
invoiceId |
Invoice ID to watch |
client |
StellarSplitClient instance |
callback |
Function to call when expiry event occurs |
warningSeconds |
Seconds before deadline to trigger callback (default: 3600) |
Cleanup function to stop polling /
Kind: type
export type WebhookConfig = {
url: string;
events: WebhookEvent[];
};Kind: type
export type WebhookEvent = "payment" | "released" | "refunded";Kind: interface
Weighted endpoint configuration for load balancing. /
export interface WeightedEndpoint {
/** RPC endpoint URL */
url: string;
/** Weight for this endpoint (higher = more requests) */
weight: number; ...