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
2 changes: 2 additions & 0 deletions Anchor.toml
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ generateExternalTypes = "NODE_NO_WARNINGS=1 yarn run ts-node ./scripts/svm/gener
fakeFillWithRandomDistribution = "NODE_NO_WARNINGS=1 yarn run ts-node ./scripts/svm/fakeFillWithRandomDistribution.ts"
addressToPublicKey = "NODE_NO_WARNINGS=1 yarn run ts-node ./scripts/svm/addressToPublicKey.ts"
publicKeyToAddress = "NODE_NO_WARNINGS=1 yarn run ts-node ./scripts/svm/publicKeyToAddress.ts"
findFillStatusPdaFromEvent = "NODE_NO_WARNINGS=1 yarn run ts-node ./scripts/svm/findFillStatusPdaFromEvent.ts"
findFillStatusFromFillStatusPda = "NODE_NO_WARNINGS=1 yarn run ts-node ./scripts/svm/findFillStatusFromFillStatusPda.ts"

[test.validator]
url = "https://api.mainnet-beta.solana.com"
Expand Down
62 changes: 62 additions & 0 deletions scripts/svm/findFillStatusFromFillStatusPda.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// This script finds the fillStatus (fillStatus + event) from a provided fillStatusPda.
import * as anchor from "@coral-xyz/anchor";
import { AnchorProvider, BN, Program } from "@coral-xyz/anchor";
import { address, createSolanaRpc } from "@solana/web3-v2.js";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
import { SvmSpokeIdl } from "../../src/svm";

import { readFillEventFromFillStatusPda } from "../../src/svm/web3-v2/solanaProgramUtils";
import { program } from "@coral-xyz/anchor/dist/cjs/native/system";
import { SvmSpoke } from "../../target/types/svm_spoke";

// Set up the provider
const provider = AnchorProvider.env();
anchor.setProvider(provider);

const argv = yargs(hideBin(process.argv))
.option("fillStatusPda", { type: "string", demandOption: true, describe: "Fill Status PDA" })
.option("programId", { type: "string", demandOption: true, describe: "SvmSpoke ID" }).argv;

async function findFillStatusFromFillStatusPda(): Promise<void> {
const resolvedArgv = await argv;
const fillStatusPda = address(resolvedArgv.fillStatusPda);

console.log(`Looking for Fill Event for Fill Status PDA: ${fillStatusPda.toString()}`);

const rpc = createSolanaRpc(provider.connection.rpcEndpoint);
Copy link
Member

Choose a reason for hiding this comment

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

Does this only work on certain "archive"-ish rpc's?

Copy link
Member Author

Choose a reason for hiding this comment

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

I used this syntax as it's from web3-v2 (now just known as kit) which is what the bots will be using. it's meant to be illustrative for how those clients can injest this data.

const { event, slot } = await readFillEventFromFillStatusPda(
rpc,
fillStatusPda,
address(resolvedArgv.programId),
SvmSpokeIdl
);
if (!event) {
console.log("No fill events found");
return;
}

console.table(
Object.entries(event.data).map(([key, value]) => {
if (key === "relay_execution_info") {
const info = value as any;
return { Property: key, Value: `relayer: ${info.relayer}, executionTimestamp: ${info.executionTimestamp}` };
}
return { Property: key, Value: (value as any).toString() };
})
);

const program = anchor.workspace.SvmSpoke as Program<SvmSpoke>;
let fillStatus;
try {
const fillStatusResponse = await program.account.fillStatusAccount.fetch(fillStatusPda);
fillStatus = Object.keys(fillStatusResponse.status)[0];
} catch (error) {
fillStatus = "filled";
}

console.log("fillStatus", fillStatus);
console.log("slot", slot);
}

findFillStatusFromFillStatusPda();
84 changes: 84 additions & 0 deletions scripts/svm/findFillStatusPdaFromEvent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
// This script finds the associated Fill Status PDA from a fill OR deposit event by re-deriving it without doing any
// // on-chain calls. Note the props required are present in both deposit and fill events.
// Example usage:
// anchor run findFillStatusPdaFromFill -- \
// --input_token "0x1c7d4b196cb0c7b01d743fbc6116a902379c7238" \
// --output_token "wBeYLVBabtv4cyb7RyMmRxvRSkRsCP4PMBCJRw66kKC" \
// --input_amount "1" \
// --output_amount "1" \
// --repayment_chain_id "133268194659241" \
// --origin_chain_id "11155111" \
// --deposit_id "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4,98" \
// --fill_deadline 1740569770 \
// --exclusivity_deadline 1740569740 \
// --exclusive_relayer "0x0000000000000000000000000000000000000000" \
// --depositor "0x9a8f92a830a5cb89a3816e3d267cb7791c16b04d" \
// --recipient "5HRmK3G6BzWAtF22dBgoTiPGVovSmG4rLvVQoUhum9FJ" \
// --message_hash "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0"

import * as anchor from "@coral-xyz/anchor";
import { PublicKey } from "@solana/web3.js";
import { BN } from "@coral-xyz/anchor";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
import { calculateRelayEventHashUint8Array, getSpokePoolProgram, evmAddressToPublicKey } from "../../src/svm/web3-v1";

// Set up the provider
const provider = anchor.AnchorProvider.env();
anchor.setProvider(provider);
const program = getSpokePoolProgram(provider);
const programId = program.programId;

// Parse arguments
const argv = yargs(hideBin(process.argv))
.option("input_token", { type: "string", demandOption: true, describe: "Input token address" })
.option("output_token", { type: "string", demandOption: true, describe: "Output token address" })
.option("input_amount", { type: "string", demandOption: true, describe: "Input amount" })
.option("output_amount", { type: "string", demandOption: true, describe: "Output amount" })
.option("repayment_chain_id", { type: "string", demandOption: true, describe: "Repayment chain ID" })
.option("origin_chain_id", { type: "string", demandOption: true, describe: "Origin chain ID" })
.option("deposit_id", { type: "string", demandOption: true, describe: "Deposit ID" })
.option("fill_deadline", { type: "number", demandOption: true, describe: "Fill deadline" })
.option("exclusivity_deadline", { type: "number", demandOption: true, describe: "Exclusivity deadline" })
.option("exclusive_relayer", { type: "string", demandOption: true, describe: "Exclusive relayer address" })
.option("depositor", { type: "string", demandOption: true, describe: "Depositor address" })
.option("recipient", { type: "string", demandOption: true, describe: "Recipient address" })
.option("message_hash", { type: "string", demandOption: true, describe: "Message hash" }).argv;

async function findFillStatusPda() {
const resolvedArgv = await argv;
const relayEventData = {
depositor: convertAddress(resolvedArgv.depositor),
recipient: convertAddress(resolvedArgv.recipient),
exclusiveRelayer: convertAddress(resolvedArgv.exclusive_relayer),
inputToken: convertAddress(resolvedArgv.input_token),
outputToken: convertAddress(resolvedArgv.output_token),
inputAmount: new BN(resolvedArgv.input_amount),
outputAmount: new BN(resolvedArgv.output_amount),
originChainId: new BN(resolvedArgv.origin_chain_id),
depositId: parseStringToUint8Array(resolvedArgv.deposit_id),
fillDeadline: resolvedArgv.fill_deadline,
exclusivityDeadline: resolvedArgv.exclusivity_deadline,
messageHash: parseStringToUint8Array(resolvedArgv.message_hash),
};

console.log("finding fill status pda for relay event data:");
console.table(Object.entries(relayEventData).map(([key, value]) => ({ Property: key, Value: value.toString() })));

const chainId = new BN(resolvedArgv.repayment_chain_id);
const relayHashUint8Array = calculateRelayEventHashUint8Array(relayEventData, chainId);
const [fillStatusPda] = PublicKey.findProgramAddressSync([Buffer.from("fills"), relayHashUint8Array], programId);
console.log("Fill Status PDA Address:", fillStatusPda.toString());
}

findFillStatusPda().catch(console.error);

function convertAddress(address: string) {
if (address.startsWith("0x")) return evmAddressToPublicKey(address);
return new PublicKey(address);
}

function parseStringToUint8Array(inputString: string): Uint8Array {
const numberArray = inputString.split(",").map(Number);
return new Uint8Array(numberArray);
}
54 changes: 40 additions & 14 deletions src/svm/web3-v2/solanaProgramUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,20 +24,7 @@ export async function readProgramEvents(
finality: Commitment = "confirmed",
options: GetSignaturesForAddressConfig = { limit: 1000 }
) {
const allSignatures: GetSignaturesForAddressTransaction[] = [];

// Fetch all signatures in sequential batches
while (true) {
const signatures = await rpc.getSignaturesForAddress(program, options).send();
allSignatures.push(...signatures);

// Update options for the next batch. Set before to the last fetched signature.
if (signatures.length > 0) {
options = { ...options, before: signatures[signatures.length - 1].signature };
}

if (options.limit && signatures.length < options.limit) break; // Exit early if the number of signatures < limit
}
const allSignatures: GetSignaturesForAddressTransaction[] = await searchSignaturesUntilLimit(rpc, program, options);

// Fetch events for all signatures in parallel
const eventsWithSlots = await Promise.all(
Expand All @@ -57,6 +44,27 @@ export async function readProgramEvents(
return eventsWithSlots.flat();
}

async function searchSignaturesUntilLimit(
rpc: web3.Rpc<web3.SolanaRpcApiFromTransport<RpcTransport>>,
program: Address,
options: GetSignaturesForAddressConfig = { limit: 1000 }
): Promise<GetSignaturesForAddressTransaction[]> {
const allSignatures: GetSignaturesForAddressTransaction[] = [];
// Fetch all signatures in sequential batches
while (true) {
const signatures = await rpc.getSignaturesForAddress(program, options).send();
allSignatures.push(...signatures);

// Update options for the next batch. Set before to the last fetched signature.
if (signatures.length > 0) {
options = { ...options, before: signatures[signatures.length - 1].signature };
}

if (options.limit && signatures.length < options.limit) break; // Exit early if the number of signatures < limit
}
return allSignatures;
}

/**
* Reads events from a transaction.
*/
Expand Down Expand Up @@ -119,3 +127,21 @@ async function processEventFromTx(

return events;
}

/**
* For a given fillStatusPDa & associated spokePool ProgramID, return the fill event.
*/
export async function readFillEventFromFillStatusPda(
rpc: web3.Rpc<web3.SolanaRpcApiFromTransport<RpcTransport>>,
fillStatusPda: Address,
programId: Address,
programIdl: Idl
): Promise<{ event: any; slot: number }> {
const signatures = await searchSignaturesUntilLimit(rpc, fillStatusPda);
if (signatures.length === 0) return { event: null, slot: 0 };

// The first signature will always be PDA creation, and therefore CPI event carrying signature. Any older signatures
// will therefore be either spam or PDA closure signatures and can be ignored when looking for the fill event.
const events = await readEvents(rpc, signatures[signatures.length - 1].signature, programId, programIdl);
return { event: events[0], slot: Number(signatures[signatures.length - 1].slot) };
}
Loading