-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathbridge.ts
437 lines (375 loc) · 12.5 KB
/
bridge.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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
import type {
AccountAddress,
ChainAddress,
ChainsConfig,
Contracts,
Network,
Platform,
TokenAddress,
TokenId,
} from '@wormhole-foundation/sdk-connect';
import {
PorticoBridge,
Wormhole,
canonicalAddress,
isEqualCaseInsensitive,
nativeChainIds,
resolveWrappedToken,
serialize,
toChain,
toChainId,
} from '@wormhole-foundation/sdk-connect';
import type { EvmChains } from '@wormhole-foundation/sdk-evm';
import {
EvmAddress,
EvmPlatform,
EvmUnsignedTransaction,
addChainId,
addFrom,
} from '@wormhole-foundation/sdk-evm';
import type { Provider, TransactionRequest } from 'ethers';
import { ethers, keccak256 } from 'ethers';
import { porticoAbi, uniswapQuoterV2Abi } from './abis.js';
import { PorticoApi } from './api.js';
import { FEE_TIER, supportedTokens } from './consts.js';
import { EvmWormholeCore } from '@wormhole-foundation/sdk-evm-core';
import { EvmTokenBridge } from '@wormhole-foundation/sdk-evm-tokenbridge';
import '@wormhole-foundation/sdk-evm-tokenbridge';
import { finality } from '@wormhole-foundation/sdk-connect';
export class EvmPorticoBridge<
N extends Network,
C extends EvmChains = EvmChains,
> implements PorticoBridge<N, C>
{
chainId: bigint;
core: EvmWormholeCore<N, C>;
tokenBridge: EvmTokenBridge<N, C>;
constructor(
readonly network: N,
readonly chain: C,
readonly provider: Provider,
readonly contracts: Contracts,
) {
if (!contracts.portico)
throw new Error('Unsupported chain, no contract addresses for: ' + chain);
this.core = new EvmWormholeCore(network, chain, provider, contracts);
this.tokenBridge = new EvmTokenBridge(network, chain, provider, contracts);
this.chainId = nativeChainIds.networkChainToNativeChainId.get(
network,
chain,
) as bigint;
}
static async fromRpc<N extends Network>(
provider: Provider,
config: ChainsConfig<N, Platform>,
): Promise<EvmPorticoBridge<N, EvmChains>> {
const [network, chain] = await EvmPlatform.chainFromRpc(provider);
const conf = config[chain]!;
if (conf.network !== network)
throw new Error(`Network mismatch: ${conf.network} != ${network}`);
return new EvmPorticoBridge(network as N, chain, provider, conf.contracts);
}
async *transfer(
sender: AccountAddress<C>,
receiver: ChainAddress,
token: TokenAddress<C>,
amount: bigint,
destToken: TokenId,
destinationPorticoAddress: string,
quote: PorticoBridge.Quote,
) {
const { minAmountStart, minAmountFinish } = quote.swapAmounts;
if (minAmountStart === 0n) throw new Error('Invalid min swap amount');
if (minAmountFinish === 0n) throw new Error('Invalid min swap amount');
const senderAddress = new EvmAddress(sender).toString();
const [isStartTokenNative, startToken] = resolveWrappedToken(
this.network,
this.chain,
token,
);
const [isFinalTokenNative, finalToken] = resolveWrappedToken(
this.network,
receiver.chain,
destToken,
);
const startTokenAddress = canonicalAddress(startToken);
const cannonTokenAddress = canonicalAddress(
await this.getTransferrableToken(startTokenAddress),
);
const receiverAddress = canonicalAddress(receiver);
const finalTokenAddress = canonicalAddress(finalToken);
const nonce = new Date().valueOf() % 2 ** 4;
const flags = PorticoBridge.serializeFlagSet({
flags: {
shouldWrapNative: isStartTokenNative,
shouldUnwrapNative: isFinalTokenNative,
},
recipientChain: toChainId(receiver.chain),
bridgeNonce: nonce,
feeTierStart: FEE_TIER,
feeTierFinish: FEE_TIER,
padding: new Uint8Array(19),
});
const transactionData = porticoAbi.encodeFunctionData('start', [
[
flags,
startTokenAddress.toLowerCase(),
cannonTokenAddress,
finalTokenAddress.toLowerCase(),
receiverAddress,
destinationPorticoAddress,
amount.toString(),
minAmountStart.toString(),
minAmountFinish.toString(),
quote.relayerFee.toString(),
],
]);
const group = this.getTokenGroup(startToken.address.toString());
const porticoAddress = this.getPorticoAddress(group);
// Approve the token if necessary
if (!isStartTokenNative)
yield* this.approve(
startTokenAddress,
senderAddress,
amount,
porticoAddress,
);
const messageFee = await this.core.getMessageFee();
const tx = {
to: porticoAddress,
data: transactionData,
value: messageFee + (isStartTokenNative ? amount : 0n),
};
yield this.createUnsignedTransaction(
addFrom(tx, senderAddress),
'PorticoBridge.Transfer',
);
}
async *redeem(sender: AccountAddress<C>, vaa: PorticoBridge.VAA) {
const recipientChain = toChain(vaa.payload.payload.flagSet.recipientChain);
const tokenAddress = vaa.payload.payload.finalTokenAddress
.toNative(recipientChain)
.toString();
const group = this.getTokenGroup(tokenAddress);
const porticoAddress = this.getPorticoAddress(group);
const contract = new ethers.Contract(
porticoAddress,
porticoAbi.fragments,
this.provider,
);
const txReq = await contract
.getFunction('receiveMessageAndSwap')
.populateTransaction(serialize(vaa));
const address = new EvmAddress(sender).toString();
yield this.createUnsignedTransaction(
addFrom(txReq, address),
'PorticoBridge.Redeem',
);
}
async isTransferCompleted(vaa: PorticoBridge.VAA): Promise<boolean> {
const isCompleted = await this.tokenBridge.tokenBridge.isTransferCompleted(
keccak256(vaa.hash),
);
return isCompleted;
}
async quoteSwap(
input: TokenAddress<C>,
output: TokenAddress<C>,
tokenGroup: string,
amount: bigint,
): Promise<bigint> {
const [, inputTokenId] = resolveWrappedToken(
this.network,
this.chain,
input,
);
const [, outputTokenId] = resolveWrappedToken(
this.network,
this.chain,
output,
);
const inputAddress = canonicalAddress(inputTokenId);
const outputAddress = canonicalAddress(outputTokenId);
if (isEqualCaseInsensitive(inputAddress, outputAddress)) return amount;
const quoterAddress = this.getQuoterAddress(tokenGroup);
const quoter = new ethers.Contract(
quoterAddress,
uniswapQuoterV2Abi.fragments,
this.provider,
);
const result = await quoter
.getFunction('quoteExactInputSingle')
.staticCall([inputAddress, outputAddress, amount, FEE_TIER, 0]);
return result[0];
}
async quoteRelay(startToken: TokenAddress<C>, endToken: TokenAddress<C>) {
return await PorticoApi.quoteRelayer(this.chain, startToken, endToken);
}
// For a given token, return the Wormhole-wrapped/highway token
// that actually gets bridged from this chain
async getTransferrableToken(address: string): Promise<TokenId> {
const token = Wormhole.tokenId(this.chain, address);
const [, wrappedToken] = resolveWrappedToken(
this.network,
this.chain,
token,
);
if (this.chain === 'Ethereum') return wrappedToken;
// Find the group that this token belongs to
const group = Object.values(supportedTokens).find((tokens) =>
tokens.find(
(t) =>
t.chain === this.chain &&
canonicalAddress(t) === canonicalAddress(wrappedToken),
),
);
if (!group)
throw new Error(`No token group found for ${address} on ${this.chain}`);
// Find the token in this group that originates on Ethereum
const tokenOnEthereum = group.find((t) => t.chain === 'Ethereum');
if (!tokenOnEthereum)
throw new Error(
`No Ethereum origin token found for ${address} on ${this.chain}`,
);
// Now find the corresponding Wormhole-wrapped/highway token on this chain
const highwayTokenAddr =
await this.tokenBridge.getWrappedAsset(tokenOnEthereum);
return Wormhole.tokenId(this.chain, highwayTokenAddr.toString());
}
supportedTokens(): { group: string; token: TokenId }[] {
const result = [];
for (const [group, tokens] of Object.entries(supportedTokens)) {
for (const token of tokens) {
if (token.chain === this.chain) result.push({ group, token });
}
}
return result;
}
getTokenGroup(address: string): string {
const tokens = this.supportedTokens();
const token = tokens.find((t) => canonicalAddress(t.token) === address);
if (!token) throw new Error('Token not found');
return token.group;
}
private async *approve(
token: string,
senderAddr: string,
amount: bigint,
contract: string,
) {
const tokenContract = EvmPlatform.getTokenImplementation(
this.provider,
token,
);
const allowance = await tokenContract.allowance(senderAddr, contract);
if (allowance < amount) {
const txReq = await tokenContract.approve.populateTransaction(
contract,
amount,
);
yield this.createUnsignedTransaction(
addFrom(txReq, senderAddr),
'PorticoBridge.Approve',
);
}
}
private createUnsignedTransaction(
txReq: TransactionRequest,
description: string,
) {
return new EvmUnsignedTransaction(
addChainId(txReq, this.chainId),
this.network,
this.chain,
description,
false,
);
}
getPorticoAddress(group: string) {
const portico = this.contracts.portico!;
if (group === 'USDT') {
// Use PancakeSwap if available for USDT
return portico.porticoPancakeSwap || portico.porticoUniswap;
}
return portico.porticoUniswap;
}
private getQuoterAddress(group: string) {
const portico = this.contracts.portico!;
if (group === 'USDT') {
// Use PancakeSwap if available for USDT
return portico.pancakeSwapQuoterV2 || portico.uniswapQuoterV2;
}
return portico.uniswapQuoterV2;
}
async getTransferResult(
vaa: PorticoBridge.VAA,
): Promise<PorticoBridge.TransferResult> {
// First check if the transfer is completed
const isCompleted = await this.isTransferCompleted(vaa);
if (!isCompleted) return { swapResult: 'pending' };
const finalToken = Wormhole.tokenId(
this.chain,
vaa.payload.payload.flagSet.flags.shouldUnwrapNative
? 'native'
: vaa.payload.payload.finalTokenAddress.toNative(this.chain).toString(),
);
const finalAmount = (() => {
const amountLessFee =
vaa.payload.payload.minAmountFinish - vaa.payload.payload.relayerFee;
return amountLessFee < 0n ? 0n : amountLessFee;
})();
const defaultResult: PorticoBridge.TransferResult = {
swapResult: 'success',
receivedToken: {
token: finalToken,
amount: finalAmount,
},
};
// This is a simplification since there is no swap on Ethereum
// since the highway token originates there
if (this.chain === 'Ethereum') return defaultResult;
// Check if the swap succeeded or failed
// NOTE: If we can't find the event, assume the swap succeeded
const { tokenBridge } = this.tokenBridge;
const filter = tokenBridge.filters.TransferRedeemed(
toChainId(vaa.emitterChain),
vaa.emitterAddress.toString(),
vaa.sequence,
);
// Search for the event in the last 15 minutes or 5000 blocks (whichever is smaller)
const latestBlock = await EvmPlatform.getLatestBlock(this.provider);
const blockTime = finality.blockTime.get(this.chain)!;
const fromBlock =
latestBlock - Math.min(5000, Math.floor((15 * 60 * 1000) / blockTime));
const logs = await tokenBridge
.queryFilter(filter, fromBlock, latestBlock)
.catch(() => null);
if (!logs || logs.length === 0) return defaultResult;
const txhash = logs[0]!.transactionHash;
const receipt = await this.provider.getTransactionReceipt(txhash);
if (!receipt) return defaultResult;
const [event] = receipt.logs
.map((log) => porticoAbi.parseLog(log))
.filter((log) => log);
if (!event) return defaultResult;
const swapCompleted = event.args.swapCompleted;
const finaluserAmount = event.args.finaluserAmount;
// If the swap failed, the highway / Wormhole-wrapped token is received instead
// of the finalToken
const token = swapCompleted
? finalToken
: Wormhole.tokenId(
this.chain,
(
await this.tokenBridge.getWrappedAsset(vaa.payload.token)
).toString(),
);
return {
swapResult: swapCompleted ? 'success' : 'failed',
receivedToken: {
token,
amount: finaluserAmount,
},
};
}
}