-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathSVMSpokePoolClient.ts
222 lines (200 loc) · 8.16 KB
/
SVMSpokePoolClient.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
217
218
219
220
221
222
import winston from "winston";
import { Address, Rpc, SolanaRpcApiFromTransport, RpcTransport } from "@solana/kit";
import {
SvmSpokeEventsClient,
SVMEventNames,
getFillDeadline,
getTimestampForBlock,
getStatePda,
unwrapEventData,
relayFillStatus,
} from "../../arch/svm";
import { FillStatus, RelayData, SortableEvent } from "../../interfaces";
import {
BigNumber,
bs58,
DepositSearchResult,
EventSearchConfig,
MakeOptional,
sortEventsAscendingInPlace,
toBN,
} from "../../utils";
import { isUpdateFailureReason } from "../BaseAbstractClient";
import { HubPoolClient } from "../HubPoolClient";
import { knownEventNames, SpokePoolClient, SpokePoolUpdate } from "./SpokePoolClient";
/**
* SvmSpokePoolClient is a client for the SVM SpokePool program. It extends the base SpokePoolClient
* and implements the abstract methods required for interacting with an SVM Spoke Pool.
*/
export class SvmSpokePoolClient extends SpokePoolClient {
/**
* Private constructor. Use the async create() method to instantiate.
*/
private constructor(
logger: winston.Logger,
hubPoolClient: HubPoolClient | null,
chainId: number,
deploymentSlot: bigint, // Using slot instead of block number for SVM
eventSearchConfig: MakeOptional<EventSearchConfig, "toBlock">,
public programId: Address,
protected statePda: Address,
public svmEventsClient: SvmSpokeEventsClient,
public rpc: Rpc<SolanaRpcApiFromTransport<RpcTransport>>
) {
// Convert deploymentSlot to number for base class, might need refinement
super(logger, hubPoolClient, chainId, Number(deploymentSlot), eventSearchConfig);
}
/**
* Factory method to asynchronously create an instance of SvmSpokePoolClient.
*/
public static async create(
logger: winston.Logger,
hubPoolClient: HubPoolClient | null,
chainId: number,
deploymentSlot: bigint,
eventSearchConfig: MakeOptional<EventSearchConfig, "toBlock"> = { fromBlock: 0, maxBlockLookBack: 0 }, // Provide default
rpc: Rpc<SolanaRpcApiFromTransport<RpcTransport>>
): Promise<SvmSpokePoolClient> {
const svmEventsClient = await SvmSpokeEventsClient.create(rpc);
const programId = svmEventsClient.getSvmSpokeAddress();
const statePda = await getStatePda(programId);
return new SvmSpokePoolClient(
logger,
hubPoolClient,
chainId,
deploymentSlot,
eventSearchConfig,
programId,
statePda,
svmEventsClient,
rpc
);
}
public _queryableEventNames(): string[] {
// We want to take the internal event names relevant to
// the SVM SpokePoolClient and filter them against the
// knownEventNames list that we reference in practice
const internalEventNames = Object.values(SVMEventNames);
return internalEventNames.filter((e) => knownEventNames.includes(e));
}
/**
* Performs an update to refresh the state of this client by querying SVM events.
*/
protected async _update(eventsToQuery: string[]): Promise<SpokePoolUpdate> {
const searchConfig = await this.updateSearchConfig(this.rpc);
if (isUpdateFailureReason(searchConfig)) {
const reason = searchConfig;
return { success: false, reason };
}
const eventSearchConfigs = eventsToQuery.map((eventName) => {
if (!this._queryableEventNames().includes(eventName)) {
throw new Error(`SpokePoolClient: Cannot query unrecognised SpokePool event name: ${eventName}`);
}
const _searchConfig = { ...searchConfig }; // shallow copy
// By default, an event's query range is controlled by the `eventSearchConfig` passed in during instantiation.
// However, certain events have special overriding requirements to their search ranges:
// - EnabledDepositRoute: The full history is always required, so override the requested fromBlock.
if (eventName === "EnabledDepositRoute" && !this.isUpdated) {
_searchConfig.fromBlock = this.deploymentBlock;
}
return _searchConfig as EventSearchConfig;
});
const spokePoolAddress = this.svmEventsClient.getSvmSpokeAddress();
this.log("debug", `Updating SpokePool client for chain ${this.chainId}`, {
eventsToQuery,
searchConfig,
spokePool: spokePoolAddress,
});
const timerStart = Date.now();
const [_currentTime, ...eventsQueried] = await Promise.all([
this.rpc.getBlockTime(BigInt(searchConfig.toBlock)).send(),
...eventsToQuery.map(async (eventName, idx) => {
const config = eventSearchConfigs[idx];
const events = await this.svmEventsClient.queryEvents(
eventName as SVMEventNames,
BigInt(config.fromBlock),
BigInt(config.toBlock)
);
return Promise.all(
events.map(async (event): Promise<SortableEvent> => {
const block = await this.rpc.getBlock(event.slot, { maxSupportedTransactionVersion: 0 }).send();
if (!block) {
this.log("error", `SpokePoolClient::update: Failed to get block for slot ${event.slot}`);
throw new Error(`SpokePoolClient::update: Failed to get block for slot ${event.slot}`);
}
return {
transactionHash: `0x${Buffer.from(bs58.decode(event.signature)).toString("hex")}`,
blockNumber: Number(block.blockHeight),
transactionIndex: 0,
logIndex: 0,
...(unwrapEventData(event.data) as Record<string, unknown>),
};
})
);
}),
]);
const currentTime = toBN(_currentTime.toString());
this.log("debug", `Time to query new events from RPC for ${this.chainId}: ${Date.now() - timerStart} ms`);
if (!BigNumber.isBigNumber(currentTime) || currentTime.lt(this.currentTime)) {
const errMsg = BigNumber.isBigNumber(currentTime)
? `currentTime: ${currentTime} < ${toBN(this.currentTime)}`
: `currentTime is not a BigNumber: ${JSON.stringify(currentTime)}`;
throw new Error(`SvmSpokePoolClient::update: ${errMsg}`);
}
// Sort all events to ensure they are stored in a consistent order.
eventsQueried.forEach((events) => sortEventsAscendingInPlace(events));
return {
success: true,
currentTime: currentTime.toNumber(), // uint32
searchEndBlock: searchConfig.toBlock,
events: eventsQueried,
};
}
/**
* Retrieves the fill deadline buffer fetched from the State PDA.
* @note This function assumes that fill deadline buffer is a constant value in svm environments.
*/
public override getMaxFillDeadlineInRange(_startSlot: number, _endSlot: number): Promise<number> {
return getFillDeadline(this.rpc, this.statePda);
}
/**
* Retrieves the timestamp for a given SVM slot number.
*/
public override getTimestampForBlock(blockNumber: number): Promise<number> {
return getTimestampForBlock(this.rpc, blockNumber);
}
/**
* Retrieves the time (timestamp) from the SVM chain state at a particular slot.
*/
public getTimeAt(_slot: number): Promise<number> {
throw new Error("getTimeAt not implemented for SVM");
}
/**
* Finds a deposit based on its deposit ID on the SVM chain.
* TODO: Implement SVM state query for deposit details.
*/
public findDeposit(_depositId: BigNumber): Promise<DepositSearchResult> {
throw new Error("findDeposit not implemented for SVM");
}
/**
* Retrieves the fill status for a given relay data from the SVM chain.
* TODO: Implement SVM state query for fill status.
*/
public override relayFillStatus(
relayData: RelayData,
blockTag: number | "latest",
destinationChainId?: number
): Promise<FillStatus> {
destinationChainId ??= this.chainId;
return relayFillStatus(this.programId, relayData, blockTag, destinationChainId, this.rpc, this.svmEventsClient);
}
/**
* Retrieves the fill status for an array of given relay data.
* @param relayData The array relay data to retrieve the fill status for.
* @param blockTag The block at which to query the fill status.
* @returns The fill status for each of the given relay data.
*/
public fillStatusArray(_relayData: RelayData[], _blockTag?: number | "latest"): Promise<(FillStatus | undefined)[]> {
throw new Error("fillStatusArray not implemented for SVM");
}
}