Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 2 additions & 129 deletions docs/PERFORMANCE_TUNING.md
Original file line number Diff line number Diff line change
Expand Up @@ -181,133 +181,6 @@ const client = new StellarSplitClient({
## Technique 5: Multi-Endpoint Load Balancing & Failover

### Explanation
Single-node deployments present a single point of failure. `RpcLoadBalancer` continuously measures latency and error rates across multiple endpoints, routing traffic to the healthiest node and quarantining degraded ones.
Single-node

### Code Example
```typescript
const client = new StellarSplitClient({
rpcUrl: "https://primary-rpc.example.com",
rpcEndpoints: [
"https://primary-rpc.example.com",
"https://secondary-rpc.example.com",
"https://fallback-rpc.example.com",
],
networkPassphrase: "Public Global Stellar Network ; September 2015",
contractId: "CA...",
});
```

### Tradeoffs
- **Advantages**: Zero downtime during vendor outages; routes read traffic to the fastest provider.
- **Drawbacks**: Requires subscriptions or access to multiple RPC provider endpoints.

### Measurements
| Injected Failure Scenario | Single Endpoint Success Rate | Load Balanced Success Rate |
| :--- | :--- | :--- |
| Primary RPC 100% Down | 0% (Total Failure) | **100% (Transparent Failover)** |
| Primary RPC 30% Packet Loss | 70% | **99.4% (Adaptive rerouting)** |

---

## Technique 6: Soroban Footprint & Storage TTL Batching

### Explanation
Soroban contract instances and storage entries have Time-To-Live (TTL) values measured in ledgers. If an invoice's storage entry expires, restoring it requires expensive archival recovery transactions (~1.5 XLM per entry).

The SDK provides `bumpStorageTtlBatch` to batch TTL extensions for multiple invoices in a single transaction.

### Code Example
```typescript
const invoiceIds = ["inv-001", "inv-002", "inv-003", "inv-004"];

// Extend storage TTL by 500,000 ledgers (~30 days) in a single batch transaction
const result = await client.bumpStorageTtlBatch(invoiceIds, 500_000);
console.log(`Extended TTL across ${invoiceIds.length} invoices. Tx: ${result.txHash}`);
```

### Tradeoffs
- **Advantages**: 60%+ reduction in transaction fee costs compared to individual TTL bumps; prevents catastrophic storage expiration.
- **Drawbacks**: Consumes minor fee resources upfront. Best scheduled as a recurring background cron job.

### Measurements
| Extension Strategy | Transactions Submitted | Total Fees Incurred | Execution Time |
| :--- | :--- | :--- | :--- |
| Individual Bumps (20 entries) | 20 transactions | ~2,000,000 stroops | 45.2 s |
| Batch Bump (`bumpStorageTtlBatch`) | 1 transaction | ~760,000 stroops | 2.8 s |
| Resource Savings | **95% fewer txs** | **62% lower fees** | **93.8% faster** |

---

## Technique 7: Real-Time Event Streaming vs. Polling

### Explanation
Polling Horizon or Soroban RPC endpoints every few seconds creates unnecessary server load and introduces notification lag for end users.

The SDK supports WebSocket and Server-Sent Events (SSE) streaming through `subscribeInvoice` and `subscribeToInvoice`.

### Code Example
```typescript
// Stream real-time status transitions and payments
const unsubscribe = client.subscribeInvoice("inv-123", (event) => {
console.log(`Event ${event.type} detected on invoice ${event.invoiceId}`);
});

// Clean up when leaving page
// unsubscribe();
```

### Tradeoffs
- **Advantages**: Immediate notification (sub-100ms lag); zero continuous RPC polling load.
- **Drawbacks**: Requires an active WebSocket or SSE connection; falls back to HTTP polling if firewall blocks persistent connections.

### Measurements
| Metric | HTTP Polling (3s interval) | Real-Time Streaming (SSE/WS) | Improvement |
| :--- | :--- | :--- | :--- |
| Average Notification Lag | 1,520 ms | 36 ms | **97.6% faster** |
| RPC Calls per Client / Hour | 1,200 requests | 1 initial connect | **99.9% fewer calls** |

---

## Performance Decision Matrix & Recommendations

| Workload Profile | Recommended Configuration | Primary Benefit |
| :--- | :--- | :--- |
| **High-Volume Payment Gateway** | `rpcPoolSize: 12`, `circuitBreaker: enabled`, `rpcEndpoints: [multi]` | 99.99% uptime, zero socket starvation |
| **User Dashboard / Explorer** | `cache: { ttlMs: 30000 }`, `batching: true`, `subscribeInvoice` | Instant UI response, minimal RPC bills |
| **Batch Settlement Bot** | `bumpStorageTtlBatch`, `verifyBatchPay`, `batchPay` | 60%+ gas savings, verified atomic payments |
| **Resource-Constrained Edge / CLI** | `SplitClient` (lazy init), single connection | Instant boot time (< 5ms), zero idle memory |

---

## Profiling Guide

Measure before tuning. Change one setting at a time and compare against a baseline.

1. **Run the repository benchmarks** to catch regressions in SDK internals:
```bash
npm run test:bench
```
2. **Compare against the load-test baselines** in `load-tests/baseline.json` (throughput, p50/p90/p95/p99 latency, error rate per scenario) after any performance-related change.
3. **Profile a Node.js script** that exercises your hot path (build first with `npm run build`):
```bash
node --cpu-prof --cpu-prof-dir=./prof your-script.js # open the .cpuprofile in Chrome DevTools
node --inspect-brk your-script.js # heap snapshots / live debugging
```
4. **Time individual RPC calls** with the SDK telemetry hooks (see `docs/TELEMETRY_HOOKS.md`) instead of ad-hoc timers, so latency is attributed per method.
5. **Check bundle size** with `npm run size-audit` and `npm run bundle:check` when optimizing for browser or edge targets.

Look first at the number of RPC round trips per user action, then cache hit rate, then CPU time in your own code.

---

## Optimization Checklist

- [ ] Baseline captured (latency percentiles, throughput, RPC calls per operation)
- [ ] Connection pooling enabled for high-concurrency workloads (`rpcPoolSize`)
- [ ] Read-heavy paths use caching with a TTL suited to how fast the data changes
- [ ] Independent reads are batched or issued concurrently rather than sequentially
- [ ] Circuit breaker configured so a failing node does not stall all requests
- [ ] Multiple RPC endpoints configured for failover where uptime matters
- [ ] Storage TTL bumps batched instead of issued per invoice
- [ ] Event subscriptions used instead of tight polling loops
- [ ] Changes re-measured against the baseline and `npm run test:bench` shows no regression
/* … truncated 6137 chars — edit only what you need near the top … */
150 changes: 149 additions & 1 deletion docs/SDK_TUTORIALS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ This guide provides step-by-step tutorials for integrating with the StellarSplit
4. [Webhook Integration](#webhook-integration)
5. [Multi-Signature Wallets](#multi-signature-wallets)
6. [Error Handling](#error-handling)
7. [Production Checklist](#production-checklist)
7. [Advanced Usage](#advanced-usage)
8. [Production Checklist](#production-checklist)

---

Expand Down Expand Up @@ -209,6 +210,153 @@ try {

---

## Advanced Usage

This section covers patterns for production-grade integrations: batching, retries, pagination, event streaming, and performance tuning.

### Pattern: Idempotent Invoice Creation

Generate a deterministic client-side key so retries never create duplicate invoices.

```typescript
import { createHash } from "node:crypto";

function idempotencyKey(creator: string, externalRef: string): string {
return createHash("sha256").update(`${creator}:${externalRef}`).digest("hex");
}

async function createInvoiceOnce(creator: string, externalRef: string) {
const key = idempotencyKey(creator, externalRef);
const existing = await client.findInvoiceByReference({ creator, reference: key });
if (existing) return existing;

return client.createInvoice({
creator,
reference: key,
recipients: [{ address: "GABC...RECIPIENT1", amount: parseAmount("100") }],
token: "USDC_CONTRACT_ADDRESS",
deadline: deadlineFromDays(7),
});
}
```

### Pattern: Retry with Exponential Backoff

Retry only transient failures (network / RPC), never validation errors.

```typescript
import { StellarSplitError, isRetryableError } from "@stellar-split/sdk";

async function withRetry<T>(fn: () => Promise<T>, attempts = 5): Promise<T> {
let lastErr: unknown;
for (let i = 0; i < attempts; i++) {
try {
return await fn();
} catch (err) {
lastErr = err;
const retryable = err instanceof StellarSplitError && isRetryableError(err);
if (!retryable || i === attempts - 1) throw err;
const delay = Math.min(2 ** i * 250, 8000) + Math.random() * 100;
await new Promise((r) => setTimeout(r, delay));
}
}
throw lastErr;
}

await withRetry(() => client.pay({ payer, invoiceId, amount: parseAmount("25") }));
```

### Pattern: Batched Payments

Pay multiple invoices in a single transaction to reduce fees and round-trips.

```typescript
const { txHash } = await client.payBatch({
payer,
payments: [
{ invoiceId: "INV_1", amount: parseAmount("10") },
{ invoiceId: "INV_2", amount: parseAmount("15") },
],
});
```

### Pattern: Paginated Invoice Listing

```typescript
async function* allInvoices(creator: string) {
let cursor: string | undefined;
do {
const page = await client.listInvoices({ creator, cursor, limit: 50 });
for (const invoice of page.items) yield invoice;
cursor = page.nextCursor;
} while (cursor);
}

for await (const invoice of allInvoices(publicKey)) {
console.log(invoice.invoiceId, invoice.status);
}
```

### Pattern: Real-Time Event Streaming

```typescript
const stream = client.streamEvents({ invoiceId });

stream.on("payment", (p) => console.log("Payment received:", p.amount));
stream.on("completed", () => stream.close());
stream.on("error", (err) => console.error("Stream error:", err));
```

### Pattern: Concurrent Payment Collection

```typescript
const results = await Promise.allSettled(
payers.map((payer) =>
withRetry(() => client.pay({ payer, invoiceId, amount: parseAmount("5") }))
)
);

const failed = results.filter((r) => r.status === "rejected");
if (failed.length) console.warn(`${failed.length} payments failed`);
```

### Best Practices

- **Reuse a single client instance** per process; it manages connection pooling internally.
- **Never retry non-idempotent operations** without an idempotency key.
- **Validate amounts and addresses** client-side before submitting to avoid wasted fees.
- **Use `payBatch`** when paying many invoices to amortize transaction fees.
- **Stream events** instead of polling for status changes.
- **Pin the SDK version** in production and review changelogs before upgrading.
- **Keep secrets server-side**; never expose `WEBHOOK_SECRET` to the browser.
- **Log `txHash` and error `code`** for every operation to aid debugging.

### Optimization Guide

| Area | Recommendation |
|------|----------------|
| Client lifecycle | Create one `StellarSplitClient` and reuse it across requests |
| Network calls | Batch reads with `listInvoices` pagination; batch writes with `payBatch` |
| Concurrency | Cap parallel payments (e.g. 5–10) to avoid RPC rate limits |
| Polling | Replace polling with `streamEvents` |
| Fees | Combine payments into a single transaction where possible |
| Caching | Cache immutable invoice metadata; invalidate on `completed` events |
| Payload size | Request only needed fields via `select` where supported |

### Advanced Reference

| Method | Description |
|--------|-------------|
| `client.payBatch({ payer, payments })` | Pay multiple invoices in one transaction |
| `client.listInvoices({ creator, cursor, limit })` | Paginated invoice listing |
| `client.findInvoiceByReference({ creator, reference })` | Look up invoice by idempotency reference |
| `client.streamEvents({ invoiceId })` | Subscribe to real-time invoice events |
| `isRetryableError(err)` | Returns `true` for transient SDK errors |
| `client.getInvoice(invoiceId)` | Fetch a single invoice by ID |
| `client.getBalance({ address, token })` | Query token balance for an address |

---

## Production Checklist

Before deploying to production:
Expand Down
37 changes: 37 additions & 0 deletions src/__tests__/configManager.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { describe, it, expect } from "vitest";
import { ConfigManager, deepMerge } from "../configManager.js";
import { CsrfProtection } from "../csrf.js";

describe("ConfigManager", () => {
it("deep merges", () => {
Expand All @@ -23,3 +24,39 @@ describe("ConfigManager", () => {
expect(m.get()).toEqual({ rpcUrl: "x" });
});
});

describe("CsrfProtection", () => {
it("issues secure tokens and validates them strictly", () => {
const csrf = new CsrfProtection();
const token = csrf.issueToken();
expect(token.length).toBeGreaterThanOrEqual(32);
expect(csrf.validateToken(token)).toBe(true);
expect(csrf.validateToken("bogus")).toBe(false);
expect(csrf.validateToken(undefined)).toBe(false);
});

it("rejects reused tokens after consumption", () => {
const csrf = new CsrfProtection();
const token = csrf.issueToken();
expect(csrf.validateToken(token, { consume: true })).toBe(true);
expect(csrf.validateToken(token)).toBe(false);
});

it("refreshes tokens and tracks state", () => {
const csrf = new CsrfProtection();
const first = csrf.issueToken();
const refreshed = csrf.refreshToken(first);
expect(refreshed).not.toBe(first);
expect(csrf.validateToken(refreshed)).toBe(true);
expect(csrf.validateToken(first)).toBe(false);
expect(csrf.getStats().issued).toBe(2);
});

it("protects state-changing requests only", () => {
const csrf = new CsrfProtection();
const token = csrf.issueToken();
expect(csrf.protectRequest("GET", {})).toBe(true);
expect(csrf.protectRequest("POST", {})).toBe(false);
expect(csrf.protectRequest("POST", { "x-csrf-token": token })).toBe(true);
});
});
Loading