Skip to content
Merged
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
39 changes: 38 additions & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,27 @@ Sets the spender's allowance and returns the confirmed transaction hash.
amount and expiration ledger appropriate for the stream operation that will
consume the allowance.

### `decimals(tokenAddress, signal?) → Promise<number>` / `symbol(tokenAddress, signal?) → Promise<string>`

Read immutable SEP-41 metadata. Results are kept in two bounded in-memory LRU
caches (256 entries each by default) keyed by RPC URL + token address, so
repeated lookups across a portfolio do not each cost an RPC simulation.
Concurrent lookups for the same token coalesce onto one in-flight request, and
failed simulations are not cached. Use `clearMetadataCache()` to invalidate,
or `getMetadataCacheMetrics()` to inspect hit/miss counts. The cache size is
configurable via `new TokenModule(config, { metadataCacheSize })`.

### `checkTrustline(token, accountAddress, options?) → Promise<TrustlineCheckResult>`

Pre-flight validation for accounts that will receive a non-native Stellar
asset. `token` may be `'native'`, `'USDC'`, a `"CODE:ISSUER"` pair, or a Stellar
Asset Contract ID. The check compares the token's contract ID against those
derived from the account's classic asset balance lines and resolves with
`{ hasTrustline, message, ... }`. Pass `{ throwOnMissing: true }` (or call
`requireTrustline(token, accountAddress)`) to throw a `MissingTrustlineError`
with an actionable message instead — use this before submitting a transaction
so users see "add this trustline first" rather than an opaque contract revert.

---

## Network explorer constants
Expand Down Expand Up @@ -129,6 +150,20 @@ Pure helpers returning `StreamProgress`: ratio and percentage complete, elapsed/

Fetches the complete stream state from the chain.

### `getStreamsBatch(streamIds, options?) → Promise<GetStreamInfosResult>`

Chunked, deduplicated reads for portfolio screens that need many streams at
once. Duplicate IDs are collapsed, the remainder is split into sequential
chunks of `chunkSize` (default 20), and each chunk uses bounded concurrency
(`maxConcurrency`, default 8). `chunkDelayMs` optionally pauses between
chunks to stay under RPC rate limits. Per-stream failures are returned in
`failures` instead of rejecting the whole batch. Also available on
`client.streams` directly.

```typescript
const { results, failures } = await client.getStreamsBatch(ids, { chunkSize: 10 });
```

---

### `withdrawable(streamId) → Promise<bigint>`
Expand Down Expand Up @@ -885,7 +920,9 @@ available (e.g. some non-browser, non-Node runtimes) it falls back to reading a
| `reconnectDelayMs` | `number` (0–60000, default 1000) | |

On the WebSocket path, an unexpected socket close calls `onError` (if provided) and retries
with linear backoff (`reconnectDelayMs * attempt`), matching `WebSocketRelayer`. The
with capped exponential backoff (`reconnectDelayMs * 2^(attempt - 1)`, capped at 30s) plus
randomized jitter of up to 30% of the capped delay. The jitter de-synchronises clients that
reconnect after the same network transition, avoiding reconnection storms. The
subscription stays active until `unsubscribe()`, `cleanup()`, or the retry budget is
exhausted. Exhaustion calls `onError` again with a message containing `exhausted` and then
tears the subscription down. The SSE fallback does not reconnect.
Expand Down
41 changes: 41 additions & 0 deletions src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1541,6 +1541,47 @@ export class ValidationError extends StreamFiError {
}
}

/**
* Thrown by `TokenModule.checkTrustline()` when an account is about to
* receive or deposit a non-native Stellar asset but has no established
* trustline for it.
*
* This is a pre-flight, client-side guard: it turns an opaque contract revert
* into an actionable message that names the account, the asset and the
* missing trustline so the UI can prompt the user to add it first.
*/
export class MissingTrustlineError extends Error {
/** The account that is missing the trustline. */
readonly account: string;
/** The token identifier that was checked. */
readonly token: string;
/** Resolved classic asset code, when known. */
readonly assetCode?: string | undefined;
/** Resolved classic asset issuer, when known. */
readonly assetIssuer?: string | undefined;

constructor(options: {
account: string;
token: string;
assetCode?: string | undefined;
assetIssuer?: string | undefined;
}) {
const asset = options.assetCode
? `${options.assetCode}${options.assetIssuer ? ` (${options.assetIssuer})` : ''}`
: options.token;
super(
`Account ${options.account} has no trustline for ${asset}. ` +
'Create the trustline before sending or depositing this asset.',
);
this.name = 'MissingTrustlineError';
this.account = options.account;
this.token = options.token;
this.assetCode = options.assetCode;
this.assetIssuer = options.assetIssuer;
Object.setPrototypeOf(this, new.target.prototype);
}
}

/**
* Thrown by {@link GraphQLIndexer.fetchAll} when the paginated query
* accumulates more pages than the configured maximum
Expand Down
9 changes: 8 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@
isRecoverableError,
StreamFiError,
IndexerMaxPagesExceededError,
MissingTrustlineError,
isConduitError,
SUPPORTED_NETWORKS,
CAIP2_TO_NETWORK,
Expand Down Expand Up @@ -249,7 +250,12 @@
ContractRole,
} from "./constants.js";

export { TokenModule, formatTokenAmount as formatLocalizedTokenAmount } from "./token.js";
export {
TokenModule,
DEFAULT_TOKEN_METADATA_CACHE_SIZE,

Check failure on line 255 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint & typecheck

Module '"./token.js"' has no exported member 'DEFAULT_TOKEN_METADATA_CACHE_SIZE'.

Check failure on line 255 in src/index.ts

View workflow job for this annotation

GitHub Actions / Test

Module '"./token.js"' has no exported member 'DEFAULT_TOKEN_METADATA_CACHE_SIZE'.

Check failure on line 255 in src/index.ts

View workflow job for this annotation

GitHub Actions / Size limit

Module '"./token.js"' has no exported member 'DEFAULT_TOKEN_METADATA_CACHE_SIZE'.
formatTokenAmount as formatLocalizedTokenAmount,
} from "./token.js";
export type { TokenModuleOptions } from "./token.js";

Check failure on line 258 in src/index.ts

View workflow job for this annotation

GitHub Actions / Lint & typecheck

Module '"./token.js"' has no exported member 'TokenModuleOptions'.

Check failure on line 258 in src/index.ts

View workflow job for this annotation

GitHub Actions / Test

Module '"./token.js"' has no exported member 'TokenModuleOptions'.

Check failure on line 258 in src/index.ts

View workflow job for this annotation

GitHub Actions / Size limit

Module '"./token.js"' has no exported member 'TokenModuleOptions'.

export {
getEndpointHealth,
Expand Down Expand Up @@ -290,6 +296,7 @@
clearTokenDecimalsCache,
getTokenDecimalsCacheMetrics,
resetTokenDecimalsCacheMetrics,
scValToString,
} from "./soroban.js";
export { getLatestLedgerInfo, clearLedgerInfoCache } from "./soroban.js";
export type { LedgerInfo } from "./soroban.js";
Expand Down
9 changes: 7 additions & 2 deletions src/indexer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -745,8 +745,13 @@ export class GraphQLIndexer {
return;
}
reconnectAttempts += 1;
const baseDelay = reconnectDelayMs * reconnectAttempts;
const cappedDelay = Math.min(baseDelay, 30_000);
// Exponential backoff: base * 2^(attempt - 1), capped at 30s. Linear
// growth kept hammering an endpoint that was still recovering.
const exponentialDelay = reconnectDelayMs * 2 ** (reconnectAttempts - 1);
const cappedDelay = Math.min(exponentialDelay, 30_000);
// Randomized jitter (up to 30% of the capped delay) de-synchronises
// clients reconnecting after the same network transition, preventing a
// reconnection storm against a recovering indexer.
const jitter = Math.random() * 0.3 * cappedDelay;
const delay = cappedDelay + jitter;
reconnectTimer = setTimeout(() => {
Expand Down
15 changes: 15 additions & 0 deletions src/soroban.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1176,6 +1176,21 @@ export function scValToU32(val: xdr.ScVal): number {
return val.u32();
}

/**
* Convert an ScVal string/symbol to a JS string.
*
* SEP-41 metadata getters use different shapes across implementations:
* `symbol()` commonly returns an `scvSymbol`, while `name()` returns an
* `scvString`. Accept both so token metadata lookups don't fail on an
* XDR union-shape mismatch.
*/
export function scValToString(val: xdr.ScVal): string {
const kind = val.switch().name;
if (kind === 'scvString') return val.str().toString('utf8');
if (kind === 'scvSymbol') return val.sym().toString('utf8');
throw new Error(`Expected a string or symbol ScVal, got "${kind}" instead.`);
}

/**
* Encode a u64 value as ScVal.
*
Expand Down
43 changes: 43 additions & 0 deletions src/streams.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ import type {
DurationBreakdown,
StreamProgress,
StreamSimulationResult,
BatchGetStreamsOptions,
GetStreamInfosResult,
} from "./types/index.js";
import type { WalletAdapter } from "./adapters/types.js";
import type { Signer } from "./signer.js";
Expand Down Expand Up @@ -993,6 +995,47 @@ export class StreamsModule {
};
}

/**
* Fetch full state for many streams while staying under RPC rate limits.
*
* This is the primary entry point for portfolio screens that need to render
* 50+ streams: instead of issuing one unthrottled fan-out, duplicate IDs are
* collapsed, the remainder is split into sequential chunks of `chunkSize`
* (default 20), and each chunk is read with bounded concurrency via
* {@link getStreamInfos}. `chunkDelayMs` optionally pauses between chunks.
* A single missing or broken stream is reported in `failures` rather than
* rejecting the whole batch, and the order within `results`/`failures`
* follows the (deduplicated) input order.
*
* @param streamIds - Stream IDs to read; strings and bigints may be mixed.
* @param options - Chunking, pacing and per-chunk concurrency controls.
*/
async getStreamsBatch(
streamIds: (bigint | string)[],
options: BatchGetStreamsOptions = {},
): Promise<GetStreamInfosResult> {
const chunkSize = Math.max(1, Math.floor(options.chunkSize ?? 20) || 20);
const chunkDelayMs = Math.max(0, options.chunkDelayMs ?? 0);
const unique = [...new Set(streamIds.map((id) => BigInt(id)))];

const results: GetStreamInfosResult['results'] = [];
const failures: GetStreamInfosResult['failures'] = [];

for (let i = 0; i < unique.length; i += chunkSize) {
if (i > 0 && chunkDelayMs > 0) {
await new Promise((resolve) => setTimeout(resolve, chunkDelayMs));
}
const chunk = await this.getStreamInfos(
unique.slice(i, i + chunkSize),
options.maxConcurrency === undefined ? {} : { maxConcurrency: options.maxConcurrency },
);
results.push(...chunk.results);
failures.push(...chunk.failures);
}

return { results, failures };
}

/** Get withdrawable balance - read-only, no transaction. */
async withdrawable(
streamId: bigint | string,
Expand Down
106 changes: 106 additions & 0 deletions src/tests/indexer-reconnect-backoff.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { GraphQLIndexer } from '../indexer.js';

class FakeWebSocket {
static instances: FakeWebSocket[] = [];

readyState = 0;
onopen: (() => void) | null = null;
onclose: (() => void) | null = null;
onerror: ((event: unknown) => void) | null = null;
onmessage: ((event: { data: string }) => void) | null = null;
sent: string[] = [];

constructor(public readonly url: string, public readonly protocols?: string | string[]) {
FakeWebSocket.instances.push(this);
}

send(message: string): void {
this.sent.push(message);
}

close(): void {
this.readyState = 3;
}

/** Simulate an unexpected network drop. */
drop(): void {
this.onclose?.();
}
}

const originalWebSocket = (globalThis as unknown as { WebSocket?: unknown }).WebSocket;

describe('GraphQLIndexer reconnect backoff', () => {
beforeEach(() => {
vi.useFakeTimers();
FakeWebSocket.instances = [];
(globalThis as unknown as { WebSocket?: unknown }).WebSocket = FakeWebSocket;
});

afterEach(() => {
vi.restoreAllMocks();
vi.useRealTimers();
if (originalWebSocket === undefined) {
delete (globalThis as unknown as { WebSocket?: unknown }).WebSocket;
} else {
(globalThis as unknown as { WebSocket?: unknown }).WebSocket = originalWebSocket;
}
});

it('doubles the delay on each reconnect attempt (capped at 30s)', () => {
vi.spyOn(Math, 'random').mockReturnValue(0); // zero jitter for exact timing
const indexer = new GraphQLIndexer('https://indexer.example/graphql');
const sub = indexer.subscribe({
query: 'subscription { stream { id } }',
onData: () => {},
onError: () => {},
reconnectDelayMs: 1000,
maxReconnectAttempts: 4,
});

// Attempt 1: base 1000 * 2^0 = 1000ms.
FakeWebSocket.instances[0]!.drop();
vi.advanceTimersByTime(999);
expect(FakeWebSocket.instances).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(FakeWebSocket.instances).toHaveLength(2);

// Attempt 2: 1000 * 2^1 = 2000ms.
FakeWebSocket.instances[1]!.drop();
vi.advanceTimersByTime(1999);
expect(FakeWebSocket.instances).toHaveLength(2);
vi.advanceTimersByTime(1);
expect(FakeWebSocket.instances).toHaveLength(3);

// Attempt 3: 1000 * 2^2 = 4000ms.
FakeWebSocket.instances[2]!.drop();
vi.advanceTimersByTime(3999);
expect(FakeWebSocket.instances).toHaveLength(3);
vi.advanceTimersByTime(1);
expect(FakeWebSocket.instances).toHaveLength(4);

sub.unsubscribe();
});

it('adds randomized jitter on top of the exponential delay', () => {
vi.spyOn(Math, 'random').mockReturnValue(0.5); // 15% of the capped delay
const indexer = new GraphQLIndexer('https://indexer.example/graphql');
const sub = indexer.subscribe({
query: 'subscription { stream { id } }',
onData: () => {},
onError: () => {},
reconnectDelayMs: 1000,
maxReconnectAttempts: 2,
});

// 1000ms base + 0.5 * 0.3 * 1000 = 1150ms.
FakeWebSocket.instances[0]!.drop();
vi.advanceTimersByTime(1149);
expect(FakeWebSocket.instances).toHaveLength(1);
vi.advanceTimersByTime(1);
expect(FakeWebSocket.instances).toHaveLength(2);

sub.unsubscribe();
});
});
36 changes: 36 additions & 0 deletions src/tests/streams-module-batch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { describe, it, expect, vi } from 'vitest';
import { StreamsModule } from '../streams.js';

describe('StreamsModule.getStreamsBatch', () => {
it('deduplicates IDs and reads them in bounded chunks', async () => {
const streams = new StreamsModule({
network: 'testnet',
factoryAddress: 'CCWAMYJME27OHTPKVSV252YRPXEO4BSKBHVLQ7ML3OWYNMB5RQEVHSM',
});
const spy = vi.spyOn(streams, 'getStreamInfos').mockImplementation(async (ids) => ({
results: ids.map((id) => ({ id } as never)),
failures: [],
}));

const out = await streams.getStreamsBatch([1n, '2', 1n, 3n, 4n, 5n], { chunkSize: 2 });

expect(spy.mock.calls.map((c) => c[0])).toEqual([[1n, 2n], [3n, 4n], [5n]]);
expect(out.results).toHaveLength(5);
expect(out.failures).toEqual([]);
});

it('forwards the per-chunk concurrency limit', async () => {
const streams = new StreamsModule({
network: 'testnet',
factoryAddress: 'CCWAMYJME27OHTPKVSV252YRPXEO4BSKBHVLQ7ML3OWYNMB5RQEVHSM',
});
const spy = vi.spyOn(streams, 'getStreamInfos').mockImplementation(async (ids) => ({
results: ids.map((id) => ({ id } as never)),
failures: [],
}));

await streams.getStreamsBatch([1n, 2n], { maxConcurrency: 3 });

expect(spy).toHaveBeenCalledWith([1n, 2n], { maxConcurrency: 3 });
});
});
Loading
Loading