-
Notifications
You must be signed in to change notification settings - Fork 20
/
BranchBridgeAgent.sol
1420 lines (1200 loc) · 51.9 KB
/
BranchBridgeAgent.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCastLib} from "solady/utils/SafeCastLib.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {ERC20} from "solmate/tokens/ERC20.sol";
import {WETH9} from "./interfaces/IWETH9.sol";
import {AnycallFlags} from "./lib/AnycallFlags.sol";
import {IAnycallProxy} from "./interfaces/IAnycallProxy.sol";
import {IAnycallConfig} from "./interfaces/IAnycallConfig.sol";
import {IAnycallExecutor} from "./interfaces/IAnycallExecutor.sol";
import {IApp, IBranchBridgeAgent} from "./interfaces/IBranchBridgeAgent.sol";
import {IBranchRouter as IRouter} from "./interfaces/IBranchRouter.sol";
import {IBranchPort as IPort} from "./interfaces/IBranchPort.sol";
import {ERC20hTokenBranch as ERC20hToken} from "./token/ERC20hTokenBranch.sol";
import {BranchBridgeAgentExecutor, DeployBranchBridgeAgentExecutor} from "./BranchBridgeAgentExecutor.sol";
import {
Deposit,
DepositStatus,
DepositInput,
DepositMultipleInput,
DepositParams,
DepositMultipleParams,
SettlementParams,
SettlementMultipleParams
} from "./interfaces/IBranchBridgeAgent.sol";
/// @title Library for Branch Bridge Agent Deployment
library DeployBranchBridgeAgent {
function deploy(
WETH9 _wrappedNativeToken,
uint256 _rootChainId,
uint256 _localChainId,
address _rootBridgeAgentAddress,
address _localAnyCallAddress,
address _localAnyCallExecutorAddress,
address _localRouterAddress,
address _localPortAddress
) external returns (BranchBridgeAgent) {
return new BranchBridgeAgent(
_wrappedNativeToken,
_rootChainId,
_localChainId,
_rootBridgeAgentAddress,
_localAnyCallAddress,
_localAnyCallExecutorAddress,
_localRouterAddress,
_localPortAddress
);
}
}
/// @title Branch Bridge Agent Contract
contract BranchBridgeAgent is IBranchBridgeAgent {
using SafeTransferLib for address;
using SafeCastLib for uint256;
/*///////////////////////////////////////////////////////////////
ENCODING CONSTS
//////////////////////////////////////////////////////////////*/
/// AnyExec Decode Consts
uint8 internal constant PARAMS_START = 1;
uint8 internal constant PARAMS_START_SIGNED = 21;
uint8 internal constant PARAMS_ENTRY_SIZE = 32;
uint8 internal constant PARAMS_GAS_OUT = 16;
/// ClearTokens Decode Consts
uint8 internal constant PARAMS_TKN_START = 5;
uint8 internal constant PARAMS_AMT_OFFSET = 64;
uint8 internal constant PARAMS_DEPOSIT_OFFSET = 96;
/*///////////////////////////////////////////////////////////////
BRIDGE AGENT STATE
//////////////////////////////////////////////////////////////*/
/// @notice Chain Id for Root Chain where liqudity is virtualized(e.g. 4).
uint256 public immutable rootChainId;
/// @notice Chain Id for Local Chain.
uint256 public immutable localChainId;
/// @notice Address for Local Wrapped Native Token.
WETH9 public immutable wrappedNativeToken;
/// @notice Address for Bridge Agent who processes requests submitted for the Root Router Address where cross-chain requests are executed in the Root Chain.
address public immutable rootBridgeAgentAddress;
/// @notice Address for Local AnycallV7 Proxy Address where cross-chain requests are sent to the Root Chain Router.
address public immutable localAnyCallAddress;
/// @notice Address for Local Anyexec Address where cross-chain requests from the Root Chain Router are received locally.
address public immutable localAnyCallExecutorAddress;
/// @notice Address for Local Router used for custom actions for different hApps.
address public immutable localRouterAddress;
/// @notice Address for Local Port Address where funds deposited from this chain are kept, managed and supplied to different Port Strategies.
address public immutable localPortAddress;
address public bridgeAgentExecutorAddress;
/*///////////////////////////////////////////////////////////////
DEPOSITS STATE
//////////////////////////////////////////////////////////////*/
/// @notice Deposit nonce used for identifying transaction.
uint32 public depositNonce;
/// @notice Mapping from Pending deposits hash to Deposit Struct.
mapping(uint32 => Deposit) public getDeposit;
/*///////////////////////////////////////////////////////////////
EXECUTOR STATE
//////////////////////////////////////////////////////////////*/
/// @notice If true, bridge agent has already served a request with this nonce from a given chain. Chain -> Nonce -> Bool
mapping(uint32 => bool) public executionHistory;
/*///////////////////////////////////////////////////////////////
GAS MANAGEMENT STATE
//////////////////////////////////////////////////////////////*/
uint256 public remoteCallDepositedGas;
uint256 internal constant MIN_FALLBACK_RESERVE = 185_000; // 100_000 for anycall + 85_000 fallback execution overhead
uint256 internal constant MIN_EXECUTION_OVERHEAD = 160_000; // 100_000 for anycall + 35_000 Pre 1st Gas Checkpoint Execution + 25_000 Post last Gas Checkpoint Executions
uint256 internal constant TRANSFER_OVERHEAD = 24_000;
constructor(
WETH9 _wrappedNativeToken,
uint256 _rootChainId,
uint256 _localChainId,
address _rootBridgeAgentAddress,
address _localAnyCallAddress,
address _localAnyCallExecutorAddress,
address _localRouterAddress,
address _localPortAddress
) {
require(_rootBridgeAgentAddress != address(0), "Root Bridge Agent Address cannot be the zero address.");
require(_localAnyCallAddress != address(0), "AnyCall Address cannot be the zero address.");
require(_localAnyCallExecutorAddress != address(0), "AnyCall Executor Address cannot be the zero address.");
require(_localRouterAddress != address(0), "Local Router Address cannot be the zero address.");
require(_localPortAddress != address(0), "Local Port Address cannot be the zero address.");
wrappedNativeToken = _wrappedNativeToken;
localChainId = _localChainId;
rootChainId = _rootChainId;
rootBridgeAgentAddress = _rootBridgeAgentAddress;
localAnyCallAddress = _localAnyCallAddress;
localAnyCallExecutorAddress = _localAnyCallExecutorAddress;
localRouterAddress = _localRouterAddress;
localPortAddress = _localPortAddress;
bridgeAgentExecutorAddress = DeployBranchBridgeAgentExecutor.deploy();
depositNonce = 1;
}
/*///////////////////////////////////////////////////////////////
VIEW FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IBranchBridgeAgent
function getDepositEntry(uint32 _depositNonce) external view returns (Deposit memory) {
return getDeposit[_depositNonce];
}
/*///////////////////////////////////////////////////////////////
USER EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IBranchBridgeAgent
function callOut(bytes calldata _params, uint128 _remoteExecutionGas) external payable lock requiresFallbackGas {
//Wrap the gas allocated for omnichain execution.
wrappedNativeToken.deposit{value: msg.value}();
//Perform Call without deposit
_callOut(msg.sender, _params, msg.value.toUint128(), _remoteExecutionGas);
}
/// @inheritdoc IBranchBridgeAgent
function callOutAndBridge(bytes calldata _params, DepositInput memory _dParams, uint128 _remoteExecutionGas)
external
payable
lock
requiresFallbackGas
{
//Wrap the gas allocated for omnichain execution.
wrappedNativeToken.deposit{value: msg.value}();
//Perform Call with deposit
_callOutAndBridge(msg.sender, _params, _dParams, msg.value.toUint128(), _remoteExecutionGas);
}
/// @inheritdoc IBranchBridgeAgent
function callOutAndBridgeMultiple(
bytes calldata _params,
DepositMultipleInput memory _dParams,
uint128 _remoteExecutionGas
) external payable lock requiresFallbackGas {
//Wrap the gas allocated for omnichain execution.
wrappedNativeToken.deposit{value: msg.value}();
//Perform Call with multiple deposits
_callOutAndBridgeMultiple(msg.sender, _params, _dParams, msg.value.toUint128(), _remoteExecutionGas);
}
/// @inheritdoc IBranchBridgeAgent
function callOutSigned(bytes calldata _params, uint128 _remoteExecutionGas)
external
payable
lock
requiresFallbackGas
{
//Encode Data for cross-chain call.
bytes memory packedData = abi.encodePacked(
bytes1(0x04), msg.sender, depositNonce, _params, msg.value.toUint128(), _remoteExecutionGas
);
//Wrap the gas allocated for omnichain execution.
wrappedNativeToken.deposit{value: msg.value}();
//Perform Signed Call without deposit
_noDepositCall(msg.sender, packedData, msg.value.toUint128());
}
/// @inheritdoc IBranchBridgeAgent
function callOutSignedAndBridge(bytes calldata _params, DepositInput memory _dParams, uint128 _remoteExecutionGas)
external
payable
lock
requiresFallbackGas
{
//Encode Data for cross-chain call.
bytes memory packedData = abi.encodePacked(
bytes1(0x05),
msg.sender,
depositNonce,
_dParams.hToken,
_dParams.token,
_dParams.amount,
_normalizeDecimals(_dParams.deposit, ERC20(_dParams.token).decimals()),
_dParams.toChain,
_params,
msg.value.toUint128(),
_remoteExecutionGas
);
//Wrap the gas allocated for omnichain execution.
wrappedNativeToken.deposit{value: msg.value}();
//Create Deposit and Send Cross-Chain request
_depositAndCall(
msg.sender,
packedData,
_dParams.hToken,
_dParams.token,
_dParams.amount,
_dParams.deposit,
msg.value.toUint128()
);
}
/// @inheritdoc IBranchBridgeAgent
function callOutSignedAndBridgeMultiple(
bytes calldata _params,
DepositMultipleInput memory _dParams,
uint128 _remoteExecutionGas
) external payable lock requiresFallbackGas {
//Normalize Deposits
uint256[] memory _deposits = new uint256[](_dParams.hTokens.length);
for (uint256 i = 0; i < _dParams.hTokens.length; i++) {
_deposits[i] = _normalizeDecimals(_dParams.deposits[i], ERC20(_dParams.tokens[i]).decimals());
}
//Encode Data for cross-chain call.
bytes memory packedData = abi.encodePacked(
bytes1(0x06),
msg.sender,
uint8(_dParams.hTokens.length),
depositNonce,
_dParams.hTokens,
_dParams.tokens,
_dParams.amounts,
_deposits,
_dParams.toChain,
_params,
msg.value.toUint128(),
_remoteExecutionGas
);
//Wrap the gas allocated for omnichain execution.
wrappedNativeToken.deposit{value: msg.value}();
//Create Deposit and Send Cross-Chain request
_depositAndCallMultiple(
msg.sender,
packedData,
_dParams.hTokens,
_dParams.tokens,
_dParams.amounts,
_dParams.deposits,
msg.value.toUint128()
);
}
/// @inheritdoc IBranchBridgeAgent
function retryDeposit(
bool _isSigned,
uint32 _depositNonce,
bytes calldata _params,
uint128 _remoteExecutionGas,
uint24 _toChain
) external payable lock requiresFallbackGas {
//Check if deposit belongs to message sender
if (getDeposit[_depositNonce].owner != msg.sender) revert NotDepositOwner();
//Encode Data for cross-chain call.
bytes memory packedData;
if (uint8(getDeposit[_depositNonce].hTokens.length) == 1) {
if (_isSigned) {
packedData = abi.encodePacked(
bytes1(0x05),
msg.sender,
_depositNonce,
getDeposit[_depositNonce].hTokens[0],
getDeposit[_depositNonce].tokens[0],
getDeposit[_depositNonce].amounts[0],
_normalizeDecimals(
getDeposit[_depositNonce].deposits[0], ERC20(getDeposit[_depositNonce].tokens[0]).decimals()
),
_toChain,
_params,
msg.value.toUint128(),
_remoteExecutionGas
);
} else {
packedData = abi.encodePacked(
bytes1(0x02),
_depositNonce,
getDeposit[_depositNonce].hTokens[0],
getDeposit[_depositNonce].tokens[0],
getDeposit[_depositNonce].amounts[0],
_normalizeDecimals(
getDeposit[_depositNonce].deposits[0], ERC20(getDeposit[_depositNonce].tokens[0]).decimals()
),
_toChain,
_params,
msg.value.toUint128(),
_remoteExecutionGas
);
}
} else if (uint8(getDeposit[_depositNonce].hTokens.length) > 1) {
//Nonce
uint32 nonce = _depositNonce;
if (_isSigned) {
packedData = abi.encodePacked(
bytes1(0x06),
msg.sender,
uint8(getDeposit[_depositNonce].hTokens.length),
nonce,
getDeposit[nonce].hTokens,
getDeposit[nonce].tokens,
getDeposit[nonce].amounts,
_normalizeDecimalsMultiple(getDeposit[nonce].deposits, getDeposit[nonce].tokens),
_toChain,
_params,
msg.value.toUint128(),
_remoteExecutionGas
);
} else {
packedData = abi.encodePacked(
bytes1(0x03),
uint8(getDeposit[nonce].hTokens.length),
_depositNonce,
getDeposit[nonce].hTokens,
getDeposit[nonce].tokens,
getDeposit[nonce].amounts,
_normalizeDecimalsMultiple(getDeposit[nonce].deposits, getDeposit[nonce].tokens),
_toChain,
_params,
msg.value.toUint128(),
_remoteExecutionGas
);
}
}
//Wrap the gas allocated for omnichain execution.
wrappedNativeToken.deposit{value: msg.value}();
//Deposit Gas to Port
_depositGas(msg.value.toUint128());
//Ensure success Status
getDeposit[_depositNonce].status = DepositStatus.Success;
//Update Deposited Gas
getDeposit[_depositNonce].depositedGas = msg.value.toUint128();
//Perform Call
_performCall(packedData);
}
/// @inheritdoc IBranchBridgeAgent
function retrySettlement(uint32 _settlementNonce, uint128 _gasToBoostSettlement)
external
payable
lock
requiresFallbackGas
{
//Encode Data for cross-chain call.
bytes memory packedData = abi.encodePacked(
bytes1(0x07), depositNonce++, _settlementNonce, msg.value.toUint128(), _gasToBoostSettlement
);
//Update State and Perform Call
_sendRetrieveOrRetry(packedData);
}
/// @inheritdoc IBranchBridgeAgent
function retrieveDeposit(uint32 _depositNonce) external payable lock requiresFallbackGas {
//Encode Data for cross-chain call.
bytes memory packedData = abi.encodePacked(bytes1(0x08), _depositNonce, msg.value.toUint128(), uint128(0));
//Update State and Perform Call
_sendRetrieveOrRetry(packedData);
}
function _sendRetrieveOrRetry(bytes memory _data) internal {
//Deposit Gas for call.
_createGasDeposit(msg.sender, msg.value.toUint128());
//Perform Call
_performCall(_data);
}
/// @inheritdoc IBranchBridgeAgent
function redeemDeposit(uint32 _depositNonce) external lock {
//Update Deposit
if (getDeposit[_depositNonce].status != DepositStatus.Failed) {
revert DepositRedeemUnavailable();
}
_redeemDeposit(_depositNonce);
}
/*///////////////////////////////////////////////////////////////
BRANCH ROUTER EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IBranchBridgeAgent
function performSystemCallOut(
address _depositor,
bytes calldata _params,
uint128 _gasToBridgeOut,
uint128 _remoteExecutionGas
) external payable lock requiresRouter {
//Get remote call execution deposited gas.
(uint128 gasToBridgeOut, bool isRemote) =
(remoteCallDepositedGas > 0 ? (_gasToBridgeOut, true) : (msg.value.toUint128(), false));
//Wrap the gas allocated for omnichain execution.
if (!isRemote && gasToBridgeOut > 0) wrappedNativeToken.deposit{value: msg.value}();
//Check Fallback Gas
_requiresFallbackGas(gasToBridgeOut);
//Encode Data for cross-chain call.
bytes memory packedData =
abi.encodePacked(bytes1(0x00), depositNonce, _params, gasToBridgeOut, _remoteExecutionGas);
//Perform Call
_noDepositCall(_depositor, packedData, gasToBridgeOut);
}
/// @inheritdoc IBranchBridgeAgent
function performCallOut(
address _depositor,
bytes calldata _params,
uint128 _gasToBridgeOut,
uint128 _remoteExecutionGas
) external payable lock requiresRouter {
//Get remote call execution deposited gas.
(uint128 gasToBridgeOut, bool isRemote) =
(remoteCallDepositedGas > 0 ? (_gasToBridgeOut, true) : (msg.value.toUint128(), false));
//Wrap the gas allocated for omnichain execution.
if (!isRemote && gasToBridgeOut > 0) wrappedNativeToken.deposit{value: msg.value}();
//Check Fallback Gas
_requiresFallbackGas(gasToBridgeOut);
//Perform Call
_callOut(_depositor, _params, gasToBridgeOut, _remoteExecutionGas);
}
/// @inheritdoc IBranchBridgeAgent
function performCallOutAndBridge(
address _depositor,
bytes calldata _params,
DepositInput memory _dParams,
uint128 _gasToBridgeOut,
uint128 _remoteExecutionGas
) external payable lock requiresRouter {
//Get remote call execution deposited gas.
(uint128 gasToBridgeOut, bool isRemote) =
(remoteCallDepositedGas > 0 ? (_gasToBridgeOut, true) : (msg.value.toUint128(), false));
//Wrap the gas allocated for omnichain execution.
if (!isRemote && gasToBridgeOut > 0) wrappedNativeToken.deposit{value: msg.value}();
//Check Fallback Gas
_requiresFallbackGas(gasToBridgeOut);
//Perform Call
_callOutAndBridge(_depositor, _params, _dParams, gasToBridgeOut, _remoteExecutionGas);
}
/// @inheritdoc IBranchBridgeAgent
function performCallOutAndBridgeMultiple(
address _depositor,
bytes calldata _params,
DepositMultipleInput memory _dParams,
uint128 _gasToBridgeOut,
uint128 _remoteExecutionGas
) external payable lock requiresRouter {
//Get remote call execution deposited gas.
(uint128 gasToBridgeOut, bool isRemote) =
(remoteCallDepositedGas > 0 ? (_gasToBridgeOut, true) : (msg.value.toUint128(), false));
//Wrap the gas allocated for omnichain execution.
if (!isRemote && gasToBridgeOut > 0) wrappedNativeToken.deposit{value: msg.value}();
//Check Fallback Gas
_requiresFallbackGas(gasToBridgeOut);
//Perform Call
_callOutAndBridgeMultiple(_depositor, _params, _dParams, gasToBridgeOut, _remoteExecutionGas);
}
/*///////////////////////////////////////////////////////////////
TOKEN MANAGEMENT EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IBranchBridgeAgent
function clearToken(address _recipient, address _hToken, address _token, uint256 _amount, uint256 _deposit)
external
requiresAgentExecutor
{
_clearToken(_recipient, _hToken, _token, _amount, _deposit);
}
/// @inheritdoc IBranchBridgeAgent
function clearTokens(bytes calldata _sParams, address _recipient)
external
requiresAgentExecutor
returns (SettlementMultipleParams memory)
{
//Parse Params
uint8 numOfAssets = uint8(bytes1(_sParams[0]));
uint32 nonce = uint32(bytes4(_sParams[PARAMS_START:PARAMS_TKN_START]));
address[] memory _hTokens = new address[](numOfAssets);
address[] memory _tokens = new address[](numOfAssets);
uint256[] memory _amounts = new uint256[](numOfAssets);
uint256[] memory _deposits = new uint256[](numOfAssets);
//Transfer token to recipient
for (uint256 i = 0; i < numOfAssets;) {
//Parse Params
_hTokens[i] = address(
uint160(
bytes20(
bytes32(
_sParams[
PARAMS_TKN_START + (PARAMS_ENTRY_SIZE * i) + 12:
PARAMS_TKN_START + (PARAMS_ENTRY_SIZE * (PARAMS_START + i))
]
)
)
)
);
_tokens[i] = address(
uint160(
bytes20(
_sParams[
PARAMS_TKN_START + PARAMS_ENTRY_SIZE * uint16(i + numOfAssets) + 12:
PARAMS_TKN_START + PARAMS_ENTRY_SIZE * uint16(PARAMS_START + i + numOfAssets)
]
)
)
);
_amounts[i] = uint256(
bytes32(
_sParams[
PARAMS_TKN_START + PARAMS_AMT_OFFSET * uint16(numOfAssets) + (PARAMS_ENTRY_SIZE * uint16(i)):
PARAMS_TKN_START + PARAMS_AMT_OFFSET * uint16(numOfAssets)
+ PARAMS_ENTRY_SIZE * uint16(PARAMS_START + i)
]
)
);
_deposits[i] = uint256(
bytes32(
_sParams[
PARAMS_TKN_START + PARAMS_DEPOSIT_OFFSET * uint16(numOfAssets) + (PARAMS_ENTRY_SIZE * uint16(i)):
PARAMS_TKN_START + PARAMS_DEPOSIT_OFFSET * uint16(numOfAssets)
+ PARAMS_ENTRY_SIZE * uint16(PARAMS_START + i)
]
)
);
//Clear Tokens to destination
if (_amounts[i] - _deposits[i] > 0) {
IPort(localPortAddress).bridgeIn(_recipient, _hTokens[i], _amounts[i] - _deposits[i]);
}
if (_deposits[i] > 0) {
IPort(localPortAddress).withdraw(_recipient, _tokens[i], _deposits[i]);
}
unchecked {
++i;
}
}
return SettlementMultipleParams(numOfAssets, _recipient, nonce, _hTokens, _tokens, _amounts, _deposits);
}
/*///////////////////////////////////////////////////////////////
LOCAL USER DEPOSIT INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Function to perform a call to the Root Omnichain Router without token deposit.
* @param _depositor address of the user that will deposit the funds.
* @param _params RLP enconded parameters to execute on the root chain.
* @param _gasToBridgeOut gas allocated for the cross-chain call.
* @param _remoteExecutionGas gas allocated for branch chain execution.
* @dev ACTION ID: 1 (Call without deposit)
*
*/
function _callOut(address _depositor, bytes calldata _params, uint128 _gasToBridgeOut, uint128 _remoteExecutionGas)
internal
{
//Encode Data for cross-chain call.
bytes memory packedData =
abi.encodePacked(bytes1(0x01), depositNonce, _params, _gasToBridgeOut, _remoteExecutionGas);
//Perform Call
_noDepositCall(_depositor, packedData, _gasToBridgeOut);
}
/**
* @notice Function to perform a call to the Root Omnichain Router while depositing a single asset.
* @param _depositor address of the user that will deposit the funds.
* @param _params RLP enconded parameters to execute on the root chain.
* @param _dParams additional token deposit parameters.
* @param _gasToBridgeOut gas allocated for the cross-chain call.
* @param _remoteExecutionGas gas allocated for branch chain execution.
* @dev ACTION ID: 2 (Call with single deposit)
*
*/
function _callOutAndBridge(
address _depositor,
bytes calldata _params,
DepositInput memory _dParams,
uint128 _gasToBridgeOut,
uint128 _remoteExecutionGas
) internal {
//Encode Data for cross-chain call.
bytes memory packedData = abi.encodePacked(
bytes1(0x02),
depositNonce,
_dParams.hToken,
_dParams.token,
_dParams.amount,
_normalizeDecimals(_dParams.deposit, ERC20(_dParams.token).decimals()),
_dParams.toChain,
_params,
_gasToBridgeOut,
_remoteExecutionGas
);
//Create Deposit and Send Cross-Chain request
_depositAndCall(
_depositor, packedData, _dParams.hToken, _dParams.token, _dParams.amount, _dParams.deposit, _gasToBridgeOut
);
}
/**
* @notice Function to perform a call to the Root Omnichain Router while depositing two or more assets.
* @param _params RLP enconded parameters to execute on the root chain.
* @param _dParams additional token deposit parameters.
* @param _gasToBridgeOut gas allocated for the cross-chain call.
* @param _remoteExecutionGas gas allocated for branch chain execution.
* @dev ACTION ID: 3 (Call with multiple deposit)
*
*/
function _callOutAndBridgeMultiple(
address _depositor,
bytes calldata _params,
DepositMultipleInput memory _dParams,
uint128 _gasToBridgeOut,
uint128 _remoteExecutionGas
) internal {
//Normalize Deposits
uint256[] memory deposits = new uint256[](_dParams.hTokens.length);
for (uint256 i = 0; i < _dParams.hTokens.length; i++) {
deposits[i] = _normalizeDecimals(_dParams.deposits[i], ERC20(_dParams.tokens[i]).decimals());
}
//Encode Data for cross-chain call.
bytes memory packedData = abi.encodePacked(
bytes1(0x03),
uint8(_dParams.hTokens.length),
depositNonce,
_dParams.hTokens,
_dParams.tokens,
_dParams.amounts,
deposits,
_dParams.toChain,
_params,
_gasToBridgeOut,
_remoteExecutionGas
);
//Create Deposit and Send Cross-Chain request
_depositAndCallMultiple(
_depositor,
packedData,
_dParams.hTokens,
_dParams.tokens,
_dParams.amounts,
_dParams.deposits,
_gasToBridgeOut
);
}
/**
* @notice Internal function to move assets from branch chain to root omnichain environment. Naive assets are deposited and hTokens are bridgedOut.
* @param _depositor token depositor.
* @param _data data to be sent to cross-chain messaging layer.
* @param _gasToBridgeOut gas allocated for the cross-chain call.
*
*/
function _noDepositCall(address _depositor, bytes memory _data, uint128 _gasToBridgeOut) internal {
//Deposit Gas for call.
_createGasDeposit(_depositor, _gasToBridgeOut);
//Perform Call
_performCall(_data);
}
/**
* @notice Internal function to move assets from branch chain to root omnichain environment. Naive assets are deposited and hTokens are bridgedOut.
* @param _depositor token depositor.
* @param _data data to be sent to cross-chain messaging layer.
* @param _hToken Local Input hToken Address.
* @param _token Native / Underlying Token Address.
* @param _amount Amount of Local hTokens deposited for trade.
* @param _deposit Amount of native tokens deposited for trade.
* @param _gasToBridgeOut gas allocated for the cross-chain call.
*
*/
function _depositAndCall(
address _depositor,
bytes memory _data,
address _hToken,
address _token,
uint256 _amount,
uint256 _deposit,
uint128 _gasToBridgeOut
) internal {
//Deposit and Store Info
_createDepositSingle(_depositor, _hToken, _token, _amount, _deposit, _gasToBridgeOut);
//Perform Call
_performCall(_data);
}
/**
* @dev Internal function to move assets from branch chain to root omnichain environment. Naive assets are deposited and hTokens are bridgedOut.
* @param _depositor token depositor.
* @param _data data to be sent to cross-chain messaging layer.
* @param _hTokens Local Input hToken Address.
* @param _tokens Native / Underlying Token Address.
* @param _amounts Amount of Local hTokens deposited for trade.
* @param _deposits Amount of native tokens deposited for trade.
* @param _gasToBridgeOut gas allocated for the cross-chain call.
*
*/
function _depositAndCallMultiple(
address _depositor,
bytes memory _data,
address[] memory _hTokens,
address[] memory _tokens,
uint256[] memory _amounts,
uint256[] memory _deposits,
uint128 _gasToBridgeOut
) internal {
//Validate Input
if (
_hTokens.length != _tokens.length || _tokens.length != _amounts.length
|| _amounts.length != _deposits.length
) revert InvalidInput();
//Deposit and Store Info
_createDepositMultiple(_depositor, _hTokens, _tokens, _amounts, _deposits, _gasToBridgeOut);
//Perform Call
_performCall(_data);
}
/**
* @dev Function to create a pending deposit.
* @param _user user address.
* @param _gasToBridgeOut gas allocated for omnichain execution.
*
*/
function _createGasDeposit(address _user, uint128 _gasToBridgeOut) internal {
//Deposit Gas to Port
_depositGas(_gasToBridgeOut);
// Update State
getDeposit[_getAndIncrementDepositNonce()] = Deposit({
owner: _user,
hTokens: new address[](0),
tokens: new address[](0),
amounts: new uint256[](0),
deposits: new uint256[](0),
status: DepositStatus.Success,
depositedGas: _gasToBridgeOut
});
}
/**
* @dev Function to create a pending deposit.
* @param _user user address.
* @param _hToken deposited local hToken addresses.
* @param _token deposited native / underlying Token addresses.
* @param _amount amounts of hTokens input.
* @param _deposit amount of deposited underlying / native tokens.
* @param _gasToBridgeOut gas allocated for omnichain execution.
*
*/
function _createDepositSingle(
address _user,
address _hToken,
address _token,
uint256 _amount,
uint256 _deposit,
uint128 _gasToBridgeOut
) internal {
//Deposit / Lock Tokens into Port
IPort(localPortAddress).bridgeOut(_user, _hToken, _token, _amount, _deposit);
//Deposit Gas to Port
_depositGas(_gasToBridgeOut);
// Cast to dynamic memory array
address[] memory hTokens = new address[](1);
hTokens[0] = _hToken;
address[] memory tokens = new address[](1);
tokens[0] = _token;
uint256[] memory amounts = new uint256[](1);
amounts[0] = _amount;
uint256[] memory deposits = new uint256[](1);
deposits[0] = _deposit;
// Update State
getDeposit[_getAndIncrementDepositNonce()] = Deposit({
owner: _user,
hTokens: hTokens,
tokens: tokens,
amounts: amounts,
deposits: deposits,
status: DepositStatus.Success,
depositedGas: _gasToBridgeOut
});
}
/**
* @notice Function to create a pending deposit.
* @param _user user address.
* @param _hTokens deposited local hToken addresses.
* @param _tokens deposited native / underlying Token addresses.
* @param _amounts amounts of hTokens input.
* @param _deposits amount of deposited underlying / native tokens.
* @param _gasToBridgeOut gas allocated for omnichain execution.
*
*/
function _createDepositMultiple(
address _user,
address[] memory _hTokens,
address[] memory _tokens,
uint256[] memory _amounts,
uint256[] memory _deposits,
uint128 _gasToBridgeOut
) internal {
//Deposit / Lock Tokens into Port
IPort(localPortAddress).bridgeOutMultiple(_user, _hTokens, _tokens, _amounts, _deposits);
//Deposit Gas to Port
_depositGas(_gasToBridgeOut);
// Update State
getDeposit[_getAndIncrementDepositNonce()] = Deposit({
owner: _user,
hTokens: _hTokens,
tokens: _tokens,
amounts: _amounts,
deposits: _deposits,
status: DepositStatus.Success,
depositedGas: _gasToBridgeOut
});
}
function _depositGas(uint128 _gasToBridgeOut) internal virtual {
address(wrappedNativeToken).safeTransfer(localPortAddress, _gasToBridgeOut);
}
/**
* @notice Function that returns Deposit nonce and increments counter.
*
*/
function _getAndIncrementDepositNonce() internal returns (uint32) {
return depositNonce++;
}
/**
* @dev External function to clear / refund a user's failed deposit.
* @param _depositNonce Identifier for user deposit.
*
*/
function _redeemDeposit(uint32 _depositNonce) internal {
//Get Deposit
Deposit storage deposit = getDeposit[_depositNonce];
//Transfer token to depositor / user
for (uint256 i = 0; i < deposit.hTokens.length;) {
_clearToken(deposit.owner, deposit.hTokens[i], deposit.tokens[i], deposit.amounts[i], deposit.deposits[i]);
unchecked {
++i;
}
}
//Delete Failed Deposit Token Info
delete getDeposit[_depositNonce];
}
/*///////////////////////////////////////////////////////////////
REMOTE USER DEPOSIT INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Function to request balance clearance from a Port to a given user.
* @param _recipient token receiver.
* @param _hToken local hToken addresse to clear balance for.
* @param _token native / underlying token addresse to clear balance for.
* @param _amount amounts of hToken to clear balance for.
* @param _deposit amount of native / underlying tokens to clear balance for.
*
*/
function _clearToken(address _recipient, address _hToken, address _token, uint256 _amount, uint256 _deposit)
internal
{
if (_amount - _deposit > 0) {
IPort(localPortAddress).bridgeIn(_recipient, _hToken, _amount - _deposit);
}
if (_deposit > 0) {
IPort(localPortAddress).withdraw(_recipient, _token, _deposit);
}
}
/**
* @notice Function to clear / refund a user's failed deposit. Called upon fallback in cross-chain messaging.
* @param _depositNonce Identifier for user deposit.
*
*/
function _clearDeposit(uint32 _depositNonce) internal {
//Update and return Deposit
getDeposit[_depositNonce].status = DepositStatus.Failed;
}
/*///////////////////////////////////////////////////////////////
ANYCALL INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/