diff --git a/docs/ADVANCED_USAGE.md b/docs/ADVANCED_USAGE.md new file mode 100644 index 00000000..aafdde42 --- /dev/null +++ b/docs/ADVANCED_USAGE.md @@ -0,0 +1,247 @@ +# SDK Advanced Usage Guide + +This guide builds on [SDK_TUTORIALS.md](./SDK_TUTORIALS.md) and covers the patterns, best practices and +optimizations used by production integrations of `@stellar-split/sdk`. + +## Table of Contents + +1. [Usage Patterns](#usage-patterns) +2. [Examples](#examples) +3. [Best Practices](#best-practices) +4. [Optimization Guide](#optimization-guide) +5. [Reference](#reference) + +--- + +## Usage Patterns + +### Resilient client configuration + +Pass an array of RPC URLs to enable warm-standby failover, and combine it with retry, rate limiting and caching: + +```typescript +import { StellarSplitClient } from "@stellar-split/sdk"; + +const client = new StellarSplitClient({ + rpcUrl: [ + "https://soroban-testnet.stellar.org", + "https://backup-rpc.example.com", + ], + networkPassphrase: "Test SDF Network ; September 2015", + contractId: "YOUR_DEPLOYED_CONTRACT_ID", + // Automatic retry with exponential backoff and jitter + retry: { maxAttempts: 4, baseDelayMs: 250, maxDelayMs: 5_000 }, + // Outbound rate limiting for transaction submission + rateLimit: { maxRequestsPerSecond: 10, windowMs: 1_000 }, + // In-memory read cache + cache: { enabled: true, ttlMs: 30_000 }, +}); +``` + +### Reacting to client events + +`StellarSplitClient` is a typed event emitter. Subscribe to circuit breaker, endpoint and wallet events to drive +monitoring or UI state. Circuit events fire when `advancedCircuitBreaker` is configured; endpoint events fire when +`rpcEndpoints` is configured. + +```typescript +client.on("circuit:open", () => console.warn("Circuit breaker opened")); +client.on("circuit:close", () => console.info("Circuit breaker closed")); +client.on("endpoint:demoted", ({ url, reason }) => console.warn(`RPC endpoint ${url} demoted: ${reason}`)); +client.on("wallet:disconnected", () => console.info("Wallet disconnected")); +``` + +### Extending the client with plugins + +Plugins receive lifecycle hooks and are torn down in reverse registration order on `shutdown()`: + +```typescript +import { StellarSplitClient, type StellarSplitPlugin } from "@stellar-split/sdk"; + +const auditPlugin: StellarSplitPlugin = { + name: "audit-log", + install(client) { + console.log("installed on", client.constructor.name); + }, + onDestroy() { + console.log("shutting down"); + }, +}; + +const client = new StellarSplitClient({ ...config, plugins: [auditPlugin] }); +``` + +See [`examples/plugin-and-interceptors.ts`](../examples/plugin-and-interceptors.ts) for a runnable version. + +--- + +## Examples + +### Simulate before you submit + +`pay()` accepts `simulate: true` to dry-run a payment without broadcasting it: + +```typescript +import { parseAmount } from "@stellar-split/sdk"; + +const simulation = await client.pay({ + payer: payerKey, + invoiceId, + amount: parseAmount("25"), + simulate: true, +}); + +if (simulation.success) { + console.log(`Estimated fee: ${simulation.fee} stroops`); + await client.pay({ payer: payerKey, invoiceId, amount: parseAmount("25") }); +} +``` + +### Preflight checks + +Verify invoice expiry and payer readiness in one call before paying: + +```typescript +const check = await client.preflightCheck({ invoiceId, payer: payerKey, amount: parseAmount("25") }); + +if (check.valid) { + await client.pay({ payer: payerKey, invoiceId, amount: parseAmount("25") }); +} +``` + +### Batch invoice creation + +Create up to five invoices in a single transaction: + +```typescript +const { invoiceIds, txHash } = await client.batchCreateInvoices([invoiceA, invoiceB, invoiceC]); +``` + +### Validating assets before use + +Validate asset codes, issuers, custom token contracts and amounts offline: + +```typescript +import { validateStellarAsset } from "@stellar-split/sdk"; + +const result = validateStellarAsset( + { code: "USDC", issuer: "GA5Z...ISSUER" }, + { amount: "250.50", limit: "10000", allowedIssuers: ["GA5Z...ISSUER"] }, +); + +if (!result.valid) { + throw new Error(result.errors.join("; ")); +} +``` + +### Payment retry with provider fallback + +Retry transient failures with exponential backoff and fall back to another provider when one gives up: + +```typescript +import { PaymentFlowRetry, PaymentFlowExhaustedError } from "@stellar-split/sdk"; + +const flow = new PaymentFlowRetry( + [ + { name: "primary", execute: (p) => primaryClient.pay(p) }, + { name: "backup", execute: (p) => backupClient.pay(p) }, + ], + { maxAttempts: 3, baseDelayMs: 500, jitter: 0.2 }, +); + +try { + const { result, provider, attempts } = await flow.execute({ payer: payerKey, invoiceId, amount }); + console.log(`Paid via ${provider} after ${attempts.length} attempt(s): ${result.txHash}`); +} catch (err) { + if (err instanceof PaymentFlowExhaustedError) { + console.error("All providers failed", err.attempts); + } +} +``` + +### Graceful shutdown + +Drain in-flight requests before terminating the client: + +```typescript +process.on("SIGTERM", async () => { + await client.waitForInFlightRequests(); + await client.shutdown(); +}); +``` + +--- + +## Best Practices + +- **Use bigint amounts.** Convert user input with `parseAmount()` and keep amounts as `bigint` stroops end to end. +- **Validate early.** Run `validateStellarAsset()` and `preflightCheck()` before building transactions so failures + surface as clear messages instead of contract errors. +- **Branch on error codes, not messages.** Every SDK error extends `StellarSplitError` and carries a `code`; use + `isRetryableErrorCode(err.code)` to decide whether to retry. +- **Only retry transient failures.** Validation and authorization errors will fail the same way every time; retrying + them wastes fees and rate-limit budget. +- **Configure failover for production.** Supply at least two RPC URLs and subscribe to `circuit:*` and `endpoint:*` events. +- **Shut down cleanly.** Call `waitForInFlightRequests()` then `shutdown()` so plugins and timers are released. +- **Never log secrets.** Keep keypairs in a `signer` adapter rather than passing raw secret keys around. + +```typescript +import { StellarSplitError, isRetryableErrorCode } from "@stellar-split/sdk"; + +try { + await client.pay(params); +} catch (err) { + if (err instanceof StellarSplitError && isRetryableErrorCode(err.code)) { + // schedule a retry + } else { + throw err; + } +} +``` + +--- + +## Optimization Guide + +| Goal | Technique | +|------|-----------| +| Fewer RPC reads | Enable `cache` with a `ttlMs` that matches how fresh invoice data must be | +| Fewer transactions | Group invoice creation with `batchCreateInvoices()` (1–5 per transaction) | +| Avoid failed submissions | `simulate: true` and `preflightCheck()` before `pay()` | +| Smooth traffic spikes | `rateLimit` queues submissions instead of overloading the RPC node | +| Avoid thundering herds | Add `jitter` to retry backoff so concurrent clients spread their retries | +| Survive node outages | Pass an array to `rpcUrl` for warm-standby failover | + +See [PERFORMANCE_TUNING.md](./PERFORMANCE_TUNING.md) for detailed tuning of connection pooling and timeouts. + +--- + +## Reference + +### Client configuration options used in this guide + +| Option | Type | Purpose | +|--------|------|---------| +| `rpcUrl` | `string \| string[]` | RPC endpoint; an array enables failover | +| `retry` | `RetryOptions` | `maxAttempts`, `baseDelayMs`, `maxDelayMs`, `retryIf`, `onRetry` | +| `rateLimit` | `RateLimiterConfig` | `maxRequestsPerSecond`, `windowMs`, `perKeyLimit` | +| `cache` | `{ enabled?, ttl?, ttlMs? }` | In-memory read cache | +| `plugins` | `StellarSplitPlugin[]` | Lifecycle extensions | +| `signer` | `Signer` | Pluggable signing vault | + +### Utilities + +| Export | Description | +|--------|-------------| +| `validateStellarAsset(asset, options?)` | Validates native, classic and custom token assets plus amount limits | +| `PaymentFlowRetry` | Retries payments with exponential backoff and provider fallback | +| `FallbackChain` | Executes an operation against a list of URLs until one succeeds | +| `isRetryableErrorCode(code)` | Reports whether an SDK error code is transient | +| `parseAmount(value)` | Converts a decimal string to bigint stroops | + +### Related documentation + +- [API.md](./API.md) — full API reference +- [ERROR_CODES.md](./ERROR_CODES.md) — error code catalogue +- [PERFORMANCE_TUNING.md](./PERFORMANCE_TUNING.md) — performance tuning +- [MIGRATION.md](./MIGRATION.md) — migration notes diff --git a/src/__tests__/paymentFlowRetry.test.ts b/src/__tests__/paymentFlowRetry.test.ts new file mode 100644 index 00000000..64b356b9 --- /dev/null +++ b/src/__tests__/paymentFlowRetry.test.ts @@ -0,0 +1,98 @@ +import { describe, expect, it, vi } from "vitest"; +import { PaymentFlowExhaustedError, PaymentFlowRetry, type PaymentProvider } from "../paymentFlowRetry"; + +const noSleep = () => Promise.resolve(); + +function provider(name: string, outcomes: Array): PaymentProvider { + const queue = [...outcomes]; + return { + name, + execute: vi.fn(async () => { + const next = queue.shift(); + if (next instanceof Error) throw next; + return next ?? `${name}-ok`; + }), + }; +} + +describe("PaymentFlowRetry", () => { + it("returns the result on first success without retrying", async () => { + const primary = provider("primary", ["tx-1"]); + const flow = new PaymentFlowRetry([primary], { sleep: noSleep }); + + const outcome = await flow.execute("payment"); + + expect(outcome.result).toBe("tx-1"); + expect(outcome.provider).toBe("primary"); + expect(outcome.attempts).toHaveLength(1); + expect(primary.execute).toHaveBeenCalledTimes(1); + }); + + it("retries transient failures until success", async () => { + const primary = provider("primary", [new Error("network timeout"), new Error("503 unavailable"), "tx-3"]); + const flow = new PaymentFlowRetry([primary], { sleep: noSleep }); + + const outcome = await flow.execute("payment"); + + expect(outcome.result).toBe("tx-3"); + expect(primary.execute).toHaveBeenCalledTimes(3); + }); + + it("waits with exponential backoff between retries", async () => { + const sleep = vi.fn(noSleep); + const primary = provider("primary", [new Error("timeout"), new Error("timeout"), "tx"]); + const flow = new PaymentFlowRetry([primary], { baseDelayMs: 100, maxAttempts: 3, sleep }); + + await flow.execute("payment"); + + expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([100, 200]); + }); + + it("falls back to the next provider after exhausting retries", async () => { + const primary = provider("primary", [new Error("timeout"), new Error("timeout")]); + const backup = provider("backup", ["backup-tx"]); + const flow = new PaymentFlowRetry([primary, backup], { maxAttempts: 2, sleep: noSleep }); + + const outcome = await flow.execute("payment"); + + expect(outcome.provider).toBe("backup"); + expect(outcome.result).toBe("backup-tx"); + expect(primary.execute).toHaveBeenCalledTimes(2); + }); + + it("skips straight to fallback on non-transient errors", async () => { + const primary = provider("primary", [new Error("insufficient balance")]); + const backup = provider("backup", ["backup-tx"]); + const flow = new PaymentFlowRetry([primary, backup], { maxAttempts: 3, sleep: noSleep }); + + const outcome = await flow.execute("payment"); + + expect(primary.execute).toHaveBeenCalledTimes(1); + expect(outcome.attempts[0]).toMatchObject({ provider: "primary", success: false, transient: false }); + }); + + it("tracks every attempt with provider, attempt number and delay", async () => { + const onAttempt = vi.fn(); + const primary = provider("primary", [new Error("timeout"), "tx"]); + const flow = new PaymentFlowRetry([primary], { baseDelayMs: 50, sleep: noSleep, onAttempt }); + + await flow.execute("payment"); + + expect(onAttempt).toHaveBeenCalledTimes(2); + expect(flow.getAttempts()).toEqual([ + expect.objectContaining({ provider: "primary", attempt: 1, success: false, transient: true, delayMs: 50 }), + expect.objectContaining({ provider: "primary", attempt: 2, success: true, delayMs: 0 }), + ]); + }); + + it("throws PaymentFlowExhaustedError when all providers fail", async () => { + const primary = provider("primary", [new Error("timeout"), new Error("timeout")]); + const backup = provider("backup", [new Error("rejected")]); + const flow = new PaymentFlowRetry([primary, backup], { maxAttempts: 2, sleep: noSleep }); + + const error = await flow.execute("payment").catch((err) => err); + + expect(error).toBeInstanceOf(PaymentFlowExhaustedError); + expect((error as PaymentFlowExhaustedError).attempts).toHaveLength(3); + }); +}); diff --git a/src/__tests__/stellarAssetValidation.test.ts b/src/__tests__/stellarAssetValidation.test.ts new file mode 100644 index 00000000..ea29d027 --- /dev/null +++ b/src/__tests__/stellarAssetValidation.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "vitest"; +import { Keypair, StrKey } from "@stellar/stellar-sdk"; +import { + parseAmountToStroops, + validateAssetAmount, + validateAssetCode, + validateAssetIssuer, + validateCustomToken, + validateStellarAsset, +} from "../stellarAssetValidation"; + +const ISSUER = Keypair.random().publicKey(); +const CONTRACT = StrKey.encodeContract(Buffer.alloc(32, 7)); + +describe("stellarAssetValidation", () => { + it("classifies valid asset codes by length", () => { + expect(validateAssetCode("USDC")).toEqual({ valid: true, type: "credit_alphanum4" }); + expect(validateAssetCode("LONGTOKEN12")).toEqual({ valid: true, type: "credit_alphanum12" }); + }); + + it("rejects empty, too long and non-alphanumeric asset codes", () => { + expect(validateAssetCode("").valid).toBe(false); + expect(validateAssetCode("THIRTEENCHARS").valid).toBe(false); + expect(validateAssetCode("US-D").valid).toBe(false); + }); + + it("verifies issuer accounts are valid G-addresses", () => { + expect(validateAssetIssuer(ISSUER)).toBeNull(); + expect(validateAssetIssuer("GNOTAREALKEY")).toMatch(/not a valid Stellar public key/); + expect(validateAssetIssuer(CONTRACT)).not.toBeNull(); + }); + + it("supports custom tokens identified by contract address", () => { + expect(validateCustomToken(CONTRACT)).toBeNull(); + expect(validateCustomToken(ISSUER)).toMatch(/not a valid contract address/); + + const result = validateStellarAsset({ contractId: CONTRACT, code: "MYTOKEN" }); + expect(result).toEqual({ valid: true, type: "contract", errors: [] }); + }); + + it("accepts native XLM without an issuer", () => { + expect(validateStellarAsset({ code: "XLM" })).toEqual({ valid: true, type: "native", errors: [] }); + expect(validateStellarAsset({ code: "native" }).type).toBe("native"); + }); + + it("validates classic assets and enforces allowed issuers", () => { + expect(validateStellarAsset({ code: "USDC", issuer: ISSUER }).valid).toBe(true); + + const missingIssuer = validateStellarAsset({ code: "USDC" }); + expect(missingIssuer.valid).toBe(false); + expect(missingIssuer.type).toBeNull(); + + const other = Keypair.random().publicKey(); + const disallowed = validateStellarAsset({ code: "USDC", issuer: ISSUER }, { allowedIssuers: [other] }); + expect(disallowed.valid).toBe(false); + expect(disallowed.errors[0]).toMatch(/allowed issuers/); + }); + + it("parses amounts with Stellar precision", () => { + expect(parseAmountToStroops("1")).toBe(10_000_000n); + expect(parseAmountToStroops("0.0000001")).toBe(1n); + expect(parseAmountToStroops("1.00000001")).toBeNull(); + expect(parseAmountToStroops("-1")).toBeNull(); + }); + + it("enforces amount and trustline limits", () => { + expect(validateAssetAmount("10", "100")).toEqual([]); + expect(validateAssetAmount("0")).toContain("Amount must be greater than zero"); + expect(validateAssetAmount("922337203685.4775808")[0]).toMatch(/exceeds the maximum/); + expect(validateAssetAmount("101", "100")[0]).toMatch(/exceeds the asset limit/); + + const result = validateStellarAsset({ code: "USDC", issuer: ISSUER }, { amount: "500", limit: "100" }); + expect(result.valid).toBe(false); + }); +}); diff --git a/src/index.ts b/src/index.ts index 808567ac..f05dbed7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1355,3 +1355,30 @@ export type { MetricsReport, MetricsCollectorOptions, } from "./metricsCollection.js"; + +// Stellar Asset Validation (#1375) +export { + validateStellarAsset, + validateAssetCode, + validateAssetIssuer, + validateCustomToken, + validateAssetAmount, + parseAmountToStroops, + STELLAR_AMOUNT_DECIMALS, + MAX_STELLAR_AMOUNT_STROOPS, +} from "./stellarAssetValidation.js"; +export type { + StellarAssetType, + StellarAssetInput, + StellarAssetValidationOptions, + StellarAssetValidationResult, +} from "./stellarAssetValidation.js"; + +// Payment Flow Retry and Fallback (#1373) +export { PaymentFlowRetry, PaymentFlowExhaustedError } from "./paymentFlowRetry.js"; +export type { + PaymentProvider, + PaymentFlowRetryOptions, + PaymentAttemptRecord, + PaymentFlowResult, +} from "./paymentFlowRetry.js"; diff --git a/src/paymentFlowRetry.ts b/src/paymentFlowRetry.ts new file mode 100644 index 00000000..5b097a74 --- /dev/null +++ b/src/paymentFlowRetry.ts @@ -0,0 +1,184 @@ +/** + * Payment flow retry and provider fallback (issue #1373). + * + * Wraps a payment submission in two layers of resilience: + * + * - **Exponential backoff retry** — transient failures (timeouts, network + * errors, 5xx responses) are retried against the same provider with an + * exponentially growing, optionally jittered delay. + * - **Provider fallback** — when a provider exhausts its attempts or fails + * with a non-transient error, the next provider in the list is tried. + * + * Every attempt is recorded so callers can inspect exactly what happened. + * + * @example + * ```ts + * const flow = new PaymentFlowRetry([ + * { name: "primary", execute: (p) => primaryClient.pay(p) }, + * { name: "backup", execute: (p) => backupClient.pay(p) }, + * ], { maxAttempts: 3, baseDelayMs: 500 }); + * + * const { result, provider, attempts } = await flow.execute(payment); + * ``` + */ + +import { StellarSplitError } from "./errors.js"; +import { computeBackoffDelay, isRetryableError } from "./retry.js"; + +/** A payment provider that can submit a payment. */ +export interface PaymentProvider { + /** Identifier used in attempt records and errors. */ + name: string; + /** Submit the payment through this provider. */ + execute: (payment: P) => Promise; +} + +/** Configuration for {@link PaymentFlowRetry}. */ +export interface PaymentFlowRetryOptions { + /** Attempts per provider, including the first. Defaults to 3. */ + maxAttempts?: number; + /** Delay before the first retry in milliseconds. Defaults to 500. */ + baseDelayMs?: number; + /** Upper bound for a single retry delay in milliseconds. Defaults to 10 000. */ + maxDelayMs?: number; + /** Jitter factor (0..1) applied to each delay. Defaults to 0. */ + jitter?: number; + /** Decides whether an error is transient and worth retrying. Defaults to {@link isRetryableError}. */ + isTransient?: (error: unknown) => boolean; + /** Called after every attempt with its record. */ + onAttempt?: (record: PaymentAttemptRecord) => void; + /** Sleep implementation (injectable for tests). */ + sleep?: (ms: number) => Promise; +} + +/** Record of a single payment attempt. */ +export interface PaymentAttemptRecord { + /** Provider the attempt was made against. */ + provider: string; + /** 1-based attempt number for this provider. */ + attempt: number; + /** Whether the attempt succeeded. */ + success: boolean; + /** Error message when the attempt failed. */ + error?: string; + /** Whether the failure was classified as transient. */ + transient?: boolean; + /** Backoff delay scheduled after this attempt (0 when none). */ + delayMs: number; + /** Epoch milliseconds when the attempt started. */ + timestamp: number; +} + +/** Successful outcome of {@link PaymentFlowRetry.execute}. */ +export interface PaymentFlowResult { + /** Value returned by the provider. */ + result: R; + /** Name of the provider that succeeded. */ + provider: string; + /** Every attempt made during this execution, in order. */ + attempts: PaymentAttemptRecord[]; +} + +/** Thrown when every provider has failed. */ +export class PaymentFlowExhaustedError extends StellarSplitError { + public readonly attempts: PaymentAttemptRecord[]; + + constructor(attempts: PaymentAttemptRecord[]) { + super( + `Payment failed after ${attempts.length} attempts across all providers.`, + "PAYMENT_FLOW_EXHAUSTED", + { attempts }, + ); + this.attempts = attempts; + Object.setPrototypeOf(this, new.target.prototype); + } +} + +/** Retries a payment with exponential backoff and falls back across providers. */ +export class PaymentFlowRetry { + private readonly providers: PaymentProvider[]; + private readonly maxAttempts: number; + private readonly baseDelayMs: number; + private readonly maxDelayMs: number; + private readonly jitter: number; + private readonly isTransient: (error: unknown) => boolean; + private readonly onAttempt?: (record: PaymentAttemptRecord) => void; + private readonly sleep: (ms: number) => Promise; + private lastAttempts: PaymentAttemptRecord[] = []; + + constructor(providers: PaymentProvider[], options: PaymentFlowRetryOptions = {}) { + if (!Array.isArray(providers) || providers.length === 0) { + throw new RangeError("PaymentFlowRetry requires at least one provider"); + } + const maxAttempts = options.maxAttempts ?? 3; + if (!Number.isInteger(maxAttempts) || maxAttempts < 1) { + throw new RangeError("maxAttempts must be an integer of at least 1"); + } + + this.providers = [...providers]; + this.maxAttempts = maxAttempts; + this.baseDelayMs = options.baseDelayMs ?? 500; + this.maxDelayMs = options.maxDelayMs ?? 10_000; + this.jitter = options.jitter ?? 0; + this.isTransient = options.isTransient ?? isRetryableError; + this.onAttempt = options.onAttempt; + this.sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))); + } + + /** + * Submit a payment, retrying transient failures and falling back to the + * next provider when one gives up. + * + * @throws {PaymentFlowExhaustedError} When every provider has failed. + */ + async execute(payment: P): Promise> { + const attempts: PaymentAttemptRecord[] = []; + this.lastAttempts = attempts; + + for (const provider of this.providers) { + for (let attempt = 1; attempt <= this.maxAttempts; attempt++) { + const timestamp = Date.now(); + try { + const result = await provider.execute(payment); + this.record(attempts, { provider: provider.name, attempt, success: true, delayMs: 0, timestamp }); + return { result, provider: provider.name, attempts: [...attempts] }; + } catch (error) { + const transient = this.isTransient(error); + const willRetry = transient && attempt < this.maxAttempts; + const delayMs = willRetry + ? computeBackoffDelay(attempt, { + baseDelayMs: this.baseDelayMs, + maxDelayMs: this.maxDelayMs, + jitter: this.jitter, + }) + : 0; + this.record(attempts, { + provider: provider.name, + attempt, + success: false, + error: error instanceof Error ? error.message : String(error), + transient, + delayMs, + timestamp, + }); + if (!willRetry) { + break; + } + await this.sleep(delayMs); + } + } + } + + throw new PaymentFlowExhaustedError([...attempts]); + } + + /** Attempts made during the most recent {@link execute} call. */ + getAttempts(): readonly PaymentAttemptRecord[] { + return [...this.lastAttempts]; + } + + private record(attempts: PaymentAttemptRecord[], record: PaymentAttemptRecord): void { + attempts.push(record); + this.onAttempt?.(record); + } +} diff --git a/src/rateLimiter.ts b/src/rateLimiter.ts index 14dbd7b6..36d07d74 100644 --- a/src/rateLimiter.ts +++ b/src/rateLimiter.ts @@ -24,6 +24,8 @@ * Issue #1058 */ +import { computeBackoffDelay } from "./retry.js"; + /** Configuration for {@link RateLimiter}. */ export interface RateLimiterConfig { /** Requests allowed per window, globally. Must be a positive finite number. */ @@ -57,6 +59,33 @@ export interface RateLimiterConfig { * Receives a {@link RateLimitEvent}. Used for logging/metrics. */ onEvent?: (event: RateLimitEvent) => void; + /** + * Backoff applied by {@link RateLimiter.executeWithBackoff} when a request + * is rejected (issue #1349). + */ + backoff?: RateLimitBackoffConfig; +} + +/** Backoff configuration for rejected requests (issue #1349). */ +export interface RateLimitBackoffConfig { + /** Delay before the first retry in milliseconds. Defaults to 100. */ + baseDelayMs?: number; + /** Upper bound for a single delay in milliseconds. Defaults to 5000. */ + maxDelayMs?: number; + /** Retries after the first rejection before giving up. Defaults to 3. */ + maxRetries?: number; +} + +/** Cumulative rate-limit decision counters (issue #1349). */ +export interface RateLimitStats { + /** Requests admitted. */ + allowed: number; + /** Requests rejected. */ + denied: number; + /** Rejections broken down by the limit that produced them. */ + deniedByScope: Record; + /** Backoff waits performed by {@link RateLimiter.executeWithBackoff}. */ + backoffRetries: number; } /** A rate-limit decision event (issue #1252). */ @@ -254,6 +283,8 @@ export class RateLimiter { private _lastRefillTime: number; private _queue: PendingAcquire[] = []; private _processing = false; + private readonly _backoff: Required; + private _stats: RateLimitStats = RateLimiter._emptyStats(); constructor(config: RateLimiterConfig) { if (!config || typeof config !== "object") { @@ -268,6 +299,7 @@ export class RateLimiter { perUserLimit, resolveUser, onEvent, + backoff, } = config; if ( typeof maxRequestsPerSecond !== "number" || @@ -301,6 +333,17 @@ export class RateLimiter { if (onEvent !== undefined && typeof onEvent !== "function") { throw new RangeError("onEvent must be a function"); } + if (backoff !== undefined) { + if (typeof backoff !== "object" || backoff === null) { + throw new RangeError("backoff must be an object"); + } + for (const field of ["baseDelayMs", "maxDelayMs", "maxRetries"] as const) { + const value = backoff[field]; + if (value !== undefined && (!Number.isFinite(value) || value < 0)) { + throw new RangeError(`backoff.${field} must be a non-negative finite number`); + } + } + } this._maxTokens = maxRequestsPerSecond; this._perKeyLimit = perKeyLimit; @@ -314,6 +357,11 @@ export class RateLimiter { this._perUserLimit = perUserLimit; this._resolveUser = resolveUser; this._onEvent = onEvent; + this._backoff = { + baseDelayMs: backoff?.baseDelayMs ?? 100, + maxDelayMs: backoff?.maxDelayMs ?? 5_000, + maxRetries: Math.floor(backoff?.maxRetries ?? 3), + }; } /** Effective window length in milliseconds. */ @@ -378,6 +426,69 @@ export class RateLimiter { }; } + /** + * Run `fn` once the rate limit admits the request, backing off + * exponentially when it is rejected (issue #1349). + * + * Each wait is the larger of the limiter's `retryAfterMs` hint and the + * exponential backoff delay for the attempt, capped by `backoff.maxDelayMs`. + * + * @param method - The method name used for per-method limits and events. + * @param fn - The function to run once admitted. + * @param key - Optional per-key scope. + * @throws {RateLimitExceededError} When still rejected after `backoff.maxRetries` retries. + */ + async executeWithBackoff(method: string, fn: () => R | Promise, key?: string): Promise { + for (let attempt = 1; ; attempt++) { + try { + this.enforce(method, [], key); + break; + } catch (err) { + if (!(err instanceof RateLimitExceededError) || attempt > this._backoff.maxRetries) { + throw err; + } + const delayMs = Math.max( + err.retryAfterMs, + computeBackoffDelay(attempt, { + baseDelayMs: this._backoff.baseDelayMs, + maxDelayMs: this._backoff.maxDelayMs, + }), + ); + this._stats.backoffRetries++; + await new Promise((resolve) => setTimeout(resolve, delayMs)); + } + } + return fn(); + } + + /** Snapshot of cumulative rate-limit decisions (issue #1349). */ + getStats(): RateLimitStats { + return { ...this._stats, deniedByScope: { ...this._stats.deniedByScope } }; + } + + /** Reset the decision counters returned by {@link getStats}. */ + resetStats(): void { + this._stats = RateLimiter._emptyStats(); + } + + private static _emptyStats(): RateLimitStats { + return { + allowed: 0, + denied: 0, + deniedByScope: { global: 0, method: 0, user: 0, key: 0 }, + backoffRetries: 0, + }; + } + + private _track(allowed: boolean, scope: RateLimitEvent["scope"]): void { + if (allowed) { + this._stats.allowed++; + } else { + this._stats.denied++; + this._stats.deniedByScope[scope]++; + } + } + private _evaluateScoped( method: string, args: unknown[], @@ -390,6 +501,7 @@ export class RateLimiter { const user = this._resolveUser ? this._resolveUser(method, args) : undefined; const deny = (scope: RateLimitEvent["scope"], retryAfterMs: number): RateLimitCheck & { user?: string } => { + if (consume) this._track(false, scope); this._emit({ method, user, allowed: false, remaining: 0, retryAfterMs, scope, timestamp: now }); return { allowed: false, remaining: 0, retryAfterMs, user }; }; @@ -430,6 +542,7 @@ export class RateLimiter { this._tokens--; } const remaining = Math.floor(this._tokens); + if (consume) this._track(true, "global"); this._emit({ method, user, allowed: true, remaining, retryAfterMs: 0, scope: "global", timestamp: now }); return { allowed: true, remaining, retryAfterMs: 0, user }; } @@ -496,11 +609,12 @@ export class RateLimiter { return Math.max(0, this._windowMs - (now - this._lastRefillTime)); } - private _evaluate(key: string | undefined, consume: boolean): RateLimitCheck { + private _evaluate(key: string | undefined, consume: boolean, track: boolean = consume): RateLimitCheck { const now = Date.now(); this._refill(now); if (this._tokens <= 0) { + if (track) this._track(false, "global"); return { allowed: false, remaining: 0, retryAfterMs: this._msUntilRefill(now) }; } @@ -509,11 +623,13 @@ export class RateLimiter { ? this._store.consume(key, this._perKeyLimit, this._windowMs, now) : this._store.peek(key, this._perKeyLimit, this._windowMs, now); if (!keyResult.allowed) { + if (track) this._track(false, "key"); return { allowed: false, remaining: 0, retryAfterMs: keyResult.retryAfterMs }; } if (consume) { this._tokens--; } + if (track) this._track(true, "global"); return { allowed: true, remaining: Math.min(Math.floor(this._tokens), keyResult.remaining), @@ -524,6 +640,7 @@ export class RateLimiter { if (consume) { this._tokens--; } + if (track) this._track(true, "global"); return { allowed: true, remaining: Math.floor(this._tokens), retryAfterMs: 0 }; } @@ -540,7 +657,9 @@ export class RateLimiter { index++; continue; } - if (this._evaluate(next.key, true).allowed) { + // Queued callers were already counted as denied; only count the grant. + if (this._evaluate(next.key, true, false).allowed) { + this._track(true, "global"); this._queue.splice(index, 1); next.resolve(); continue; diff --git a/src/stellarAssetValidation.ts b/src/stellarAssetValidation.ts new file mode 100644 index 00000000..7214270b --- /dev/null +++ b/src/stellarAssetValidation.ts @@ -0,0 +1,226 @@ +/** + * Stellar asset validation (issue #1375). + * + * Offline, structural validation for every kind of asset the SDK accepts: + * + * - **Native XLM** — code `"XLM"` (or `"native"`) with no issuer. + * - **Classic credit assets** — `credit_alphanum4` (1–4 chars) and + * `credit_alphanum12` (5–12 chars) codes issued by a valid G-address. + * - **Custom tokens** — Soroban token contracts identified by a C-address. + * - **Limits** — amounts are checked against the 7-decimal stroop precision, + * the int64 ceiling Stellar imposes, and an optional trustline limit. + * + * Network checks (issuer existence, stellar.toml) live in + * {@link verifyAssetIssuer}; this module never performs I/O. + */ + +import { StrKey } from "@stellar/stellar-sdk"; + +/** Kind of asset a validated input resolves to. */ +export type StellarAssetType = + | "native" + | "credit_alphanum4" + | "credit_alphanum12" + | "contract"; + +/** Asset description accepted by {@link validateStellarAsset}. */ +export interface StellarAssetInput { + /** Asset code (e.g. "USDC"). Optional for custom tokens. */ + code?: string; + /** Issuer G-address for classic credit assets. */ + issuer?: string; + /** Soroban token contract C-address for custom tokens. */ + contractId?: string; +} + +/** Options for {@link validateStellarAsset}. */ +export interface StellarAssetValidationOptions { + /** Amount to check against limits, as a decimal string (e.g. "10.5"). */ + amount?: string; + /** Trustline/asset limit the amount must not exceed, as a decimal string. */ + limit?: string; + /** When provided, the issuer must be one of these G-addresses. */ + allowedIssuers?: string[]; +} + +/** Result of {@link validateStellarAsset}. */ +export interface StellarAssetValidationResult { + /** Whether every check passed. */ + valid: boolean; + /** Resolved asset type, or `null` when it could not be determined. */ + type: StellarAssetType | null; + /** Human-readable reasons for each failed check. */ + errors: string[]; +} + +/** Number of decimal places Stellar amounts support. */ +export const STELLAR_AMOUNT_DECIMALS = 7; + +/** Largest representable amount in stroops (int64 max). */ +export const MAX_STELLAR_AMOUNT_STROOPS = 9_223_372_036_854_775_807n; + +const ASSET_CODE_PATTERN = /^[A-Za-z0-9]{1,12}$/; +const AMOUNT_PATTERN = /^\d+(\.\d+)?$/; + +/** + * Validate an asset code and classify it by length. + * + * @param code - The asset code to validate. + * @returns The asset type on success, or an error message. + */ +export function validateAssetCode( + code: string, +): { valid: true; type: "credit_alphanum4" | "credit_alphanum12" } | { valid: false; error: string } { + if (typeof code !== "string" || code.length === 0) { + return { valid: false, error: "Asset code is required" }; + } + if (!ASSET_CODE_PATTERN.test(code)) { + return { + valid: false, + error: `Asset code "${code}" must be 1-12 alphanumeric characters`, + }; + } + return { valid: true, type: code.length <= 4 ? "credit_alphanum4" : "credit_alphanum12" }; +} + +/** + * Validate that an issuer is a well-formed Stellar account (G-address). + * + * @param issuer - Issuer public key. + * @returns `null` when valid, otherwise an error message. + */ +export function validateAssetIssuer(issuer: string): string | null { + if (typeof issuer !== "string" || issuer.length === 0) { + return "Asset issuer is required"; + } + if (!StrKey.isValidEd25519PublicKey(issuer)) { + return `Asset issuer "${issuer}" is not a valid Stellar public key`; + } + return null; +} + +/** + * Validate a custom token contract address (C-address). + * + * @param contractId - Soroban contract id. + * @returns `null` when valid, otherwise an error message. + */ +export function validateCustomToken(contractId: string): string | null { + if (typeof contractId !== "string" || contractId.length === 0) { + return "Token contract id is required"; + } + if (!StrKey.isValidContract(contractId)) { + return `Token contract id "${contractId}" is not a valid contract address`; + } + return null; +} + +/** + * Convert a decimal amount string into stroops. + * + * @returns The amount in stroops, or `null` when the string is malformed or + * has more than {@link STELLAR_AMOUNT_DECIMALS} decimal places. + */ +export function parseAmountToStroops(amount: string): bigint | null { + if (typeof amount !== "string" || !AMOUNT_PATTERN.test(amount)) { + return null; + } + const [whole, fraction = ""] = amount.split("."); + if (fraction.length > STELLAR_AMOUNT_DECIMALS) { + return null; + } + return BigInt(whole + fraction.padEnd(STELLAR_AMOUNT_DECIMALS, "0")); +} + +/** + * Validate an amount against Stellar's precision and size limits and, + * optionally, a trustline limit. + * + * @param amount - Decimal amount string. + * @param limit - Optional decimal limit the amount must not exceed. + * @returns A list of error messages (empty when valid). + */ +export function validateAssetAmount(amount: string, limit?: string): string[] { + const errors: string[] = []; + const stroops = parseAmountToStroops(amount); + if (stroops === null) { + errors.push( + `Amount "${amount}" must be a non-negative decimal with at most ${STELLAR_AMOUNT_DECIMALS} decimal places`, + ); + return errors; + } + if (stroops <= 0n) { + errors.push("Amount must be greater than zero"); + } + if (stroops > MAX_STELLAR_AMOUNT_STROOPS) { + errors.push(`Amount "${amount}" exceeds the maximum Stellar amount`); + } + if (limit !== undefined) { + const limitStroops = parseAmountToStroops(limit); + if (limitStroops === null) { + errors.push(`Limit "${limit}" is not a valid Stellar amount`); + } else if (stroops > limitStroops) { + errors.push(`Amount "${amount}" exceeds the asset limit of "${limit}"`); + } + } + return errors; +} + +/** + * Validate a Stellar asset — native, classic credit asset, or custom token — + * and optionally an amount against its limits. + * + * @example + * validateStellarAsset({ code: "USDC", issuer: "GA5Z..." }, { amount: "25", limit: "1000" }); + * validateStellarAsset({ contractId: "CA3D..." }); + * validateStellarAsset({ code: "XLM" }); + */ +export function validateStellarAsset( + asset: StellarAssetInput, + options: StellarAssetValidationOptions = {}, +): StellarAssetValidationResult { + const errors: string[] = []; + let type: StellarAssetType | null = null; + + if (!asset || typeof asset !== "object") { + return { valid: false, type: null, errors: ["Asset is required"] }; + } + + const { code, issuer, contractId } = asset; + const isNative = (code === "XLM" || code === "native") && !issuer && !contractId; + + if (contractId !== undefined) { + const error = validateCustomToken(contractId); + if (error) { + errors.push(error); + } else { + type = "contract"; + } + if (code !== undefined) { + const codeResult = validateAssetCode(code); + if (!codeResult.valid) errors.push(codeResult.error); + } + } else if (isNative) { + type = "native"; + } else { + const codeResult = validateAssetCode(code ?? ""); + if (!codeResult.valid) { + errors.push(codeResult.error); + } + const issuerError = validateAssetIssuer(issuer ?? ""); + if (issuerError) { + errors.push(issuerError); + } else if (options.allowedIssuers && !options.allowedIssuers.includes(issuer as string)) { + errors.push(`Asset issuer "${issuer}" is not in the list of allowed issuers`); + } + if (codeResult.valid && !issuerError) { + type = codeResult.type; + } + } + + if (options.amount !== undefined) { + errors.push(...validateAssetAmount(options.amount, options.limit)); + } + + return { valid: errors.length === 0, type, errors }; +} diff --git a/test/rateLimiter.test.ts b/test/rateLimiter.test.ts index a0569e1f..dbc40801 100644 --- a/test/rateLimiter.test.ts +++ b/test/rateLimiter.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it, vi } from "vitest"; import { Keypair, StrKey } from "@stellar/stellar-sdk"; -import { RateLimiter, RateLimitStore } from "../src/rateLimiter.js"; +import { RateLimiter, RateLimitExceededError, RateLimitStore } from "../src/rateLimiter.js"; import type { RateLimiterConfig } from "../src/rateLimiter.js"; import { StellarSplitClient } from "../src/client.js"; @@ -228,4 +228,75 @@ describe("StellarSplitClient rateLimit configuration", () => { }); }); +// --------------------------------------------------------------------------- +// Backoff and tracking (#1349) +// --------------------------------------------------------------------------- + +describe("RateLimiter — backoff and tracking", () => { + it("tracks allowed and denied decisions by scope", () => { + vi.useFakeTimers(); + try { + const limiter = new RateLimiter({ maxRequestsPerSecond: 3, perKeyLimit: 1 }); + limiter.tryAcquire("alice"); + limiter.tryAcquire("alice"); + limiter.tryAcquire("bob"); + limiter.tryAcquire(); + limiter.tryAcquire(); + limiter.check(); + + expect(limiter.getStats()).toEqual({ + allowed: 3, + denied: 2, + deniedByScope: { global: 1, method: 0, user: 0, key: 1 }, + backoffRetries: 0, + }); + + limiter.resetStats(); + expect(limiter.getStats().allowed).toBe(0); + } finally { + vi.useRealTimers(); + } + }); + + it("executeWithBackoff waits for capacity before running the function", async () => { + vi.useFakeTimers(); + try { + const limiter = new RateLimiter({ maxRequestsPerSecond: 1, backoff: { baseDelayMs: 100 } }); + const fn = vi.fn(() => "done"); + await expect(limiter.executeWithBackoff("pay", fn)).resolves.toBe("done"); + + const pending = limiter.executeWithBackoff("pay", fn); + await vi.advanceTimersByTimeAsync(999); + expect(fn).toHaveBeenCalledTimes(1); + + await vi.advanceTimersByTimeAsync(1); + await expect(pending).resolves.toBe("done"); + expect(fn).toHaveBeenCalledTimes(2); + expect(limiter.getStats().backoffRetries).toBe(1); + } finally { + vi.useRealTimers(); + } + }); + + it("executeWithBackoff gives up after maxRetries", async () => { + vi.useFakeTimers(); + try { + const limiter = new RateLimiter({ maxRequestsPerSecond: 1, backoff: { maxRetries: 0 } }); + await limiter.executeWithBackoff("pay", () => undefined); + const fn = vi.fn(); + + await expect(limiter.executeWithBackoff("pay", fn)).rejects.toBeInstanceOf(RateLimitExceededError); + expect(fn).not.toHaveBeenCalled(); + } finally { + vi.useRealTimers(); + } + }); + + it("rejects invalid backoff configuration", () => { + expect(() => new RateLimiter({ maxRequestsPerSecond: 1, backoff: { baseDelayMs: -1 } })).toThrow(RangeError); + expect(() => new RateLimiter({ maxRequestsPerSecond: 1, backoff: { maxRetries: Number.NaN } })).toThrow( + RangeError, + ); + }); +});