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
128 changes: 128 additions & 0 deletions src/batch-tx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,134 @@ import type { Network } from './types/index.js';

export const DEFAULT_BATCH_TIMEOUT_SECONDS = 30;

// ── Deduplicated footprint builder ────────────────────────────────────────────

/** Anything that can yield ledger keys for a merged batch footprint. */
export type FootprintSource =
| xdr.LedgerFootprint
| xdr.LedgerKey[]
| {
readOnly?: xdr.LedgerKey[];
readWrite?: xdr.LedgerKey[];
footprint?: FootprintSource;
transactionData?: { footprint?: FootprintSource };
}
| null
| undefined;

interface KeySets {
readOnly: xdr.LedgerKey[];
readWrite: xdr.LedgerKey[];
}

function isLedgerKey(value: unknown): value is xdr.LedgerKey {
return value instanceof xdr.LedgerKey;
}

function uniqueKeyId(key: xdr.LedgerKey): string {
return key.toXDR('base64');
}

function normalizeFootprintSource(source: FootprintSource): KeySets | undefined {
if (!source) return undefined;
if (typeof source !== 'object' && typeof source !== 'function') {
throw new BatchBuildError('footprint sources must be xdr.LedgerFootprint values, xdr.LedgerKey arrays, or simulation responses');
}
if (Array.isArray(source)) {
for (const key of source) {
if (!isLedgerKey(key)) {
throw new BatchBuildError('footprint arrays must contain only xdr.LedgerKey values');
}
}
return { readOnly: [], readWrite: source };
}
const record = source as Record<string, unknown>;
if (typeof record.footprint === 'object' || typeof record.footprint === 'function') {
return normalizeFootprintSource(record.footprint as FootprintSource);
}
const txData = record.transactionData as { footprint?: FootprintSource } | undefined;
if (txData && typeof txData === 'object' && txData.footprint) {
return normalizeFootprintSource(txData.footprint);
}
// Real `xdr.LedgerFootprint` instances expose accessor methods rather than
// plain arrays; duck-type them so a second copy of the SDK still works.
if (typeof record.readOnly === 'function' && typeof record.readWrite === 'function') {
const readOnly = (record.readOnly as () => xdr.LedgerKey[])();
const readWrite = (record.readWrite as () => xdr.LedgerKey[])();
return { readOnly, readWrite };
}
const readOnly = Array.isArray(record.readOnly) ? record.readOnly : [];
const readWrite = Array.isArray(record.readWrite) ? record.readWrite : [];
for (const key of [...readOnly, ...readWrite]) {
if (!isLedgerKey(key)) {
throw new BatchBuildError('footprint arrays must contain only xdr.LedgerKey values');
}
}
return { readOnly, readWrite };
}

/**
* Merge several footprints (or arrays of ledger keys, or Soroban simulation
* responses) into one {@link xdr.LedgerFootprint} with every ledger key
* appearing at most once.
*
* Batch payloads combine operations that often touch the same ledger entries
* (source account, token balances, stream contracts). Sending a footprint with
* duplicate keys — or with a key only in `readOnly` when another operation
* needs it as `readWrite` — makes the network reject the whole batch. This
* builder unions the sets and promotes any key seen as writable to `readWrite`.
*
* The first occurrence of each key wins the ordering, and the input footprints
* are never mutated.
*
* @param sources Footprints/keys to merge, passed as an array or as arguments.
*/
export function mergeFootprints(
...sources: Array<FootprintSource | FootprintSource[]>
): xdr.LedgerFootprint {
const flat: FootprintSource[] = sources.flat() as FootprintSource[];
const readOnly = new Map<string, xdr.LedgerKey>();
const readWrite = new Map<string, xdr.LedgerKey>();

for (const source of flat) {
const keys = normalizeFootprintSource(source);
if (!keys) continue;
for (const key of keys.readOnly) {
const id = uniqueKeyId(key);
if (!readWrite.has(id) && !readOnly.has(id)) readOnly.set(id, key);
}
for (const key of keys.readWrite) {
const id = uniqueKeyId(key);
readOnly.delete(id);
if (!readWrite.has(id)) readWrite.set(id, key);
}
}

return new xdr.LedgerFootprint({
readOnly: Array.from(readOnly.values()),
readWrite: Array.from(readWrite.values()),
});
}

/** Remove duplicate ledger keys from a single footprint, promoting writable keys. */
export function deduplicateFootprint(footprint: FootprintSource): xdr.LedgerFootprint {
return mergeFootprints(footprint);
}

/** Alias of {@link mergeFootprints}. */
export const buildDeduplicatedFootprint = mergeFootprints;
/** Alias of {@link mergeFootprints}. */
export const buildMergedFootprint = mergeFootprints;
/** Alias of {@link mergeFootprints} for batch-specific call sites. */
export const mergeBatchFootprints = mergeFootprints;

/** Merge the footprints attached to a list of Soroban simulation responses. */
export function mergeSimulationFootprints(
simulations: SorobanRpc.Api.SimulateTransactionResponse[],
): xdr.LedgerFootprint {
return mergeFootprints(simulations as unknown as FootprintSource[]);
}

/**
* Split a flat list of batch operations into chunks small enough to fit
* Soroban's per-transaction instruction / footprint limits.
Expand Down
30 changes: 30 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,12 @@ export {
BatchBuildError,
BatchPartiallySubmittedError,
submitBatch,
mergeFootprints,
deduplicateFootprint,
buildDeduplicatedFootprint,
buildMergedFootprint,
mergeBatchFootprints,
mergeSimulationFootprints,
} from "./batch-tx.js";
export type {
BatchTransactionContext,
Expand All @@ -42,6 +48,7 @@ export type {
BatchTxStatus,
BatchSubmitOptions,
BatchSimulationResult,
FootprintSource,
BuildableOperation,
BatchPayload,
BatchSimulationSummary,
Expand All @@ -52,6 +59,11 @@ export {
DEFAULT_INDEXER_MAX_PAGES,
DEFAULT_SUBSCRIPTION_POLLING_INTERVAL_MS,
LedgerGapDetector,
replayEventsFrom,
DEFAULT_REPLAY_LEDGER_OFFSET,
DEFAULT_REPLAY_EVENTS_PAGE_SIZE,
DEFAULT_REPLAY_EVENTS_MAX_PAGES,
REPLAY_EVENTS_FROM_QUERY,
} from "./indexer.js";
export {
MockGraphQLIndexer,
Expand All @@ -78,6 +90,8 @@ export type {
FetchStreamsBySenderOptions,
StreamsByRecipientOptions,
StreamStatusFilter,
ReplayEventsFromOptions,
ReplayEventsFromResult,
} from "./indexer.js";
export {
withSignatureTimeout,
Expand All @@ -88,12 +102,28 @@ export {
LedgerHardwareError,
normalizeLedgerError,
classifyLedgerError,
isDeviceTimeoutError,
wrapLedgerError,
wrapDeviceTimeoutError,
withDeviceDiagnosticHints,
withDeviceTimeout,
LEDGER_DEVICE_TIMEOUT_HINT,
LEDGER_DEVICE_DIAGNOSTIC_HINT,
PreflightSimulationError,
PreflightSigner,
preflightSimulate,
preflightBeforeSign,
preflightCheck,
withPreflightSimulation,
withSimulationPreflight,
WebAuthnSigner,
derToRawSignature,
} from "./signer.js";
export type {
Signer,
SignerOptions,
PreflightSimulationServer,
PreflightSimulationOptions,
WebAuthnCredentialDescriptor,
WebAuthnAssertionResponse,
WebAuthnAssertionCredential,
Expand Down
Loading