-
Notifications
You must be signed in to change notification settings - Fork 15
/
RootBridgeAgent.sol
1238 lines (1044 loc) · 47.5 KB
/
RootBridgeAgent.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 {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";
import {ExcessivelySafeCall} from "lib/ExcessivelySafeCall.sol";
import {ILayerZeroEndpoint} from "./interfaces/ILayerZeroEndpoint.sol";
import {IBranchBridgeAgent} from "./interfaces/IBranchBridgeAgent.sol";
import {IERC20hTokenRoot} from "./interfaces/IERC20hTokenRoot.sol";
import {BridgeAgentConstants} from "./interfaces/BridgeAgentConstants.sol";
import {
GasParams,
DepositParams,
DepositMultipleParams,
ILayerZeroReceiver,
IRootBridgeAgent,
Settlement,
SettlementInput,
SettlementMultipleInput
} from "./interfaces/IRootBridgeAgent.sol";
import {IRootPort as IPort} from "./interfaces/IRootPort.sol";
import {VirtualAccount} from "./VirtualAccount.sol";
import {DeployRootBridgeAgentExecutor, RootBridgeAgentExecutor} from "./RootBridgeAgentExecutor.sol";
/// @title Root Bridge Agent Contract
/// @author MaiaDAO
contract RootBridgeAgent is IRootBridgeAgent, BridgeAgentConstants {
using SafeTransferLib for address;
using ExcessivelySafeCall for address;
/*///////////////////////////////////////////////////////////////
ROOT BRIDGE AGENT STATE
//////////////////////////////////////////////////////////////*/
/// @notice Local Chain Id
uint16 public immutable localChainId;
/// @notice Bridge Agent Factory Address.
address public immutable factoryAddress;
/// @notice Local Core Root Router Address
address public immutable localRouterAddress;
/// @notice Local Port Address where funds deposited from this chain are stored.
address public immutable localPortAddress;
/// @notice Local Layer Zero Endpoint Address for cross-chain communication.
address public immutable lzEndpointAddress;
/// @notice Address of Root Bridge Agent Executor.
address public immutable bridgeAgentExecutorAddress;
/*///////////////////////////////////////////////////////////////
BRANCH BRIDGE AGENTS STATE
//////////////////////////////////////////////////////////////*/
/// @notice Chain -> Branch Bridge Agent Address. For N chains, each Root Bridge Agent Address has M =< N Branch Bridge Agent Address.
mapping(uint256 chainId => address branchBridgeAgent) public getBranchBridgeAgent;
/// @notice Message Path for each connected Branch Bridge Agent as bytes for Layzer Zero interaction = localAddress + destinationAddress abi.encodePacked()
mapping(uint256 chainId => bytes branchBridgeAgentPath) public getBranchBridgeAgentPath;
/// @notice If true, bridge agent manager has allowed for a new given branch bridge agent to be synced/added.
mapping(uint256 chainId => bool allowed) public isBranchBridgeAgentAllowed;
/*///////////////////////////////////////////////////////////////
SETTLEMENTS STATE
//////////////////////////////////////////////////////////////*/
/// @notice Deposit nonce used for identifying transaction.
uint32 public settlementNonce;
/// @notice Mapping from Settlement nonce to Settlement Struct.
mapping(uint256 nonce => Settlement settlementInfo) public getSettlement;
/*///////////////////////////////////////////////////////////////
EXECUTOR STATE
//////////////////////////////////////////////////////////////*/
/// @notice If true, bridge agent has already served a request with this nonce from a given chain. Chain -> Nonce -> Bool
mapping(uint256 chainId => mapping(uint256 nonce => uint256 state)) public executionState;
/*///////////////////////////////////////////////////////////////
REENTRANCY STATE
//////////////////////////////////////////////////////////////*/
/// @notice Re-entrancy lock modifier state.
uint256 internal _unlocked = 1;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
/**
* @notice Constructor for Bridge Agent.
* @param _localChainId Local Chain Id.
* @param _lzEndpointAddress Local Layerzero Endpoint Address.
* @param _localPortAddress Local Port Address.
* @param _localRouterAddress Local Port Address.
*/
constructor(
uint16 _localChainId,
address _lzEndpointAddress,
address _localPortAddress,
address _localRouterAddress
) {
require(_lzEndpointAddress != address(0), "Layerzero Enpoint Address cannot be zero address");
require(_localPortAddress != address(0), "Port Address cannot be zero address");
require(_localRouterAddress != address(0), "Router Address cannot be zero address");
factoryAddress = msg.sender;
localChainId = _localChainId;
lzEndpointAddress = _lzEndpointAddress;
localPortAddress = _localPortAddress;
localRouterAddress = _localRouterAddress;
bridgeAgentExecutorAddress = DeployRootBridgeAgentExecutor.deploy(address(this));
settlementNonce = 1;
}
/*///////////////////////////////////////////////////////////////
FALLBACK FUNCTIONS
//////////////////////////////////////////////////////////////*/
receive() external payable {}
/*///////////////////////////////////////////////////////////////
VIEW EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IRootBridgeAgent
function getSettlementEntry(uint32 _settlementNonce) external view override returns (Settlement memory) {
return getSettlement[_settlementNonce];
}
/// @inheritdoc IRootBridgeAgent
function getFeeEstimate(
uint256 _gasLimit,
uint256 _remoteBranchExecutionGas,
bytes calldata _payload,
uint16 _dstChainId
) external view returns (uint256 _fee) {
(_fee,) = ILayerZeroEndpoint(lzEndpointAddress).estimateFees(
_dstChainId,
address(this),
_payload,
false,
abi.encodePacked(uint16(2), _gasLimit, _remoteBranchExecutionGas, getBranchBridgeAgent[_dstChainId])
);
}
/*///////////////////////////////////////////////////////////////
ROOT ROUTER EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IRootBridgeAgent
function callOut(
address payable _refundee,
address _recipient,
uint16 _dstChainId,
bytes calldata _params,
GasParams calldata _gParams
) external payable override lock requiresRouter {
//Encode Data for call.
bytes memory payload = abi.encodePacked(bytes1(0x00), _recipient, settlementNonce++, _params);
//Perform Call to clear hToken balance on destination branch chain.
_performCall(_dstChainId, _refundee, payload, _gParams);
}
/// @inheritdoc IRootBridgeAgent
function callOutAndBridge(
address payable _refundee,
address _recipient,
uint16 _dstChainId,
bytes calldata _params,
SettlementInput calldata _sParams,
GasParams calldata _gParams,
bool _hasFallbackToggled
) external payable override lock requiresRouter {
// Create Settlement and Perform call
bytes memory payload = _createSettlement(
settlementNonce,
_refundee,
_recipient,
_dstChainId,
_params,
_sParams.globalAddress,
_sParams.amount,
_sParams.deposit,
_hasFallbackToggled
);
//Perform Call.
_performCall(_dstChainId, _refundee, payload, _gParams);
}
/// @inheritdoc IRootBridgeAgent
function callOutAndBridgeMultiple(
address payable _refundee,
address _recipient,
uint16 _dstChainId,
bytes calldata _params,
SettlementMultipleInput calldata _sParams,
GasParams calldata _gParams,
bool _hasFallbackToggled
) external payable override lock requiresRouter {
// Create Settlement and Perform call
bytes memory payload = _createSettlementMultiple(
settlementNonce,
_refundee,
_recipient,
_dstChainId,
_sParams.globalAddresses,
_sParams.amounts,
_sParams.deposits,
_params,
_hasFallbackToggled
);
// Perform Call to destination Branch Chain.
_performCall(_dstChainId, _refundee, payload, _gParams);
}
/*///////////////////////////////////////////////////////////////
SETTLEMENT EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IRootBridgeAgent
function retrySettlement(
uint32 _settlementNonce,
address _recipient,
bytes calldata _params,
GasParams calldata _gParams,
bool _hasFallbackToggled
) external payable override lock {
// Get storage reference
Settlement storage settlementReference = getSettlement[_settlementNonce];
// Check if Settlement hasn't been redeemed.
if (settlementReference.owner == address(0)) revert SettlementRetryUnavailable();
// Check if caller is Settlement owner
if (msg.sender != settlementReference.owner) {
if (msg.sender != address(IPort(localPortAddress).getUserAccount(settlementReference.owner))) {
revert NotSettlementOwner();
}
}
// Update Settlement Status
settlementReference.status = STATUS_SUCCESS;
// Perform Settlement Retry
_performRetrySettlementCall(
_hasFallbackToggled,
settlementReference.hTokens,
settlementReference.tokens,
settlementReference.amounts,
settlementReference.deposits,
_params,
_settlementNonce,
payable(settlementReference.owner),
_recipient,
settlementReference.dstChainId,
_gParams,
msg.value
);
}
/// @inheritdoc IRootBridgeAgent
function retrieveSettlement(uint32 _settlementNonce, GasParams calldata _gParams) external payable lock {
//Get settlement storage reference
Settlement storage settlementReference = getSettlement[_settlementNonce];
// Get Settlement owner.
address settlementOwner = settlementReference.owner;
// Check if Settlement is Retrieve.
if (settlementOwner == address(0)) revert SettlementRetrieveUnavailable();
// Check Settlement Owner
if (msg.sender != settlementOwner) {
if (msg.sender != address(IPort(localPortAddress).getUserAccount(settlementOwner))) {
revert NotSettlementOwner();
}
}
//Encode Data for cross-chain call.
bytes memory payload = abi.encodePacked(bytes1(0x03), settlementOwner, _settlementNonce);
//Retrieve Deposit
_performCall(settlementReference.dstChainId, payable(settlementOwner), payload, _gParams);
}
/// @inheritdoc IRootBridgeAgent
function redeemSettlement(uint32 _settlementNonce) external override lock {
// Get setttlement storage reference
Settlement storage settlement = getSettlement[_settlementNonce];
// Get deposit owner.
address settlementOwner = settlement.owner;
// Check if Settlement is redeemable.
if (settlement.status == STATUS_SUCCESS) revert SettlementRedeemUnavailable();
if (settlementOwner == address(0)) revert SettlementRedeemUnavailable();
// Check if Settlement Owner is msg.sender or msg.sender is the virtual account of the settlement owner.
if (msg.sender != settlementOwner) {
if (msg.sender != address(IPort(localPortAddress).getUserAccount(settlementOwner))) {
revert NotSettlementOwner();
}
}
// Clear Global hTokens To Recipient on Root Chain cancelling Settlement to Branch
for (uint256 i = 0; i < settlement.hTokens.length;) {
// Save to memory
address _hToken = settlement.hTokens[i];
// Check if asset
if (_hToken != address(0)) {
// Save to memory
uint24 _dstChainId = settlement.dstChainId;
// Move hTokens from Branch to Root + Mint Sufficient hTokens to match new port deposit
IPort(localPortAddress).bridgeToRoot(
msg.sender,
IPort(localPortAddress).getGlobalTokenFromLocal(_hToken, _dstChainId),
settlement.amounts[i],
settlement.deposits[i],
_dstChainId
);
}
unchecked {
++i;
}
}
// Delete Settlement
delete getSettlement[_settlementNonce];
}
/*///////////////////////////////////////////////////////////////
TOKEN MANAGEMENT EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc IRootBridgeAgent
function bridgeIn(address _recipient, DepositParams memory _dParams, uint256 _srcChainId)
public
override
requiresAgentExecutor
{
// Deposit can't be greater than amount.
if (_dParams.amount < _dParams.deposit) revert InvalidInputParams();
// Cache local port address
address _localPortAddress = localPortAddress;
// Check local exists.
if (_dParams.amount > 0) {
if (!IPort(_localPortAddress).isLocalToken(_dParams.hToken, _srcChainId)) {
revert InvalidInputParams();
}
}
// Check underlying exists.
if (_dParams.deposit > 0) {
if (IPort(_localPortAddress).getLocalTokenFromUnderlying(_dParams.token, _srcChainId) != _dParams.hToken) {
revert InvalidInputParams();
}
}
// Move hTokens from Branch to Root + Mint Sufficient hTokens to match new port deposit
IPort(_localPortAddress).bridgeToRoot(
_recipient,
IPort(_localPortAddress).getGlobalTokenFromLocal(_dParams.hToken, _srcChainId),
_dParams.amount,
_dParams.deposit,
_srcChainId
);
}
/// @inheritdoc IRootBridgeAgent
function bridgeInMultiple(address _recipient, DepositMultipleParams calldata _dParams, uint256 _srcChainId)
external
override
requiresAgentExecutor
{
// Cache length
uint256 length = _dParams.hTokens.length;
// Check MAX_LENGTH
if (length > MAX_TOKENS_LENGTH) revert InvalidInputParams();
// Bridge in assets
for (uint256 i = 0; i < length;) {
bridgeIn(
_recipient,
DepositParams({
hToken: _dParams.hTokens[i],
token: _dParams.tokens[i],
amount: _dParams.amounts[i],
deposit: _dParams.deposits[i],
depositNonce: 0
}),
_srcChainId
);
unchecked {
++i;
}
}
}
/*///////////////////////////////////////////////////////////////
LAYER ZERO EXTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @inheritdoc ILayerZeroReceiver
function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64, bytes calldata _payload) public {
(bool success,) = address(this).excessivelySafeCall(
gasleft(),
150,
abi.encodeWithSelector(this.lzReceiveNonBlocking.selector, msg.sender, _srcChainId, _srcAddress, _payload)
);
if (!success) if (msg.sender == getBranchBridgeAgent[localChainId]) revert ExecutionFailure();
}
/// @inheritdoc IRootBridgeAgent
function lzReceiveNonBlocking(
address _endpoint,
uint16 _srcChainId,
bytes calldata _srcAddress,
bytes calldata _payload
) public override requiresEndpoint(_endpoint, _srcChainId, _srcAddress) {
// Deposit Nonce
uint32 nonce;
// DEPOSIT FLAG: 0 (System request / response)
if (_payload[0] == 0x00) {
// Parse deposit nonce
nonce = uint32(bytes4(_payload[PARAMS_START:PARAMS_TKN_START]));
// Check if tx has already been executed
if (executionState[_srcChainId][nonce] != STATUS_READY) {
revert AlreadyExecutedTransaction();
}
// Avoid stack too deep
uint16 srcChainId = _srcChainId;
// Try to execute remote request
// Flag 0 - RootBridgeAgentExecutor(bridgeAgentExecutorAddress).executeSystemRequest(_localRouterAddress, _payload, _srcChainId)
_execute(
nonce,
abi.encodeWithSelector(
RootBridgeAgentExecutor.executeSystemRequest.selector, localRouterAddress, _payload, srcChainId
),
srcChainId
);
// DEPOSIT FLAG: 1 (Call without Deposit)
} else if (_payload[0] == 0x01) {
// Parse Deposit Nonce
nonce = uint32(bytes4(_payload[PARAMS_START:PARAMS_TKN_START]));
// Check if tx has already been executed
if (executionState[_srcChainId][nonce] != STATUS_READY) {
revert AlreadyExecutedTransaction();
}
// Avoid stack too deep
uint16 srcChainId = _srcChainId;
// Try to execute remote request
// Flag 1 - RootBridgeAgentExecutor(bridgeAgentExecutorAddress).executeNoDeposit(localRouterAddress, payload, _srcChainId)
_execute(
nonce,
abi.encodeWithSelector(
RootBridgeAgentExecutor.executeNoDeposit.selector, localRouterAddress, _payload, srcChainId
),
srcChainId
);
// DEPOSIT FLAG: 2 (Call with Deposit)
} else if (_payload[0] == 0x02) {
//Parse Deposit Nonce
nonce = uint32(bytes4(_payload[PARAMS_START:PARAMS_TKN_START]));
//Check if tx has already been executed
if (executionState[_srcChainId][nonce] != STATUS_READY) {
revert AlreadyExecutedTransaction();
}
// Avoid stack too deep
uint16 srcChainId = _srcChainId;
// Try to execute remote request
// Flag 2 - RootBridgeAgentExecutor(bridgeAgentExecutorAddress).executeWithDeposit(localRouterAddress, _payload, _srcChainId)
_execute(
nonce,
abi.encodeWithSelector(
RootBridgeAgentExecutor.executeWithDeposit.selector, localRouterAddress, _payload, srcChainId
),
srcChainId
);
// DEPOSIT FLAG: 3 (Call with multiple asset Deposit)
} else if (_payload[0] == 0x03) {
// Parse deposit nonce
nonce = uint32(bytes4(_payload[2:6]));
// Check if tx has already been executed
if (executionState[_srcChainId][nonce] != STATUS_READY) {
revert AlreadyExecutedTransaction();
}
// Avoid stack too deep
uint16 srcChainId = _srcChainId;
// Try to execute remote request
// Flag 3 - RootBridgeAgentExecutor(bridgeAgentExecutorAddress).executeWithDepositMultiple(localRouterAddress, _payload, _srcChainId)
_execute(
nonce,
abi.encodeWithSelector(
RootBridgeAgentExecutor.executeWithDepositMultiple.selector,
localRouterAddress,
_payload,
srcChainId
),
srcChainId
);
// DEPOSIT FLAG: 4 (Call without Deposit + msg.sender)
} else if (_payload[0] == 0x04) {
// Parse deposit nonce
nonce = uint32(bytes4(_payload[PARAMS_START_SIGNED:PARAMS_TKN_START_SIGNED]));
//Check if tx has already been executed
if (executionState[_srcChainId][nonce] != STATUS_READY) {
revert AlreadyExecutedTransaction();
}
// Get User Virtual Account
VirtualAccount userAccount = IPort(localPortAddress).fetchVirtualAccount(
address(uint160(bytes20(_payload[PARAMS_START:PARAMS_START_SIGNED])))
);
// Toggle Router Virtual Account use for tx execution
IPort(localPortAddress).toggleVirtualAccountApproved(userAccount, localRouterAddress);
// Avoid stack too deep
uint16 srcChainId = _srcChainId;
// Try to execute remote request
// Flag 4 - RootBridgeAgentExecutor(bridgeAgentExecutorAddress).executeSignedNoDeposit(address(userAccount), localRouterAddress, data, _srcChainId
_execute(
nonce,
abi.encodeWithSelector(
RootBridgeAgentExecutor.executeSignedNoDeposit.selector,
address(userAccount),
localRouterAddress,
_payload,
srcChainId
),
srcChainId
);
// Toggle Router Virtual Account use for tx execution
IPort(localPortAddress).toggleVirtualAccountApproved(userAccount, localRouterAddress);
//DEPOSIT FLAG: 5 (Call with Deposit + msg.sender)
} else if (_payload[0] & 0x7F == 0x05) {
// Parse deposit nonce
nonce = uint32(bytes4(_payload[PARAMS_START_SIGNED:PARAMS_TKN_START_SIGNED]));
//Check if tx has already been executed
if (executionState[_srcChainId][nonce] != STATUS_READY) {
revert AlreadyExecutedTransaction();
}
// Get User Virtual Account
VirtualAccount userAccount = IPort(localPortAddress).fetchVirtualAccount(
address(uint160(bytes20(_payload[PARAMS_START:PARAMS_START_SIGNED])))
);
// Toggle Router Virtual Account use for tx execution
IPort(localPortAddress).toggleVirtualAccountApproved(userAccount, localRouterAddress);
// Avoid stack too deep
uint16 srcChainId = _srcChainId;
// Try to execute remote request
// Flag 5 - RootBridgeAgentExecutor(bridgeAgentExecutorAddress).executeSignedWithDeposit(address(userAccount), localRouterAddress, data, _srcChainId)
_execute(
_payload[0] == 0x85,
nonce,
address(uint160(bytes20(_payload[PARAMS_START:PARAMS_START_SIGNED]))),
abi.encodeWithSelector(
RootBridgeAgentExecutor.executeSignedWithDeposit.selector,
address(userAccount),
localRouterAddress,
_payload,
srcChainId
),
srcChainId
);
// Toggle Router Virtual Account use for tx execution
IPort(localPortAddress).toggleVirtualAccountApproved(userAccount, localRouterAddress);
// DEPOSIT FLAG: 6 (Call with multiple asset Deposit + msg.sender)
} else if (_payload[0] & 0x7F == 0x06) {
// Parse deposit nonce
nonce = uint32(bytes4(_payload[PARAMS_START_SIGNED + PARAMS_START:PARAMS_START_SIGNED + PARAMS_TKN_START]));
// Check if tx has already been executed
if (executionState[_srcChainId][nonce] != STATUS_READY) {
revert AlreadyExecutedTransaction();
}
// Get User Virtual Account
VirtualAccount userAccount = IPort(localPortAddress).fetchVirtualAccount(
address(uint160(bytes20(_payload[PARAMS_START:PARAMS_START_SIGNED])))
);
// Toggle Router Virtual Account use for tx execution
IPort(localPortAddress).toggleVirtualAccountApproved(userAccount, localRouterAddress);
// Avoid stack too deep
uint16 srcChainId = _srcChainId;
// Try to execute remote request
// Flag 6 - RootBridgeAgentExecutor(bridgeAgentExecutorAddress).executeSignedWithDepositMultiple(address(userAccount), localRouterAddress, data, _srcChainId)
_execute(
_payload[0] == 0x86,
nonce,
address(uint160(bytes20(_payload[PARAMS_START:PARAMS_START_SIGNED]))),
abi.encodeWithSelector(
RootBridgeAgentExecutor.executeSignedWithDepositMultiple.selector,
address(userAccount),
localRouterAddress,
_payload,
srcChainId
),
srcChainId
);
// Toggle Router Virtual Account use for tx execution
IPort(localPortAddress).toggleVirtualAccountApproved(userAccount, localRouterAddress);
/// DEPOSIT FLAG: 7 (retrySettlement)
} else if (_payload[0] & 0x7F == 0x07) {
// Prepare Variables for decoding
address owner;
bytes memory params;
GasParams memory gParams;
// Decode Input
(nonce, owner, params, gParams) = abi.decode(_payload[PARAMS_START:], (uint32, address, bytes, GasParams));
// Get storage reference
Settlement storage settlementReference = getSettlement[nonce];
// Check if Settlement hasn't been redeemed.
if (settlementReference.owner == address(0)) revert SettlementRetryUnavailable();
// Check settlement owner
if (owner != settlementReference.owner) {
if (owner != address(IPort(localPortAddress).getUserAccount(settlementReference.owner))) {
revert NotSettlementOwner();
}
}
//Update Settlement Staus
settlementReference.status = STATUS_SUCCESS;
//Retry settlement call with new params and gas
_performRetrySettlementCall(
_payload[0] == 0x87,
settlementReference.hTokens,
settlementReference.tokens,
settlementReference.amounts,
settlementReference.deposits,
params,
nonce,
payable(settlementReference.owner),
settlementReference.recipient,
settlementReference.dstChainId,
gParams,
address(this).balance
);
/// DEPOSIT FLAG: 8 (retrieveDeposit)
} else if (_payload[0] == 0x08) {
//Parse deposit nonce
nonce = uint32(bytes4(_payload[PARAMS_START_SIGNED:PARAMS_TKN_START_SIGNED]));
//Check if deposit is in retrieve mode
if (executionState[_srcChainId][nonce] == STATUS_DONE) {
revert AlreadyExecutedTransaction();
} else {
//Set settlement to retrieve mode, if not already set.
if (executionState[_srcChainId][nonce] == STATUS_READY) {
executionState[_srcChainId][nonce] = STATUS_RETRIEVE;
}
//Trigger fallback/Retry failed fallback
_performFallbackCall(
payable(address(uint160(bytes20(_payload[PARAMS_START:PARAMS_START_SIGNED])))), nonce, _srcChainId
);
}
//DEPOSIT FLAG: 9 (Fallback)
} else if (_payload[0] == 0x09) {
// Parse nonce
nonce = uint32(bytes4(_payload[PARAMS_START:PARAMS_TKN_START]));
// Reopen Settlement for redemption
getSettlement[nonce].status = STATUS_FAILED;
// Emit LogFallback
emit LogFallback(nonce, _srcChainId);
// return to prevent unnecessary emits/logic
return;
// Unrecognized Function Selector
} else {
revert UnknownFlag();
}
emit LogExecute(nonce, _srcChainId);
}
/*///////////////////////////////////////////////////////////////
DEPOSIT EXECUTION INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Internal function requests execution from Root Bridge Agent Executor Contract.
* @param _depositNonce Identifier for nonce being executed.
* @param _calldata Payload of message to be executed by the Root Bridge Agent Executor Contract.
* @param _srcChainId Chain ID of source chain where request originates from.
*/
function _execute(uint256 _depositNonce, bytes memory _calldata, uint16 _srcChainId) private {
//Update tx state as executed
executionState[_srcChainId][_depositNonce] = STATUS_DONE;
//Try to execute the remote request
(bool success,) = bridgeAgentExecutorAddress.call{value: address(this).balance}(_calldata);
// No fallback is requested revert allowing for retry.
if (!success) revert ExecutionFailure();
}
/**
* @notice Internal function requests execution from Root Bridge Agent Executor Contract.
* @param _hasFallbackToggled if true, fallback on execution failure is toggled on.
* @param _depositNonce Identifier for nonce being executed.
* @param _refundee address to refund gas to in case of fallback being triggered.
* @param _calldata Calldata to be executed by the Root Bridge Agent Executor Contract.
* @param _srcChainId Chain ID of source chain where request originates from.
*/
function _execute(
bool _hasFallbackToggled,
uint32 _depositNonce,
address _refundee,
bytes memory _calldata,
uint16 _srcChainId
) private {
//Update tx state as executed
executionState[_srcChainId][_depositNonce] = STATUS_DONE;
//Try to execute the remote request
(bool success,) = bridgeAgentExecutorAddress.call{value: address(this).balance}(_calldata);
//Update tx state if execution failed
if (!success) {
//Read the fallback flag.
if (_hasFallbackToggled) {
// Update tx state as retrieve only
executionState[_srcChainId][_depositNonce] = STATUS_RETRIEVE;
// Perform the fallback call
_performFallbackCall(payable(_refundee), _depositNonce, _srcChainId);
} else {
// No fallback is requested revert allowing for retry.
revert ExecutionFailure();
}
}
}
/*///////////////////////////////////////////////////////////////
LAYER ZERO INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Internal function performs call to Layer Zero Endpoint Contract for cross-chain messaging.
* @param _refundee address to refund excess gas to.
* @param _dstChainId Layer Zero Chain ID of destination chain.
* @param _payload Payload of message to be sent to Layer Zero Endpoint Contract.
* @param _gParams Gas parameters for cross-chain message execution.
*/
function _performCall(
uint16 _dstChainId,
address payable _refundee,
bytes memory _payload,
GasParams calldata _gParams
) internal {
// Get destination Branch Bridge Agent
address callee = getBranchBridgeAgent[_dstChainId];
// Check if valid destination
if (callee == address(0)) revert UnrecognizedBridgeAgent();
// Check if call to remote chain
if (_dstChainId != localChainId) {
//Sends message to Layerzero Enpoint
ILayerZeroEndpoint(lzEndpointAddress).send{value: msg.value}(
_dstChainId,
getBranchBridgeAgentPath[_dstChainId],
_payload,
_refundee,
address(0),
abi.encodePacked(uint16(2), _gParams.gasLimit, _gParams.remoteBranchExecutionGas, callee)
);
// Check if call to local chain
} else {
//Send Gas to Local Branch Bridge Agent
callee.call{value: msg.value}("");
//Execute locally
IBranchBridgeAgent(callee).lzReceive(0, "", 0, _payload);
}
}
/**
* @notice Internal function performs call to Layer Zero Endpoint Contract for cross-chain messaging.
* @param _hasFallbackToggled if true, fallback is toggled on.
* @param _hTokens deposited global token address.
* @param _tokens deposited global token address.
* @param _amounts amounts of total hTokens + Tokens output.
* @param _deposits amount of underlying/native tokens to output.
* @param _params Payload of message to be sent to Layer Zero Endpoint Contract.
* @param _gParams Gas parameters for cross-chain message execution.
* @param _settlementNonce Identifier for token settlement.
* @param _refundee address of token owner and gas refundee.
* @param _recipient destination chain receiver address.
* @param _dstChainId Chain ID of destination chain.
*/
function _performRetrySettlementCall(
bool _hasFallbackToggled,
address[] memory _hTokens,
address[] memory _tokens,
uint256[] memory _amounts,
uint256[] memory _deposits,
bytes memory _params,
uint32 _settlementNonce,
address payable _refundee,
address _recipient,
uint16 _dstChainId,
GasParams memory _gParams,
uint256 _value
) internal {
// Check if payload is ready for message
if (_hTokens.length == 0) revert SettlementRetryUnavailableUseCallout();
// Get packed data
bytes memory payload;
// Check if it's a single asset settlement
if (_hTokens.length == 1) {
//Pack new Data
payload = abi.encodePacked(
_hasFallbackToggled ? bytes1(0x81) : bytes1(0x01),
_recipient,
_settlementNonce,
_hTokens[0],
_tokens[0],
_amounts[0],
_deposits[0],
_params
);
// Check if it's mulitple asset settlement
} else if (_hTokens.length > 1) {
//Pack new Data
payload = abi.encodePacked(
_hasFallbackToggled ? bytes1(0x82) : bytes1(0x02),
_recipient,
uint8(_hTokens.length),
_settlementNonce,
_hTokens,
_tokens,
_amounts,
_deposits,
_params
);
}
// Get destination Branch Bridge Agent
address callee = getBranchBridgeAgent[_dstChainId];
// Check if valid destination
if (callee == address(0)) revert UnrecognizedBridgeAgent();
// Check if call to remote chain
if (_dstChainId != localChainId) {
//Sends message to Layerzero Enpoint
ILayerZeroEndpoint(lzEndpointAddress).send{value: _value}(
_dstChainId,
getBranchBridgeAgentPath[_dstChainId],
payload,
payable(_refundee),
address(0),
abi.encodePacked(uint16(2), _gParams.gasLimit, _gParams.remoteBranchExecutionGas, callee)
);
// Check if call to local chain
} else {
//Send Gas to Local Branch Bridge Agent
callee.call{value: _value}("");
//Execute locally
IBranchBridgeAgent(callee).lzReceive(0, "", 0, payload);
}
}
/**
* @notice Internal function performs call to Layerzero Enpoint Contract for cross-chain messaging.
* @param _depositNonce branch deposit nonce.
* @param _dstChainId Chain ID of destination chain.
*/
function _performFallbackCall(address payable _refundee, uint32 _depositNonce, uint16 _dstChainId) internal {
//Sends message to LayerZero messaging layer
ILayerZeroEndpoint(lzEndpointAddress).send{value: address(this).balance}(
_dstChainId,
getBranchBridgeAgentPath[_dstChainId],
abi.encodePacked(bytes1(0x04), _depositNonce),
payable(_refundee),
address(0),
""
);
}
/*///////////////////////////////////////////////////////////////
SETTLEMENT INTERNAL FUNCTIONS
//////////////////////////////////////////////////////////////*/
/**
* @notice Function to settle a single asset and perform a remote call to a branch chain.
* @param _settlementNonce Identifier for token settlement.
* @param _refundee address of token owner and gas refundee.
* @param _recipient destination chain token receiver address.
* @param _dstChainId branch chain to bridge to.
* @param _params params for branch bridge agent and router execution.
* @param _globalAddress global address of the token in root chain.
* @param _amount amount of hTokens to be bridged out.
* @param _deposit amount of underlying tokens to be cleared from branch port.
* @param _hasFallbackToggled if true, fallback is toggled on.
*/
function _createSettlement(
uint32 _settlementNonce,
address payable _refundee,
address _recipient,
uint16 _dstChainId,
bytes memory _params,
address _globalAddress,
uint256 _amount,
uint256 _deposit,
bool _hasFallbackToggled
) internal returns (bytes memory _payload) {
// Update Settlement Nonce
settlementNonce = _settlementNonce + 1;
// Get Local Branch Token Address from Root Port
address localAddress = IPort(localPortAddress).getLocalTokenFromGlobal(_globalAddress, _dstChainId);
// Get Underlying Token Address from Root Port
address underlyingAddress = IPort(localPortAddress).getUnderlyingTokenFromLocal(localAddress, _dstChainId);
//Update State to reflect bridgeOut
_updateStateOnBridgeOut(
msg.sender, _globalAddress, localAddress, underlyingAddress, _amount, _deposit, _dstChainId
);
// Prepare data for call
_payload = abi.encodePacked(
_hasFallbackToggled ? bytes1(0x81) : bytes1(0x01),
_recipient,
_settlementNonce,
localAddress,
underlyingAddress,
_amount,
_deposit,
_params