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 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
115 changes: 95 additions & 20 deletions src/arch/svm/SpokeUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ import {
toAddress,
unwrapEventData,
} from "./";
import { EventWithData, SVMEventNames, SVMProvider } from "./types";
import { CHAIN_IDs } from "../../constants";
import { SVMEventNames, SVMProvider } from "./types";

/**
* @note: Average Solana slot duration is about 400-500ms. We can be conservative
Expand Down Expand Up @@ -94,7 +94,41 @@ export function getDepositIdAtBlock(_contract: unknown, _blockTag: number): Prom
}

/**
* Finds deposit events within a 2-day window ending at the specified slot.
* 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 find historical deposit for unsafe deposit ID ${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 time window (default 2 days) ending at the specified slot.
*
* @remarks
* This implementation uses a slot-limited search approach because Solana PDA state has
Expand All @@ -114,7 +148,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 @@ -129,24 +164,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 @@ -172,6 +193,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
120 changes: 101 additions & 19 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 @@ -16,6 +16,7 @@ import {
MakeOptional,
toBN,
EvmAddress,
MultipleDepositSearchResult,
toAddressType,
} from "../../utils";
import {
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; 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 @@ -180,15 +178,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 @@ -215,12 +233,76 @@ 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 };
}

// 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),
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.

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
40 changes: 39 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,19 +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,
getNetworkName,
InvalidFill,
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 @@ -228,6 +231,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: `${getNetworkName(this.chainId)} 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: deposit.outputToken.isZeroAddress()
? this.getDestinationTokenForDeposit(deposit)
: deposit.outputToken,
}))
);

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

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