-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
421 lines (352 loc) · 11.6 KB
/
index.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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
require("log-timestamp");
import { HyperClient, MessageStatusWithMeta } from "@polytope-labs/hyperclient";
import { config } from "dotenv";
import {
createPublicClient,
createWalletClient,
decodeFunctionData,
formatEther,
fromHex,
getContract,
http,
parseAbi,
parseEventLogs,
toHex,
} from "viem";
import { privateKeyToAccount } from "viem/accounts";
import { bscTestnet, optimismSepolia } from "viem/chains";
import { ApiPromise, WsProvider } from "@polkadot/api";
import { Account } from "@ethereumjs/util";
import ERC6160 from "./abis/erc6160";
import PING_MODULE from "./abis/pingModule";
import EVM_HOST from "./abis/evmHost";
import HANDLER from "./abis/handler";
const PING_MODULE_ADDRESS = "0xFE9f23F0F2fE83b8B9576d3FC94e9a7458DdDD35";
/*
Using a viem client, dispatches an onchain transaction to the ping module.
The ping module contract, dispatches an ISMP request to Hyperbridge.
Then tracks the resulting ISMP request using Hyperclient.
*/
async function testPostAndGetRequest() {
const {
bscTestnetClient,
bscFeeToken,
BSC,
OP,
account,
tokenFaucet,
opSepoliaHandler,
bscHandler,
bscPing,
opSepoliaClient,
opSepoliaIsmpHost,
} = await setUp();
const blockNumber = await bscTestnetClient.getBlockNumber();
console.log("Latest block number: ", blockNumber);
let balance = await bscFeeToken.read.balanceOf([account.address as any]);
console.log("FeeToken balance: $", formatEther(balance));
// Get fee tokens from faucet
if (balance === BigInt(0)) {
const hash = await tokenFaucet.write.drip([bscFeeToken.address]);
await bscTestnetClient.waitForTransactionReceipt({
hash,
confirmations: 1,
});
balance = await bscFeeToken.read.balanceOf([account.address as any]);
console.log("New FeeToken balance: $", formatEther(balance));
}
const allowance = await bscFeeToken.read.allowance([account.address!, PING_MODULE_ADDRESS]);
if (allowance === BigInt(0)) {
console.log("Setting allowance .. ");
// set allowance to type(uint256).max
const hash = await bscFeeToken.write.approve([
PING_MODULE_ADDRESS,
fromHex("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff", "bigint"),
]);
await bscTestnetClient.waitForTransactionReceipt({
hash,
confirmations: 1,
});
}
console.log("Setting up hyperclient");
const HyperbridgeConfig = {
// rpc_url: "ws://127.0.0.1:9001",
rpc_url: "wss://hyperbridge-paseo-rpc.blockops.network",
state_machine: "KUSAMA-4009"
};
const hyperclient = await HyperClient.init({
source: BSC,
dest: OP,
hyperbridge: HyperbridgeConfig,
});
// send GetRequest
console.log("\n\nSending Get Request\n\n");
const wsProvider = new WsProvider(HyperbridgeConfig.rpc_url);
const api = await ApiPromise.create({ provider: wsProvider });
const height = (
await api.query.ismp.latestStateMachineHeight({
stateId: {
Evm: 11155420,
},
consensusStateId: "ETH0",
})
).toJSON() as number;
const txHash = await bscPing.write.dispatch([
{
source: "0x",
dest: OP.state_machine,
nonce: 0n,
context: "0x",
from: account.address,
keys: [account.address, opSepoliaIsmpHost.address, opSepoliaHandler.address],
height: BigInt(height), // latest height
timeoutTimestamp: 0n,
},
]);
const txReceipt = await bscTestnetClient.waitForTransactionReceipt({
hash: txHash,
confirmations: 1,
});
console.log(`Transaction reciept: ${bscTestnet.blockExplorers.default.url}/tx/${txHash}`);
console.log("Block: ", txReceipt.blockNumber);
// parse EvmHost PostRequestEvent emitted in the transcation logs
const txEvent = parseEventLogs({ abi: EVM_HOST.ABI, logs: txReceipt.logs })[0];
if (txEvent.eventName !== "GetRequestEvent") {
throw new Error("Unexpected Event type");
}
const txRequest = txEvent.args;
console.log({ txRequest });
const getRequest = {
...txRequest,
};
const statusStream = await hyperclient.get_request_status_stream(getRequest as any, { Dispatched: txReceipt.blockNumber });
for await (const item of statusStream) {
let status: MessageStatusWithMeta;
if (item instanceof Map) {
status = Object.fromEntries((item as any).entries()) as MessageStatusWithMeta;
} else {
status = item;
}
console.log({ status });
switch (status.kind) {
case "SourceFinalized": {
console.log(
`Status ${status.kind}, Transaction: https://gargantua.statescan.io/#/extrinsics/${status.transaction_hash}`,
);
break;
}
case "HyperbridgeVerified": {
console.log(
`Status ${status.kind}, Transaction: https://gargantua.statescan.io/#/extrinsics/${status.transaction_hash}`,
);
break;
}
case "HyperbridgeFinalized": {
console.log(
`Status ${status.kind}, Transaction: ${bscTestnet.blockExplorers.default.url}/tx/${status.transaction_hash}`,
);
const { args, functionName } = decodeFunctionData({
abi: HANDLER.ABI,
data: status.calldata,
});
try {
const hash = await bscHandler.write.handleGetResponses(args as any);
const getResponseReceipt = await bscTestnetClient.waitForTransactionReceipt({
hash,
confirmations: 1,
});
console.log(`Transaction submitted: ${bscTestnet.blockExplorers.default.url}/tx/${hash}`);
const event = parseEventLogs({ abi: PING_MODULE.ABI, logs: getResponseReceipt.logs })[0];
if (event.eventName === "GetResponseReceived") {
// we requested the raw account in the world state, here we decode the response
for (const { key, value } of event.args.message) {
console.log({
address: key,
account: Account.fromRlpSerializedAccount(value as any),
});
}
}
} catch (e) {
console.error("Error self-relaying: ", e);
}
break;
}
case "DestinationDelivered": {
console.log(
`Status ${status.kind}, Transaction: ${bscTestnet.blockExplorers.default.url}/tx/${status.transaction_hash}`,
);
break;
}
}
}
console.log("\n\nSending Post Request\n\n");
const hash = await bscPing.write.ping([
{
dest: await opSepoliaIsmpHost.read.host(),
count: BigInt(1),
fee: BigInt(0),
module: PING_MODULE_ADDRESS,
timeout: BigInt(60 * 60),
},
]);
const receipt = await bscTestnetClient.waitForTransactionReceipt({
hash,
confirmations: 1,
});
console.log(`Transaction reciept: ${bscTestnet.blockExplorers.default.url}/tx/${hash}`);
console.log("Block: ", receipt.blockNumber);
// parse EvmHost PostRequestEvent emitted in the transcation logs
const event = parseEventLogs({ abi: EVM_HOST.ABI, logs: receipt.logs })[0];
if (event.eventName !== "PostRequestEvent") {
throw new Error("Unexpected Event type");
}
const request = event.args;
console.log({ request });
const status = await hyperclient.query_post_request_status(request);
console.log("Request status: ", status);
const stream = await hyperclient.post_request_status_stream(request, { Dispatched: receipt.blockNumber });
for await (const item of stream) {
let status: MessageStatusWithMeta;
if (item instanceof Map) {
status = Object.fromEntries((item as any).entries()) as MessageStatusWithMeta;
} else {
status = item;
}
console.log({ status });
switch (status.kind) {
case "SourceFinalized": {
console.log(
`Status ${status.kind}, Transaction: https://gargantua.statescan.io/#/extrinsics/${status.transaction_hash}`,
);
break;
}
case "HyperbridgeVerified": {
console.log(
`Status ${status.kind}, Transaction: https://gargantua.statescan.io/#/extrinsics/${status.transaction_hash}`,
);
break;
}
case "HyperbridgeFinalized": {
console.log(
`Status ${status.kind}, Transaction: https://sepolia-optimism.etherscan.io/tx/${status.transaction_hash}`,
);
const { args, functionName } = decodeFunctionData({
abi: HANDLER.ABI,
data: status.calldata,
});
try {
const hash = await opSepoliaHandler.write.handlePostRequests(args as any);
await opSepoliaClient.waitForTransactionReceipt({
hash,
confirmations: 1,
});
console.log(`Transaction submitted: https://sepolia-optimism.etherscan.io/tx/${hash}`);
} catch (e) {
console.error("Error self-relaying: ", e);
}
break;
}
case "Timeout": {
return;
}
case "DestinationDelivered": {
console.log(
`Status ${status.kind}, Transaction: https://sepolia-optimism.etherscan.io/tx/${status.transaction_hash}`,
);
return;
}
}
}
}
async function setUp() {
const account = privateKeyToAccount(process.env.PRIVATE_KEY as any);
const bscWalletClient = createWalletClient({
chain: bscTestnet,
account,
transport: http(),
});
const opWalletClient = createWalletClient({
chain: optimismSepolia,
account,
transport: http(),
});
const bscTestnetClient = createPublicClient({
chain: bscTestnet,
transport: http(),
});
const opSepoliaClient = createPublicClient({
chain: optimismSepolia,
transport: http(),
});
const bscPing = getContract({
address: PING_MODULE_ADDRESS,
abi: PING_MODULE.ABI,
client: { public: bscTestnetClient, wallet: bscWalletClient },
});
const bscIsmpHostAddress = await bscPing.read.host();
const bscIsmpHost = getContract({
address: bscIsmpHostAddress,
abi: EVM_HOST.ABI,
client: bscTestnetClient,
});
const bscHostParams = await bscIsmpHost.read.hostParams();
const bscHandler = getContract({
address: bscHostParams.handler,
abi: HANDLER.ABI,
client: { public: bscTestnetClient, wallet: bscWalletClient },
});
const bscFeeToken = getContract({
address: bscHostParams.feeToken,
abi: ERC6160.ABI,
client: { public: bscTestnetClient, wallet: bscWalletClient },
});
const opSepoliaPing = getContract({
address: PING_MODULE_ADDRESS,
abi: PING_MODULE.ABI,
client: opSepoliaClient,
});
const opSepoliaIsmpHostAddress = await opSepoliaPing.read.host();
const opSepoliaIsmpHost = getContract({
address: opSepoliaIsmpHostAddress,
abi: EVM_HOST.ABI,
client: opSepoliaClient,
});
const opSepoliaHostParams = await opSepoliaIsmpHost.read.hostParams();
const opSepoliaHandler = getContract({
address: opSepoliaHostParams.handler,
abi: HANDLER.ABI,
client: { public: opSepoliaClient, wallet: opWalletClient },
});
const tokenFaucet = getContract({
address: "0x17d8cc0859fbA942A7af243c3EBB69AbBfe0a320",
abi: parseAbi(["function drip(address token) public"]),
client: { public: bscTestnetClient, wallet: bscWalletClient },
});
const BSC = {
rpc_url: process.env.BSC_URL!,
consensus_state_id: "BSC0",
host_address: bscIsmpHostAddress,
state_machine: await bscIsmpHost.read.host(),
};
const OP = {
rpc_url: process.env.OP_URL!,
consensus_state_id: "ETH0",
host_address: opSepoliaIsmpHostAddress,
state_machine: await opSepoliaIsmpHost.read.host(),
};
return {
bscTestnetClient,
bscFeeToken,
account,
tokenFaucet,
BSC,
OP,
opSepoliaHandler,
bscHandler,
bscPing,
opSepoliaClient,
opSepoliaIsmpHost,
};
}
config();
testPostAndGetRequest();