Skip to content
Closed
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@across-protocol/sdk",
"author": "UMA Team",
"version": "4.3.38",
"version": "4.3.39",
"license": "AGPL-3.0",
"homepage": "https://docs.across.to/reference/sdk",
"files": [
Expand Down
114 changes: 94 additions & 20 deletions src/arch/svm/SpokeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ import {
} from "./";
import { SvmCpiEventsClient } from "./eventsClient";
import { SVM_BLOCK_NOT_AVAILABLE, SVM_SLOT_SKIPPED, isSolanaError } from "./provider";
import { AttestedCCTPMessage, SVMEventNames, SVMProvider } from "./types";
import { AttestedCCTPMessage, EventWithData, SVMEventNames, SVMProvider } from "./types";
import {
getEmergencyDeleteRootBundleRootBundleId,
getNearestSlotTime,
Expand Down Expand Up @@ -163,6 +163,40 @@ export function getDepositIdAtBlock(_contract: unknown, _blockTag: number): Prom
throw new Error("getDepositIdAtBlock: not implemented");
}

/**
* Helper function to query deposit events within a time window.
* @param eventClient - SvmCpiEventsClient instance
* @param depositId - The deposit ID to search for
* @param slot - The slot to search up to (defaults to current slot)
* @param secondsLookback - The number of seconds to look back for deposits (defaults to 2 days)
* @returns Array of deposit events within the slot window
*/
async function queryDepositEventsInWindow(
eventClient: SvmCpiEventsClient,
depositId: BigNumber,
slot?: bigint,
secondsLookback = 2 * 24 * 60 * 60 // 2 days
): Promise<EventWithData[]> {
// We can only perform this search when we have a safe deposit ID.
if (isUnsafeDepositId(depositId)) {
throw new Error(`Cannot binary search for depositId ${depositId}`);
}

const provider = eventClient.getRpc();
const { slot: currentSlot } = await getNearestSlotTime(provider);

// If no slot is provided, use the current slot
// If a slot is provided, ensure it's not in the future
const endSlot = slot !== undefined ? BigInt(Math.min(Number(slot), Number(currentSlot))) : currentSlot;

// Calculate start slot (approximately secondsLookback seconds earlier)
const slotsInElapsed = BigInt(Math.round((secondsLookback * 1000) / SLOT_DURATION_MS));
const startSlot = endSlot - slotsInElapsed;

// Query for the deposit events with this limited slot range
return eventClient.queryEvents("FundsDeposited", startSlot, endSlot);
}

/**
* Finds deposit events within a 2-day window ending at the specified slot.
*
Expand All @@ -184,7 +218,8 @@ export function getDepositIdAtBlock(_contract: unknown, _blockTag: number): Prom
* @important
* This function may return `undefined` for valid deposit IDs that are older than the search
* window (approximately 2 days before the specified slot). This is an acceptable limitation
* as deposits this old are typically not relevant to current operations.
* as deposits this old are typically not relevant to current operations. This can be an issue
* if no proposal was made for a chain over a period of > 1.5 days.
*
* @param eventClient - SvmCpiEventsClient instance
* @param depositId - The deposit ID to search for
Expand All @@ -199,24 +234,9 @@ export async function findDeposit(
slot?: bigint,
secondsLookback = 2 * 24 * 60 * 60 // 2 days
): Promise<DepositWithBlock | undefined> {
// We can only perform this search when we have a safe deposit ID.
if (isUnsafeDepositId(depositId)) {
throw new Error(`Cannot binary search for depositId ${depositId}`);
}

const provider = eventClient.getRpc();
const { slot: currentSlot } = await getNearestSlotTime(provider);

// If no slot is provided, use the current slot
// If a slot is provided, ensure it's not in the future
const endSlot = slot !== undefined ? BigInt(Math.min(Number(slot), Number(currentSlot))) : currentSlot;

// Calculate start slot (approximately secondsLookback seconds earlier)
const slotsInElapsed = BigInt(Math.round((secondsLookback * 1000) / SLOT_DURATION_MS));
const startSlot = endSlot - slotsInElapsed;

// Query for the deposit events with this limited slot range. Filter by deposit id.
const depositEvent = (await eventClient.queryEvents("FundsDeposited", startSlot, endSlot))?.find((event) =>
const depositEvents = await queryDepositEventsInWindow(eventClient, depositId, slot, secondsLookback);
// Find the first matching deposit event
const depositEvent = depositEvents.find((event) =>
depositId.eq((event.data as unknown as { depositId: BigNumber }).depositId)
);

Expand Down Expand Up @@ -245,6 +265,60 @@ export async function findDeposit(
} as DepositWithBlock;
}

/**
* Finds all deposit events within a time window (default 2 days) ending at the specified slot.
*
* @remarks
* This implementation uses a slot-limited search approach because Solana PDA state has
* limitations that prevent directly referencing old deposit IDs. Unlike EVM chains where
* we might use binary search across the entire chain history, in Solana we must query within
* a constrained slot range.
*
* The search window is calculated by:
* 1. Using the provided slot (or current confirmed slot if none is provided)
* 2. Looking back 2 days worth of slots from that point
*
* We use a 2-day window because:
* 1. Most valid deposits that need to be processed will be recent
* 2. This covers multiple bundle submission periods
* 3. It balances performance with practical deposit age
*
* @important
* This function may return an empty array for valid deposit IDs that are older than the search
* window (approximately 2 days before the specified slot). This is an acceptable limitation
* as deposits this old are typically not relevant to current operations. This can be an issue
* if no proposal was made for a chain over a period of > 1.5 days.
*
* @param eventClient - SvmCpiEventsClient instance
* @param depositId - The deposit ID to search for
* @param slot - The slot to search up to (defaults to current slot). The search will look
* for deposits between (slot - secondsLookback) and slot.
* @param secondsLookback - The number of seconds to look back for deposits (defaults to 2 days).
* @returns Array of deposits if found within the slot window, empty array otherwise
*/
export async function findAllDeposits(
eventClient: SvmCpiEventsClient,
depositId: BigNumber,
slot?: bigint,
secondsLookback = 2 * 24 * 60 * 60 // 2 days
): Promise<DepositWithBlock[]> {
const depositEvents = await queryDepositEventsInWindow(eventClient, depositId, slot, secondsLookback);

// Filter for all matching deposit events
const matchingEvents = depositEvents.filter((event) =>
depositId.eq((event.data as unknown as { depositId: BigNumber }).depositId)
);

// Return all deposit events with block info
return matchingEvents.map((event) => ({
txnRef: event.signature.toString(),
blockNumber: Number(event.slot),
txnIndex: 0,
logIndex: 0,
...(unwrapEventData(event.data) as Record<string, unknown>),
})) as DepositWithBlock[];
}

/**
* Resolves the fill status of a deposit at a specific slot or at the current confirmed one.
*
Expand Down
122 changes: 101 additions & 21 deletions src/clients/SpokePoolClient/EVMSpokePoolClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {
relayFillStatus,
getTimestampForBlock as _getTimestampForBlock,
} from "../../arch/evm";
import { DepositWithBlock, FillStatus, RelayData } from "../../interfaces";
import { DepositWithBlock, FillStatus, Log, RelayData } from "../../interfaces";
import {
BigNumber,
DepositSearchResult,
Expand All @@ -17,6 +17,7 @@ import {
toBN,
EvmAddress,
toAddressType,
MultipleDepositSearchResult,
} from "../../utils";
import {
EventSearchConfig,
Expand Down Expand Up @@ -148,28 +149,25 @@ export class EVMSpokePoolClient extends SpokePoolClient {
return _getTimeAt(this.spokePool, blockNumber);
}

public override async findDeposit(depositId: BigNumber): Promise<DepositSearchResult> {
let deposit = this.getDeposit(depositId);
if (deposit) {
return { found: true, deposit };
}

// No deposit found; revert to searching for it.
const upperBound = this.latestHeightSearched || undefined; // Don't permit block 0 as the high block.
private async queryDepositEvents(
depositId: BigNumber
): Promise<{ events: Log[]; from: number; elapsedMs: number } | { reason: string }> {
const tStart = Date.now();
const upperBound = this.latestHeightSearched || undefined;
const from = await findDepositBlock(this.spokePool, depositId, this.deploymentBlock, upperBound);
const chain = getNetworkName(this.chainId);

if (!from) {
const reason =
`Unable to find ${chain} depositId ${depositId}` +
` within blocks [${this.deploymentBlock}, ${upperBound ?? "latest"}].`;
return { found: false, code: InvalidFill.DepositIdNotFound, reason };
return {
reason: `Unable to find ${chain} depositId ${depositId} within blocks [${this.deploymentBlock}, ${
upperBound ?? "latest"
}].`,
};
}

const to = from;
const tStart = Date.now();
// Check both V3FundsDeposited and FundsDeposited events to look for a specified depositId.
const { maxLookBack } = this.eventSearchConfig;
const query = (
const events = (
await Promise.all([
paginatedEventQuery(
this.spokePool,
Expand All @@ -182,15 +180,35 @@ export class EVMSpokePoolClient extends SpokePoolClient {
{ from, to, maxLookBack }
),
])
).flat();
)
.flat()
.filter(({ args }) => args["depositId"].eq(depositId));

const tStop = Date.now();
return { events, from, elapsedMs: tStop - tStart };
}

public override async findDeposit(depositId: BigNumber): Promise<DepositSearchResult> {
let deposit = this.getDeposit(depositId);
if (deposit) {
return { found: true, deposit };
}

// No deposit found; revert to searching for it.
const result = await this.queryDepositEvents(depositId);

if ("reason" in result) {
return { found: false, code: InvalidFill.DepositIdNotFound, reason: result.reason };
}

const { events: query, from, elapsedMs } = result;

const event = query.find(({ args }) => args["depositId"].eq(depositId));
if (event === undefined) {
return {
found: false,
code: InvalidFill.DepositIdNotFound,
reason: `${chain} depositId ${depositId} not found at block ${from}.`,
reason: `${getNetworkName(this.chainId)} depositId ${depositId} not found at block ${from}.`,
};
}

Expand All @@ -206,23 +224,85 @@ export class EVMSpokePoolClient extends SpokePoolClient {
fromLiteChain: true, // To be updated immediately afterwards.
toLiteChain: true, // To be updated immediately afterwards.
} as DepositWithBlock;

if (deposit.outputToken.isZeroAddress()) {
deposit.outputToken = this.getDestinationTokenForDeposit(deposit);
}
deposit.fromLiteChain = this.isOriginLiteChain(deposit);
deposit.toLiteChain = this.isDestinationLiteChain(deposit);

this.logger.debug({
at: "SpokePoolClient#findDeposit",
message: "Located deposit outside of SpokePoolClient's search range",
deposit,
elapsedMs: tStop - tStart,
elapsedMs,
});

return { found: true, deposit };
}

public override async findAllDeposits(depositId: BigNumber): Promise<MultipleDepositSearchResult> {
// First check memory for deposits
let deposits = this.getDepositsForDepositId(depositId);
if (deposits.length > 0) {
return { found: true, deposits };
}

// If no deposits found in memory, try to find on-chain
const result = await this.queryDepositEvents(depositId);
if ("reason" in result) {
return { found: false, code: InvalidFill.DepositIdNotFound, reason: result.reason };
}

const { events, elapsedMs } = result;

if (events.length === 0) {
return {
found: false,
code: InvalidFill.DepositIdNotFound,
reason: `${getNetworkName(this.chainId)} depositId ${depositId} not found at block ${result.from}.`,
};
}

// First do all synchronous operations
deposits = events.map((event) => {
const deposit = {
...spreadEventWithBlockNumber(event),
inputToken: toAddressType(event.args.inputToken, event.args.originChainId),
outputToken: toAddressType(event.args.outputToken, event.args.destinationChainId),
depositor: toAddressType(event.args.depositor, this.chainId),
recipient: toAddressType(event.args.recipient, event.args.destinationChainId),
exclusiveRelayer: toAddressType(event.args.exclusiveRelayer, event.args.destinationChainId),
originChainId: this.chainId,
fromLiteChain: true, // To be updated immediately afterwards.
toLiteChain: true, // To be updated immediately afterwards.
} as DepositWithBlock;

if (deposit.outputToken.isZeroAddress()) {
deposit.outputToken = this.getDestinationTokenForDeposit(deposit);
}
deposit.fromLiteChain = this.isOriginLiteChain(deposit);
deposit.toLiteChain = this.isDestinationLiteChain(deposit);

return deposit;
});

// Then do all async operations in parallel
deposits = await Promise.all(
deposits.map(async (deposit) => ({
...deposit,
quoteBlockNumber: await this.getBlockNumber(Number(deposit.quoteTimestamp)),
}))
);

this.logger.debug({
at: "SpokePoolClient#findAllDeposits",
message: "Located deposits outside of SpokePoolClient's search range",
deposits: deposits,
elapsedMs,
});

return { found: true, deposits };
}

public override getTimestampForBlock(blockNumber: number): Promise<number> {
return _getTimestampForBlock(this.spokePool.provider, blockNumber);
}
Expand Down
Loading