-
Notifications
You must be signed in to change notification settings - Fork 723
/
Copy pathBridge.sol
420 lines (320 loc) · 14.7 KB
/
Bridge.sol
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
// contracts/Bridge.sol
// SPDX-License-Identifier: Apache 2
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "../libraries/external/BytesLib.sol";
import "./BridgeGetters.sol";
import "./BridgeSetters.sol";
import "./BridgeStructs.sol";
import "./BridgeGovernance.sol";
import "./token/Token.sol";
import "./token/TokenImplementation.sol";
contract Bridge is BridgeGovernance {
using BytesLib for bytes;
// Produce a AssetMeta message for a given token
function attestToken(address tokenAddress, uint32 nonce) public payable returns (uint64 sequence){
// decimals, symbol & token are not part of the core ERC20 token standard, so we need to support contracts that dont implement them
(,bytes memory queriedDecimals) = tokenAddress.staticcall(abi.encodeWithSignature("decimals()"));
(,bytes memory queriedSymbol) = tokenAddress.staticcall(abi.encodeWithSignature("symbol()"));
(,bytes memory queriedName) = tokenAddress.staticcall(abi.encodeWithSignature("name()"));
uint8 decimals = abi.decode(queriedDecimals, (uint8));
string memory symbolString = abi.decode(queriedSymbol, (string));
string memory nameString = abi.decode(queriedName, (string));
bytes32 symbol;
bytes32 name;
assembly {
// first 32 bytes hold string length
symbol := mload(add(symbolString, 32))
name := mload(add(nameString, 32))
}
BridgeStructs.AssetMeta memory meta = BridgeStructs.AssetMeta({
payloadID : 2,
// Address of the token. Left-zero-padded if shorter than 32 bytes
tokenAddress : bytes32(uint256(uint160(tokenAddress))),
// Chain ID of the token
tokenChain : chainId(),
// Number of decimals of the token (big-endian uint8)
decimals : decimals,
// Symbol of the token (UTF-8)
symbol : symbol,
// Name of the token (UTF-8)
name : name
});
bytes memory encoded = encodeAssetMeta(meta);
sequence = wormhole().publishMessage{
value : msg.value
}(nonce, encoded, 15);
}
function wrapAndTransferETH(uint16 recipientChain, bytes32 recipient, uint256 arbiterFee, uint32 nonce) public payable returns (uint64 sequence) {
uint wormholeFee = wormhole().messageFee();
require(wormholeFee < msg.value, "value is smaller than wormhole fee");
uint amount = msg.value - wormholeFee;
require(arbiterFee <= amount, "fee is bigger than amount minus wormhole fee");
uint normalizedAmount = amount / (10 ** 10);
uint normalizedArbiterFee = arbiterFee / (10 ** 10);
// refund dust
uint dust = amount - (normalizedAmount * (10 ** 10));
if (dust > 0) {
payable(msg.sender).transfer(dust);
}
// deposit into WETH
WETH().deposit{
value : amount - dust
}();
// track and check outstanding token amounts
bridgeOut(address(WETH()), normalizedAmount);
sequence = logTransfer(chainId(), bytes32(uint256(uint160(address(WETH())))), normalizedAmount, recipientChain, recipient, normalizedArbiterFee, wormholeFee, nonce);
}
// Initiate a Transfer
function transferTokens(address token, uint256 amount, uint16 recipientChain, bytes32 recipient, uint256 arbiterFee, uint32 nonce) public payable returns (uint64 sequence) {
// determine token parameters
uint16 tokenChain;
bytes32 tokenAddress;
if (isWrappedAsset(token)) {
tokenChain = TokenImplementation(token).chainId();
tokenAddress = TokenImplementation(token).nativeContract();
} else {
tokenChain = chainId();
tokenAddress = bytes32(uint256(uint160(token)));
}
// query tokens decimals
(,bytes memory queriedDecimals) = token.staticcall(abi.encodeWithSignature("decimals()"));
uint8 decimals = abi.decode(queriedDecimals, (uint8));
// adjust decimals
uint256 normalizedAmount = amount;
uint256 normalizedArbiterFee = arbiterFee;
if (decimals > 8) {
uint multiplier = 10 ** (decimals - 8);
normalizedAmount /= multiplier;
normalizedArbiterFee /= multiplier;
// don't deposit dust that can not be bridged due to the decimal shift
amount = normalizedAmount * multiplier;
}
if (tokenChain == chainId()) {
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
// track and check outstanding token amounts
bridgeOut(token, normalizedAmount);
} else {
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);
TokenImplementation(token).burn(address(this), amount);
}
sequence = logTransfer(tokenChain, tokenAddress, normalizedAmount, recipientChain, recipient, normalizedArbiterFee, msg.value, nonce);
}
function logTransfer(uint16 tokenChain, bytes32 tokenAddress, uint256 amount, uint16 recipientChain, bytes32 recipient, uint256 fee, uint256 callValue, uint32 nonce) internal returns (uint64 sequence) {
require(fee <= amount, "fee exceeds amount");
BridgeStructs.Transfer memory transfer = BridgeStructs.Transfer({
payloadID : 1,
amount : amount,
tokenAddress : tokenAddress,
tokenChain : tokenChain,
to : recipient,
toChain : recipientChain,
fee : fee
});
bytes memory encoded = encodeTransfer(transfer);
sequence = wormhole().publishMessage{
value : callValue
}(nonce, encoded, 15);
}
function updateWrapped(bytes memory encodedVm) external returns (address token) {
(IWormhole.VM memory vm, bool valid, string memory reason) = wormhole().parseAndVerifyVM(encodedVm);
require(valid, reason);
require(verifyBridgeVM(vm), "invalid emitter");
BridgeStructs.AssetMeta memory meta = parseAssetMeta(vm.payload);
return _updateWrapped(meta, vm.sequence);
}
function _updateWrapped(BridgeStructs.AssetMeta memory meta, uint64 sequence) internal returns (address token) {
address wrapped = wrappedAsset(meta.tokenChain, meta.tokenAddress);
require(wrapped != address(0), "wrapped asset does not exists");
// Update metadata
TokenImplementation(wrapped).updateDetails(bytes32ToString(meta.name), bytes32ToString(meta.symbol), sequence);
return wrapped;
}
function createWrapped(bytes memory encodedVm) external returns (address token) {
(IWormhole.VM memory vm, bool valid, string memory reason) = wormhole().parseAndVerifyVM(encodedVm);
require(valid, reason);
require(verifyBridgeVM(vm), "invalid emitter");
BridgeStructs.AssetMeta memory meta = parseAssetMeta(vm.payload);
return _createWrapped(meta, vm.sequence);
}
// Creates a wrapped asset using AssetMeta
function _createWrapped(BridgeStructs.AssetMeta memory meta, uint64 sequence) internal returns (address token) {
require(meta.tokenChain != chainId(), "can only wrap tokens from foreign chains");
require(wrappedAsset(meta.tokenChain, meta.tokenAddress) == address(0), "wrapped asset already exists");
// initialize the TokenImplementation
bytes memory initialisationArgs = abi.encodeWithSelector(
TokenImplementation.initialize.selector,
bytes32ToString(meta.name),
bytes32ToString(meta.symbol),
meta.decimals,
sequence,
address(this),
meta.tokenChain,
meta.tokenAddress
);
// initialize the BeaconProxy
bytes memory constructorArgs = abi.encode(address(this), initialisationArgs);
// deployment code
bytes memory bytecode = abi.encodePacked(type(BridgeToken).creationCode, constructorArgs);
bytes32 salt = keccak256(abi.encodePacked(meta.tokenChain, meta.tokenAddress));
assembly {
token := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
if iszero(extcodesize(token)) {
revert(0, 0)
}
}
setWrappedAsset(meta.tokenChain, meta.tokenAddress, token);
}
function completeTransfer(bytes memory encodedVm) public {
_completeTransfer(encodedVm, false);
}
function completeTransferAndUnwrapETH(bytes memory encodedVm) public {
_completeTransfer(encodedVm, true);
}
// Execute a Transfer message
function _completeTransfer(bytes memory encodedVm, bool unwrapWETH) internal {
(IWormhole.VM memory vm, bool valid, string memory reason) = wormhole().parseAndVerifyVM(encodedVm);
require(valid, reason);
require(verifyBridgeVM(vm), "invalid emitter");
BridgeStructs.Transfer memory transfer = parseTransfer(vm.payload);
require(!isTransferCompleted(vm.hash), "transfer already completed");
setTransferCompleted(vm.hash);
require(transfer.toChain == chainId(), "invalid target chain");
IERC20 transferToken;
if (transfer.tokenChain == chainId()) {
transferToken = IERC20(address(uint160(uint256(transfer.tokenAddress))));
// track outstanding token amounts
bridgedIn(address(transferToken), transfer.amount);
} else {
address wrapped = wrappedAsset(transfer.tokenChain, transfer.tokenAddress);
require(wrapped != address(0), "no wrapper for this token created yet");
transferToken = IERC20(wrapped);
}
require(unwrapWETH == false || address(transferToken) == address(WETH()), "invalid token, can only unwrap WETH");
// query decimals
(,bytes memory queriedDecimals) = address(transferToken).staticcall(abi.encodeWithSignature("decimals()"));
uint8 decimals = abi.decode(queriedDecimals, (uint8));
// adjust decimals
uint256 nativeAmount = transfer.amount;
uint256 nativeFee = transfer.fee;
if (decimals > 8) {
uint multiplier = 10 ** (decimals - 8);
nativeAmount *= multiplier;
nativeFee *= multiplier;
}
// transfer fee to arbiter
if (nativeFee > 0) {
require(nativeFee <= nativeAmount, "fee higher than transferred amount");
if (unwrapWETH) {
WETH().withdraw(nativeFee);
payable(msg.sender).transfer(nativeFee);
} else {
if (transfer.tokenChain != chainId()) {
// mint wrapped asset
TokenImplementation(address(transferToken)).mint(msg.sender, nativeFee);
} else {
SafeERC20.safeTransfer(transferToken, msg.sender, nativeFee);
}
}
}
// transfer bridged amount to recipient
uint transferAmount = nativeAmount - nativeFee;
address transferRecipient = address(uint160(uint256(transfer.to)));
if (unwrapWETH) {
WETH().withdraw(transferAmount);
payable(transferRecipient).transfer(transferAmount);
} else {
if (transfer.tokenChain != chainId()) {
// mint wrapped asset
TokenImplementation(address(transferToken)).mint(transferRecipient, transferAmount);
} else {
SafeERC20.safeTransfer(transferToken, transferRecipient, transferAmount);
}
}
}
function bridgeOut(address token, uint normalizedAmount) internal {
uint outstanding = outstandingBridged(token);
require(outstanding + normalizedAmount <= type(uint64).max, "transfer exceeds max outstanding bridged token amount");
setOutstandingBridged(token, outstanding + normalizedAmount);
}
function bridgedIn(address token, uint normalizedAmount) internal {
setOutstandingBridged(token, outstandingBridged(token) - normalizedAmount);
}
function verifyBridgeVM(IWormhole.VM memory vm) internal view returns (bool){
if (bridgeContracts(vm.emitterChainId) == vm.emitterAddress) {
return true;
}
return false;
}
function encodeAssetMeta(BridgeStructs.AssetMeta memory meta) public pure returns (bytes memory encoded) {
encoded = abi.encodePacked(
meta.payloadID,
meta.tokenAddress,
meta.tokenChain,
meta.decimals,
meta.symbol,
meta.name
);
}
function encodeTransfer(BridgeStructs.Transfer memory transfer) public pure returns (bytes memory encoded) {
encoded = abi.encodePacked(
transfer.payloadID,
transfer.amount,
transfer.tokenAddress,
transfer.tokenChain,
transfer.to,
transfer.toChain,
transfer.fee
);
}
function parseAssetMeta(bytes memory encoded) public pure returns (BridgeStructs.AssetMeta memory meta) {
uint index = 0;
meta.payloadID = encoded.toUint8(index);
index += 1;
require(meta.payloadID == 2, "invalid AssetMeta");
meta.tokenAddress = encoded.toBytes32(index);
index += 32;
meta.tokenChain = encoded.toUint16(index);
index += 2;
meta.decimals = encoded.toUint8(index);
index += 1;
meta.symbol = encoded.toBytes32(index);
index += 32;
meta.name = encoded.toBytes32(index);
index += 32;
require(encoded.length == index, "invalid AssetMeta");
}
function parseTransfer(bytes memory encoded) public pure returns (BridgeStructs.Transfer memory transfer) {
uint index = 0;
transfer.payloadID = encoded.toUint8(index);
index += 1;
require(transfer.payloadID == 1, "invalid Transfer");
transfer.amount = encoded.toUint256(index);
index += 32;
transfer.tokenAddress = encoded.toBytes32(index);
index += 32;
transfer.tokenChain = encoded.toUint16(index);
index += 2;
transfer.to = encoded.toBytes32(index);
index += 32;
transfer.toChain = encoded.toUint16(index);
index += 2;
transfer.fee = encoded.toUint256(index);
index += 32;
require(encoded.length == index, "invalid Transfer");
}
function bytes32ToString(bytes32 input) internal pure returns (string memory) {
uint256 i;
while (i < 32 && input[i] != 0) {
i++;
}
bytes memory array = new bytes(i);
for (uint c = 0; c < i; c++) {
array[c] = input[c];
}
return string(array);
}
// we need to accept ETH sends to unwrap WETH
receive() external payable {}
}