diff --git a/docs/api.md b/docs/api.md index 3a3146c4..f4ea7c9f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -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` / `symbol(tokenAddress, signal?) → Promise` + +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` + +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 @@ -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` + +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` @@ -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. diff --git a/src/errors.ts b/src/errors.ts index 8a363ec9..84a92d7b 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -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 diff --git a/src/index.ts b/src/index.ts index 96d1584d..c82c6b9c 100644 --- a/src/index.ts +++ b/src/index.ts @@ -133,6 +133,7 @@ export { isRecoverableError, StreamFiError, IndexerMaxPagesExceededError, + MissingTrustlineError, isConduitError, SUPPORTED_NETWORKS, CAIP2_TO_NETWORK, @@ -249,7 +250,12 @@ export type { ContractRole, } from "./constants.js"; -export { TokenModule, formatTokenAmount as formatLocalizedTokenAmount } from "./token.js"; +export { + TokenModule, + DEFAULT_TOKEN_METADATA_CACHE_SIZE, + formatTokenAmount as formatLocalizedTokenAmount, +} from "./token.js"; +export type { TokenModuleOptions } from "./token.js"; export { getEndpointHealth, @@ -290,6 +296,7 @@ export { clearTokenDecimalsCache, getTokenDecimalsCacheMetrics, resetTokenDecimalsCacheMetrics, + scValToString, } from "./soroban.js"; export { getLatestLedgerInfo, clearLedgerInfoCache } from "./soroban.js"; export type { LedgerInfo } from "./soroban.js"; diff --git a/src/indexer.ts b/src/indexer.ts index dc49adaa..a7aa51e2 100644 --- a/src/indexer.ts +++ b/src/indexer.ts @@ -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(() => { diff --git a/src/soroban.ts b/src/soroban.ts index e587667e..20e2e287 100644 --- a/src/soroban.ts +++ b/src/soroban.ts @@ -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. * diff --git a/src/streams.ts b/src/streams.ts index 33970d30..04b11594 100644 --- a/src/streams.ts +++ b/src/streams.ts @@ -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"; @@ -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 { + 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, diff --git a/src/tests/indexer-reconnect-backoff.test.ts b/src/tests/indexer-reconnect-backoff.test.ts new file mode 100644 index 00000000..c29d827a --- /dev/null +++ b/src/tests/indexer-reconnect-backoff.test.ts @@ -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(); + }); +}); diff --git a/src/tests/streams-module-batch.test.ts b/src/tests/streams-module-batch.test.ts new file mode 100644 index 00000000..31675376 --- /dev/null +++ b/src/tests/streams-module-batch.test.ts @@ -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 }); + }); +}); diff --git a/src/tests/token-metadata-trustline.test.ts b/src/tests/token-metadata-trustline.test.ts new file mode 100644 index 00000000..e90a9cf3 --- /dev/null +++ b/src/tests/token-metadata-trustline.test.ts @@ -0,0 +1,158 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { Address, Asset, Keypair, Networks, xdr } from '@stellar/stellar-sdk'; + +const { mockBuildContractCallTx, mockSimulateReadOnly, mockGetAccount, mockGetTokenDecimals } = vi.hoisted(() => ({ + mockBuildContractCallTx: vi.fn(), + mockSimulateReadOnly: vi.fn(), + mockGetAccount: vi.fn(), + mockGetTokenDecimals: vi.fn(), +})); + +vi.mock('../soroban.js', async (importOriginal) => ({ + ...(await importOriginal()), + buildContractCallTx: mockBuildContractCallTx, + simulateReadOnly: mockSimulateReadOnly, + getTokenDecimals: mockGetTokenDecimals, + getServer: () => ({ getAccount: mockGetAccount }), +})); + + +import { MissingTrustlineError } from '../errors.js'; +import { USDC_ISSUER } from '../constants.js'; +import { TokenModule } from '../token.js'; + +const owner = Keypair.random(); +const tokenA = Address.contract(Buffer.alloc(32, 7)).toString(); +const tokenB = Address.contract(Buffer.alloc(32, 8)).toString(); +const tx = { kind: 'transaction' }; + +function newTokens(options?: { metadataCacheSize?: number }): TokenModule { + return new TokenModule( + { network: 'testnet', keypair: owner }, + options, + ); +} + +describe('TokenModule metadata LRU cache', () => { + beforeEach(() => { + mockGetTokenDecimals.mockReset().mockResolvedValue(7); + mockBuildContractCallTx.mockReset().mockResolvedValue(tx); + mockSimulateReadOnly.mockReset().mockResolvedValue(xdr.ScVal.scvU32(7)); + mockGetAccount.mockReset(); + }); + + it('caches decimals per token and only queries the source once', async () => { + const tokens = newTokens(); + await expect(tokens.decimals(tokenA)).resolves.toBe(7); + await expect(tokens.decimals(tokenA)).resolves.toBe(7); + await expect(tokens.decimals(tokenA)).resolves.toBe(7); + + expect(mockGetTokenDecimals).toHaveBeenCalledTimes(1); + expect(mockGetTokenDecimals.mock.calls[0]?.[3]).toBe(tokenA); + }); + + it('caches symbol values (scvString and scvSymbol)', async () => { + mockSimulateReadOnly.mockResolvedValueOnce(xdr.ScVal.scvString(Buffer.from('USDC'))); + const tokens = newTokens(); + await expect(tokens.symbol(tokenA)).resolves.toBe('USDC'); + await expect(tokens.getSymbol(tokenA)).resolves.toBe('USDC'); + + mockSimulateReadOnly.mockResolvedValueOnce(xdr.ScVal.scvSymbol(Buffer.from('XLM'))); + await expect(tokens.symbol(tokenB)).resolves.toBe('XLM'); + + expect(mockSimulateReadOnly).toHaveBeenCalledTimes(2); + expect(mockBuildContractCallTx.mock.calls[0]?.[4]).toBe('symbol'); + }); + + it('coalesces concurrent in-flight lookups for the same token', async () => { + const tokens = newTokens(); + const [a, b] = await Promise.all([tokens.decimals(tokenA), tokens.decimals(tokenA)]); + + expect(a).toBe(7); + expect(b).toBe(7); + expect(mockGetTokenDecimals).toHaveBeenCalledTimes(1); + }); + + it('does not cache failed metadata lookups', async () => { + mockGetTokenDecimals + .mockRejectedValueOnce(new Error('simulation boom')) + .mockResolvedValueOnce(2); + const tokens = newTokens(); + + await expect(tokens.decimals(tokenA)).rejects.toThrow('simulation boom'); + await expect(tokens.decimals(tokenA)).resolves.toBe(2); + expect(mockGetTokenDecimals).toHaveBeenCalledTimes(2); + }); + + it('evicts the least-recently-used token at the configured capacity', async () => { + const tokens = newTokens({ metadataCacheSize: 1 }); + await tokens.decimals(tokenA); + await tokens.decimals(tokenB); + // tokenA was evicted by tokenB, so this is a third LRU miss. + await tokens.decimals(tokenA); + + expect(tokens.getMetadataCacheMetrics().decimals.cacheMisses).toBe(3); + }); + + it('clearMetadataCache forces fresh lookups', async () => { + const tokens = newTokens(); + await tokens.decimals(tokenA); + tokens.clearMetadataCache(); + await tokens.decimals(tokenA); + + expect(mockGetTokenDecimals).toHaveBeenCalledTimes(2); + }); +}); + +describe('TokenModule.checkTrustline', () => { + const issuer = USDC_ISSUER.testnet; + const usdcContract = new Asset('USDC', issuer).contractId(Networks.TESTNET); + const account = Keypair.random().publicKey(); + + beforeEach(() => { + mockGetAccount.mockReset(); + }); + + it('never requires a trustline for native XLM', async () => { + const result = await newTokens().checkTrustline('native', account); + expect(result.hasTrustline).toBe(true); + expect(mockGetAccount).not.toHaveBeenCalled(); + }); + + it('detects an existing trustline via the asset contract ID', async () => { + mockGetAccount.mockResolvedValue({ + balances: [ + { asset_type: 'native', balance: '10' }, + { asset_type: 'credit_alphanum4', asset_code: 'USDC', asset_issuer: issuer, balance: '5' }, + ], + }); + + const result = await newTokens().checkTrustline(usdcContract, account); + expect(result.hasTrustline).toBe(true); + expect(result.assetCode).toBe('USDC'); + expect(result.message).toContain('has a trustline'); + }); + + it('reports a missing trustline with an actionable message', async () => { + mockGetAccount.mockResolvedValue({ balances: [{ asset_type: 'native', balance: '10' }] }); + + const result = await newTokens().checkTrustline('USDC', account); + expect(result.hasTrustline).toBe(false); + expect(result.message).toContain('no trustline'); + expect(result.message).toContain(account); + }); + + it('throws MissingTrustlineError when throwOnMissing is set', async () => { + mockGetAccount.mockResolvedValue({ balances: [{ asset_type: 'native', balance: '10' }] }); + + await expect( + newTokens().checkTrustline('USDC', account, { throwOnMissing: true }), + ).rejects.toBeInstanceOf(MissingTrustlineError); + }); + + it('requireTrustline throws on a missing trustline', async () => { + mockGetAccount.mockResolvedValue({ balances: [{ asset_type: 'native', balance: '10' }] }); + + await expect(newTokens().requireTrustline('USDC', account)).rejects.toThrow(/trustline/); + }); +}); diff --git a/src/token.ts b/src/token.ts index 440e1e5f..1a08dd58 100644 --- a/src/token.ts +++ b/src/token.ts @@ -11,12 +11,15 @@ import { KeypairWalletAdapter } from "./adapters/keypair.js"; import { USDC_ISSUER, ZERO_ADDR } from "./constants.js"; import { buildContractCallTx, + clearTokenDecimalsCache, DEFAULT_RPC, + getServer, getTokenDecimals, invokeContract, NETWORK_PASSPHRASE, resolveFee, scValToI128, + scValToString, simulateReadOnly, } from "./soroban.js"; @@ -36,11 +39,31 @@ export class TokenModule { */ private readonly knownDecimals = new Map(); - constructor(private readonly config: ConduitConfig) { + /** + * Immutable SEP-41 metadata (`decimals()` / `symbol()`) is queried far more + * often than it changes. Bounded LRU caches keep repeat lookups off the + * network without letting a large portfolio grow the cache without limit. + */ + private readonly decimalsCache: LruMemoCache; + private readonly symbolCache: LruMemoCache; + + /** + * In-flight de-duplication: concurrent lookups for the same token share a + * single simulation. Entries are removed on settlement (success or failure) + * so a failed simulation is retried on the next call. + */ + private readonly decimalsInFlight = new Map>(); + private readonly symbolInFlight = new Map>(); + + constructor(private readonly config: ConduitConfig, options: TokenModuleOptions = {}) { this.rpcUrl = config.rpcUrl ?? DEFAULT_RPC[config.network]; this.passphrase = NETWORK_PASSPHRASE[config.network]; this.fee = resolveFee(config); + const cacheSize = Math.max(1, Math.floor(options.metadataCacheSize ?? DEFAULT_TOKEN_METADATA_CACHE_SIZE)); + this.decimalsCache = new LruMemoCache(cacheSize); + this.symbolCache = new LruMemoCache(cacheSize); + if (config.wallet) { this.activeWallet = config.wallet; } else if (config.keypair) { @@ -65,8 +88,9 @@ export class TokenModule { * * Native XLM, the network's USDC, and anything passed to * {@link registerDecimals} resolve with no RPC call. Any other token is - * queried once via its `decimals()` and then served from the process-wide - * cache in `soroban.ts`, so repeated balance formatting never re-queries it. + * queried once via its `decimals()` and then served from this module's + * bounded LRU metadata cache, so repeated balance formatting never + * re-queries it. Concurrent lookups coalesce onto one in-flight simulation. * * @param callerAddress - Source account for the read-only simulation. * Defaults to the connected wallet / signer, or a zero address. @@ -77,8 +101,13 @@ export class TokenModule { ): Promise { const known = this.knownDecimals.get(tokenAddress); if (known !== undefined) return known; - const caller = callerAddress ?? (await this.defaultCaller()); - return getTokenDecimals(this.rpcUrl, this.passphrase, caller, tokenAddress); + return this.loadMetadata( + this.decimalsCache, + this.decimalsInFlight, + tokenAddress, + (caller) => getTokenDecimals(this.rpcUrl, this.passphrase, caller, tokenAddress), + callerAddress, + ); } /** Record `decimals` for `tokenAddress` so {@link decimals} never queries the RPC for it. */ diff --git a/src/types/index.ts b/src/types/index.ts index 27b44d8b..2fbff039 100644 --- a/src/types/index.ts +++ b/src/types/index.ts @@ -447,6 +447,34 @@ export interface GetStreamInfosResult { failures: GetStreamInfosFailure[]; } +/** Options for `TokenModule.checkTrustline()`. */ +export interface TrustlineCheckOptions { + signal?: AbortSignal | undefined; + /** + * When true, a missing trustline throws `MissingTrustlineError` instead of + * resolving with `hasTrustline: false`. Defaults to false. + */ + throwOnMissing?: boolean; +} + +/** Result of a `TokenModule.checkTrustline()` pre-flight check. */ +export interface TrustlineCheckResult { + /** Whether `account` can receive the token without adding a trustline. */ + hasTrustline: boolean; + /** The account that was checked. */ + account: string; + /** The token identifier that was checked (`native`, `USDC`, or a contract ID). */ + token: string; + /** Resolved classic asset code, when the token maps to a classic asset. */ + assetCode?: string | undefined; + /** Resolved classic asset issuer, when the token maps to a classic asset. */ + assetIssuer?: string | undefined; + /** The Stellar Asset Contract ID used for the comparison, when resolved. */ + contractId?: string | undefined; + /** Human-readable explanation suitable for UI error/success messages. */ + message: string; +} + export interface GovernorConfig { feeBps: number; feeRecipient?: string;