-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy patheventsClient.ts
216 lines (193 loc) · 8.19 KB
/
eventsClient.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import { getDeployedAddress, SvmSpokeIdl } from "@across-protocol/contracts";
import { getSolanaChainId } from "@across-protocol/contracts/dist/src/svm/web3-v1";
import web3, {
Address,
Commitment,
GetSignaturesForAddressApi,
GetTransactionApi,
RpcTransport,
Signature,
} from "@solana/kit";
import { bs58 } from "../../utils";
import { EventData, EventName, EventWithData } from "./types";
import { decodeEvent, isDevnet } from "./utils";
import { getSlotForBlock } from "./SpokeUtils";
// Utility type to extract the return type for the JSON encoding overload. We only care about the overload where the
// configuration parameter (C) has the optional property 'encoding' set to 'json'.
type ExtractJsonOverload<T> = T extends (signature: infer _S, config: infer C) => infer R
? C extends { encoding?: "json" }
? R
: never
: never;
type GetTransactionReturnType = ExtractJsonOverload<GetTransactionApi["getTransaction"]>;
type GetSignaturesForAddressConfig = Parameters<GetSignaturesForAddressApi["getSignaturesForAddress"]>[1];
type GetSignaturesForAddressTransaction = ReturnType<GetSignaturesForAddressApi["getSignaturesForAddress"]>[number];
type GetSignaturesForAddressApiResponse = readonly GetSignaturesForAddressTransaction[];
export class SvmSpokeEventsClient {
private rpc: web3.Rpc<web3.SolanaRpcApiFromTransport<RpcTransport>>;
private svmSpokeAddress: Address;
private svmSpokeEventAuthority: Address;
/**
* Private constructor. Use the async create() method to instantiate.
*/
private constructor(
rpc: web3.Rpc<web3.SolanaRpcApiFromTransport<RpcTransport>>,
svmSpokeAddress: Address,
eventAuthority: Address
) {
this.rpc = rpc;
this.svmSpokeAddress = svmSpokeAddress;
this.svmSpokeEventAuthority = eventAuthority;
}
/**
* Factory method to asynchronously create an instance of SvmSpokeEventsClient.
*/
public static async create(
rpc: web3.Rpc<web3.SolanaRpcApiFromTransport<RpcTransport>>
): Promise<SvmSpokeEventsClient> {
const isTestnet = await isDevnet(rpc);
const programId = getDeployedAddress("SvmSpoke", getSolanaChainId(isTestnet ? "devnet" : "mainnet").toString());
if (!programId) throw new Error("Program not found");
const svmSpokeAddress = web3.address(programId);
const [svmSpokeEventAuthority] = await web3.getProgramDerivedAddress({
programAddress: svmSpokeAddress,
seeds: ["__event_authority"],
});
return new SvmSpokeEventsClient(rpc, svmSpokeAddress, svmSpokeEventAuthority);
}
/**
* Queries events for the SvmSpoke program filtered by event name.
*
* @param eventName - The name of the event to filter by.
* @param fromBlock - Optional starting block.
* @param toBlock - Optional ending block.
* @param options - Options for fetching signatures.
* @returns A promise that resolves to an array of events matching the eventName.
*/
public async queryEvents<T extends EventData>(
eventName: EventName,
fromBlock?: bigint,
toBlock?: bigint,
options: GetSignaturesForAddressConfig = { limit: 1000, commitment: "confirmed" }
): Promise<EventWithData<T>[]> {
const events = await this.queryAllEvents(fromBlock, toBlock, options);
return events.filter((event) => event.name === eventName) as EventWithData<T>[];
}
/**
* Queries all events for a specific program.
*
* @param fromBlock - Optional starting block.
* @param toBlock - Optional ending block.
* @param options - Options for fetching signatures.
* @returns A promise that resolves to an array of all events with additional metadata.
*/
private async queryAllEvents(
fromBlock?: bigint,
toBlock?: bigint,
options: GetSignaturesForAddressConfig = { limit: 1000, commitment: "confirmed" }
): Promise<EventWithData<EventData>[]> {
const allSignatures: GetSignaturesForAddressTransaction[] = [];
let hasMoreSignatures = true;
let currentOptions = options;
let fromSlot: bigint | undefined;
let toSlot: bigint | undefined;
if (fromBlock) {
const slot = await getSlotForBlock(this.rpc, fromBlock, BigInt(0));
fromSlot = slot;
}
if (toBlock) {
const slot = await getSlotForBlock(this.rpc, toBlock, BigInt(0));
toSlot = slot;
}
while (hasMoreSignatures) {
const signatures: GetSignaturesForAddressApiResponse = await this.rpc
.getSignaturesForAddress(this.svmSpokeAddress, currentOptions)
.send();
// Signatures are sorted by slot in descending order.
allSignatures.push(...signatures);
// Update options for the next batch. Set "before" to the last fetched signature.
if (signatures.length > 0) {
currentOptions = { ...currentOptions, before: signatures[signatures.length - 1].signature };
}
if (fromSlot && allSignatures.length > 0 && allSignatures[allSignatures.length - 1].slot < fromSlot) {
hasMoreSignatures = false;
}
hasMoreSignatures = Boolean(
hasMoreSignatures && currentOptions.limit && signatures.length === currentOptions.limit
);
}
const filteredSignatures = allSignatures.filter((signatureTransaction) => {
if (fromSlot && signatureTransaction.slot < fromSlot) return false;
if (toSlot && signatureTransaction.slot > toSlot) return false;
return true;
});
// Fetch events for all signatures in parallel.
const eventsWithSlots = await Promise.all(
filteredSignatures.map(async (signatureTransaction) => {
const events = await this.readEventsFromSignature(signatureTransaction.signature, options.commitment);
return events.map((event) => ({
...event,
confirmationStatus: signatureTransaction.confirmationStatus,
blockTime: signatureTransaction.blockTime,
signature: signatureTransaction.signature,
slot: signatureTransaction.slot,
}));
})
);
return eventsWithSlots.flat();
}
/**
* Reads events from a transaction signature.
*
* @param txSignature - The transaction signature.
* @param commitment - Commitment level.
* @returns A promise that resolves to an array of events.
*/
private async readEventsFromSignature(txSignature: Signature, commitment: Commitment = "confirmed") {
const txResult = await this.rpc
.getTransaction(txSignature, { commitment, maxSupportedTransactionVersion: 0 })
.send();
if (txResult === null) return [];
return this.processEventFromTx(txResult);
}
/**
* Processes events from a transaction.
*
* @param txResult - The transaction result.
* @returns A promise that resolves to an array of events with their data and name.
*/
private processEventFromTx(
txResult: GetTransactionReturnType
): { program: Address; data: EventData; name: EventName }[] {
if (!txResult) return [];
const events: { program: Address; data: EventData; name: EventName }[] = [];
const accountKeys = txResult.transaction.message.accountKeys;
const messageAccountKeys = [...accountKeys];
// Writable accounts come first, then readonly.
// See https://docs.anza.xyz/proposals/versioned-transactions#new-transaction-format
messageAccountKeys.push(...(txResult?.meta?.loadedAddresses?.writable ?? []));
messageAccountKeys.push(...(txResult?.meta?.loadedAddresses?.readonly ?? []));
for (const ixBlock of txResult.meta?.innerInstructions ?? []) {
for (const ix of ixBlock.instructions) {
const ixProgramId = messageAccountKeys[ix.programIdIndex];
const singleIxAccount = ix.accounts.length === 1 ? messageAccountKeys[ix.accounts[0]] : undefined;
if (
ixProgramId !== undefined &&
singleIxAccount !== undefined &&
this.svmSpokeAddress === ixProgramId &&
this.svmSpokeEventAuthority === singleIxAccount
) {
const ixData = bs58.decode(ix.data);
// Skip the first 8 bytes (assumed header) and encode the rest.
const eventData = Buffer.from(ixData.slice(8)).toString("base64");
const { name, data } = decodeEvent(SvmSpokeIdl, eventData);
events.push({ program: this.svmSpokeAddress, name, data });
}
}
}
return events;
}
public getSvmSpokeAddress(): Address {
return this.svmSpokeAddress;
}
}