Skip to content

feature: Get all Invalid Fills #1085

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 18 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
114 changes: 96 additions & 18 deletions src/arch/svm/SpokeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import {
getStatePda,
unwrapEventData,
} from "./";
import { SVMEventNames, SVMProvider } from "./types";
import { EventWithData, SVMEventNames, SVMProvider } from "./types";

/**
* @note: Average Solana slot duration is about 400-500ms. We can be conservative
Expand Down Expand Up @@ -74,6 +74,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 currentSlot = await provider.getSlot({ commitment: "confirmed" }).send();

// 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 Down Expand Up @@ -110,24 +144,10 @@ 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 currentSlot = await provider.getSlot({ commitment: "confirmed" }).send();

// 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;
const depositEvents = await queryDepositEventsInWindow(eventClient, depositId, slot, secondsLookback);

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

Expand All @@ -146,6 +166,64 @@ export async function findDeposit(
} as DepositWithBlock;
}

/**
* Finds all deposit events within a 2-day window 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.
*
* @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)
);

// If no deposit events are found, return empty array
if (!matchingEvents || matchingEvents.length === 0) {
return [];
}

// 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
112 changes: 95 additions & 17 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 {
MakeOptional,
toBN,
EvmAddress,
MultipleDepositSearchResult,
} from "../../utils";
import {
EventSearchConfig,
Expand Down Expand Up @@ -146,28 +147,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; chain: string; 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 @@ -181,7 +179,25 @@ export class EVMSpokePoolClient extends SpokePoolClient {
),
])
).flat();

const tStop = Date.now();
return { events, from, chain, 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, chain, elapsedMs } = result;

const event = query.find(({ args }) => args["depositId"].eq(depositId));
if (event === undefined) {
Expand Down Expand Up @@ -210,12 +226,74 @@ export class EVMSpokePoolClient extends SpokePoolClient {
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: 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: query, chain, elapsedMs } = result;

// Find all events with matching depositId
const events = query.filter(({ args }) => args["depositId"].eq(depositId));

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

// First do all synchronous operations
deposits = events.map((event) => {
const deposit = {
...spreadEventWithBlockNumber(event),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This PR looks fine to me. I'd prefer if we can merge this after we do the address migration though. Once we do that, you'd need to manually cast the address args here (like depositor, recipient, etc.) to an Address type.

originChainId: this.chainId,
fromLiteChain: true,
toLiteChain: true,
} as DepositWithBlock;

if (isZeroAddress(deposit.outputToken)) {
deposit.outputToken = this.getDestinationTokenForDeposit(deposit);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fwiw I think this needs to be re-worked following the Address class updates that were merged on Friday.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: deposits };
}

public override getTimestampForBlock(blockNumber: number): Promise<number> {
return _getTimestampForBlock(this.spokePool.provider, blockNumber);
}
Expand Down
39 changes: 38 additions & 1 deletion src/clients/SpokePoolClient/SVMSpokePoolClient.ts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@melisaguevara @bmzig You're both strong on the SVMSpokePoolClient - possible to take a pass over this file?

Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,22 @@ import {
relayFillStatus,
fillStatusArray,
} from "../../arch/svm";
import { FillStatus, RelayData, SortableEvent } from "../../interfaces";
import { DepositWithBlock, FillStatus, RelayData, SortableEvent } from "../../interfaces";
import {
BigNumber,
DepositSearchResult,
EventSearchConfig,
InvalidFill,
isZeroAddress,
MakeOptional,
MultipleDepositSearchResult,
sortEventsAscendingInPlace,
SvmAddress,
} from "../../utils";
import { isUpdateFailureReason } from "../BaseAbstractClient";
import { HubPoolClient } from "../HubPoolClient";
import { knownEventNames, SpokePoolClient, SpokePoolUpdate } from "./SpokePoolClient";
import { findAllDeposits } from "../../arch/svm/SpokeUtils";

/**
* SvmSpokePoolClient is a client for the SVM SpokePool program. It extends the base SpokePoolClient
Expand Down Expand Up @@ -231,6 +233,41 @@ export class SVMSpokePoolClient extends SpokePoolClient {
};
}

public override async findAllDeposits(depositId: BigNumber): Promise<MultipleDepositSearchResult> {
// TODO: Should we have something like this? In findDeposit we don't look in memory.
// // First check memory for deposits
// const memoryDeposits = this.getDepositsForDepositId(depositId);
// if (memoryDeposits.length > 0) {
// return { found: true, deposits: memoryDeposits };
// }

// If no deposits found in memory, try to find on-chain
const deposits = await findAllDeposits(this.svmEventsClient, depositId);
if (!deposits || deposits.length === 0) {
return {
found: false,
code: InvalidFill.DepositIdNotFound,
reason: `Deposit with ID ${depositId} not found`,
};
}

// Enrich all deposits with additional information
const enrichedDeposits = await Promise.all(
deposits.map(async (deposit: DepositWithBlock) => ({
...deposit,
quoteBlockNumber: await this.getBlockNumber(Number(deposit.quoteTimestamp)),
originChainId: this.chainId,
fromLiteChain: this.isOriginLiteChain(deposit),
toLiteChain: this.isDestinationLiteChain(deposit),
outputToken: isZeroAddress(deposit.outputToken)
? this.getDestinationTokenForDeposit(deposit)
: deposit.outputToken,
}))
);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@dijanin-brat ooc, should this be 1:1 with the EVM implementation?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

They work with 2 different types of data (EVM has Log and SVM has DepositWithBlock). In SVM we are just adding values for few more fields, in EVM we are creating whole new structure. I guess this can be refactored in a way that both EVM and SVM use the same functiom/method for this. Do you think that should be done?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For follow-up after this PR, yeah. I'm pretty sure they should using the same underlying types, since DepositWithBlock is the product of processing a Log type. So the fact that these are different hints at some unexpected asymmetry between the implementations.


return { found: true, deposits: enrichedDeposits };
}

/**
* Retrieves the fill status for a given relay data from the SVM chain.
*/
Expand Down
Loading