forked from axelarnetwork/interchain-token-service
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInterchainTokenService.sol
1244 lines (1080 loc) · 51.7 KB
/
InterchainTokenService.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 { IERC20 } from '@axelar-network/axelar-gmp-sdk-solidity/contracts/interfaces/IERC20.sol';
import { IAxelarGasService } from '@axelar-network/axelar-gmp-sdk-solidity/contracts/interfaces/IAxelarGasService.sol';
import { IAxelarGateway } from '@axelar-network/axelar-gmp-sdk-solidity/contracts/interfaces/IAxelarGateway.sol';
import { ExpressExecutorTracker } from '@axelar-network/axelar-gmp-sdk-solidity/contracts/express/ExpressExecutorTracker.sol';
import { Upgradable } from '@axelar-network/axelar-gmp-sdk-solidity/contracts/upgradable/Upgradable.sol';
import { AddressBytes } from '@axelar-network/axelar-gmp-sdk-solidity/contracts/libs/AddressBytes.sol';
import { Multicall } from '@axelar-network/axelar-gmp-sdk-solidity/contracts/utils/Multicall.sol';
import { Pausable } from '@axelar-network/axelar-gmp-sdk-solidity/contracts/utils/Pausable.sol';
import { InterchainAddressTracker } from '@axelar-network/axelar-gmp-sdk-solidity/contracts/utils/InterchainAddressTracker.sol';
import { IInterchainTokenService } from './interfaces/IInterchainTokenService.sol';
import { ITokenHandler } from './interfaces/ITokenHandler.sol';
import { ITokenManagerDeployer } from './interfaces/ITokenManagerDeployer.sol';
import { IInterchainTokenDeployer } from './interfaces/IInterchainTokenDeployer.sol';
import { IInterchainTokenExecutable } from './interfaces/IInterchainTokenExecutable.sol';
import { IInterchainTokenExpressExecutable } from './interfaces/IInterchainTokenExpressExecutable.sol';
import { ITokenManager } from './interfaces/ITokenManager.sol';
import { IGatewayCaller } from './interfaces/IGatewayCaller.sol';
import { Create3AddressFixed } from './utils/Create3AddressFixed.sol';
import { Operator } from './utils/Operator.sol';
/**
* @title The Interchain Token Service
* @notice This contract is responsible for facilitating interchain token transfers.
* It (mostly) does not handle tokens, but is responsible for the messaging that needs to occur for interchain transfers to happen.
* @dev The only storage used in this contract is for Express calls.
* Furthermore, no ether is intended to or should be sent to this contract except as part of deploy/interchainTransfer payable methods for gas payment.
*/
contract InterchainTokenService is
Upgradable,
Operator,
Pausable,
Multicall,
Create3AddressFixed,
ExpressExecutorTracker,
InterchainAddressTracker,
IInterchainTokenService
{
using AddressBytes for bytes;
using AddressBytes for address;
IAxelarGateway public immutable gateway;
IAxelarGasService public immutable gasService;
address public immutable interchainTokenFactory;
bytes32 public immutable chainNameHash;
address public immutable interchainTokenDeployer;
address public immutable tokenManagerDeployer;
/**
* @dev Token manager implementation addresses
*/
address public immutable tokenManager;
address public immutable tokenHandler;
address public immutable gatewayCaller;
bytes32 internal constant PREFIX_INTERCHAIN_TOKEN_ID = keccak256('its-interchain-token-id');
bytes32 internal constant PREFIX_INTERCHAIN_TOKEN_SALT = keccak256('its-interchain-token-salt');
bytes32 private constant CONTRACT_ID = keccak256('interchain-token-service');
bytes32 private constant EXECUTE_SUCCESS = keccak256('its-execute-success');
bytes32 private constant EXPRESS_EXECUTE_SUCCESS = keccak256('its-express-execute-success');
/**
* @dev The message types that are sent between InterchainTokenService on different chains.
*/
uint256 private constant MESSAGE_TYPE_INTERCHAIN_TRANSFER = 0;
uint256 private constant MESSAGE_TYPE_DEPLOY_INTERCHAIN_TOKEN = 1;
uint256 private constant MESSAGE_TYPE_DEPLOY_TOKEN_MANAGER = 2;
uint256 private constant MESSAGE_TYPE_SEND_TO_HUB = 3;
uint256 private constant MESSAGE_TYPE_RECEIVE_FROM_HUB = 4;
/**
* @dev Tokens and token managers deployed via the Token Factory contract use a special deployer address.
* This removes the dependency on the address the token factory was deployed too to be able to derive the same tokenId.
*/
address internal constant TOKEN_FACTORY_DEPLOYER = address(0);
/**
* @dev Latest version of metadata that's supported.
*/
uint32 internal constant LATEST_METADATA_VERSION = 1;
/**
* @dev Chain name where ITS Hub exists. This is used for routing ITS calls via ITS hub.
* This is set as a constant, since the ITS Hub will exist on Axelar.
*/
string internal constant ITS_HUB_CHAIN_NAME = 'Axelarnet';
bytes32 internal constant ITS_HUB_CHAIN_NAME_HASH = keccak256(abi.encodePacked(ITS_HUB_CHAIN_NAME));
/**
* @dev Special identifier that the trusted address for a chain should be set to, which indicates if the ITS call
* for that chain should be routed via the ITS hub.
*/
string internal constant ITS_HUB_ROUTING_IDENTIFIER = 'hub';
bytes32 internal constant ITS_HUB_ROUTING_IDENTIFIER_HASH = keccak256(abi.encodePacked(ITS_HUB_ROUTING_IDENTIFIER));
/**
* @notice Constructor for the Interchain Token Service.
* @dev All of the variables passed here are stored as immutable variables.
* @param tokenManagerDeployer_ The address of the TokenManagerDeployer.
* @param interchainTokenDeployer_ The address of the InterchainTokenDeployer.
* @param gateway_ The address of the AxelarGateway.
* @param gasService_ The address of the AxelarGasService.
* @param interchainTokenFactory_ The address of the InterchainTokenFactory.
* @param chainName_ The name of the chain that this contract is deployed on.
* @param tokenManagerImplementation_ The tokenManager implementation.
* @param tokenHandler_ The tokenHandler implementation.
* @param gatewayCaller_ The gatewayCaller implementation.
*/
constructor(
address tokenManagerDeployer_,
address interchainTokenDeployer_,
address gateway_,
address gasService_,
address interchainTokenFactory_,
string memory chainName_,
address tokenManagerImplementation_,
address tokenHandler_,
address gatewayCaller_
) {
if (
gasService_ == address(0) ||
tokenManagerDeployer_ == address(0) ||
interchainTokenDeployer_ == address(0) ||
gateway_ == address(0) ||
interchainTokenFactory_ == address(0) ||
tokenManagerImplementation_ == address(0) ||
tokenHandler_ == address(0) ||
gatewayCaller_ == address(0)
) revert ZeroAddress();
gateway = IAxelarGateway(gateway_);
gasService = IAxelarGasService(gasService_);
tokenManagerDeployer = tokenManagerDeployer_;
interchainTokenDeployer = interchainTokenDeployer_;
interchainTokenFactory = interchainTokenFactory_;
if (bytes(chainName_).length == 0) revert InvalidChainName();
chainNameHash = keccak256(bytes(chainName_));
tokenManager = tokenManagerImplementation_;
tokenHandler = tokenHandler_;
gatewayCaller = gatewayCaller_;
}
/*******\
MODIFIERS
\*******/
/**
* @notice This modifier is used to ensure that only a remote InterchainTokenService can invoke the execute function.
* @param sourceChain The source chain of the contract call.
* @param sourceAddress The source address that the call came from.
*/
modifier onlyRemoteService(string calldata sourceChain, string calldata sourceAddress) {
if (!isTrustedAddress(sourceChain, sourceAddress)) revert NotRemoteService();
_;
}
/*****\
GETTERS
\*****/
/**
* @notice Getter for the contract id.
* @return bytes32 The contract id of this contract.
*/
function contractId() external pure returns (bytes32) {
return CONTRACT_ID;
}
/**
* @notice Calculates the address of a TokenManager from a specific tokenId.
* @dev The TokenManager does not need to exist already.
* @param tokenId The tokenId.
* @return tokenManagerAddress_ The deployment address of the TokenManager.
*/
function tokenManagerAddress(bytes32 tokenId) public view returns (address tokenManagerAddress_) {
tokenManagerAddress_ = _create3Address(tokenId);
}
/**
* @notice Returns the address of a TokenManager from a specific tokenId.
* @dev The TokenManager needs to exist already.
* @param tokenId The tokenId.
* @return tokenManagerAddress_ The deployment address of the TokenManager.
*/
function validTokenManagerAddress(bytes32 tokenId) public view returns (address tokenManagerAddress_) {
tokenManagerAddress_ = tokenManagerAddress(tokenId);
if (tokenManagerAddress_.code.length == 0) revert TokenManagerDoesNotExist(tokenId);
}
/**
* @notice Returns the address of the token that an existing tokenManager points to.
* @param tokenId The tokenId.
* @return tokenAddress The address of the token.
*/
function validTokenAddress(bytes32 tokenId) public view returns (address tokenAddress) {
address tokenManagerAddress_ = validTokenManagerAddress(tokenId);
tokenAddress = ITokenManager(tokenManagerAddress_).tokenAddress();
}
/**
* @notice Returns the address of the interchain token associated with the given tokenId.
* @dev The token does not need to exist.
* @param tokenId The tokenId of the interchain token.
* @return tokenAddress The address of the interchain token.
*/
function interchainTokenAddress(bytes32 tokenId) public view returns (address tokenAddress) {
tokenId = _getInterchainTokenSalt(tokenId);
tokenAddress = _create3Address(tokenId);
}
/**
* @notice Calculates the tokenId that would correspond to a link for a given deployer with a specified salt.
* @param sender The address of the TokenManager deployer.
* @param salt The salt that the deployer uses for the deployment.
* @return tokenId The tokenId that the custom TokenManager would get (or has gotten).
*/
function interchainTokenId(address sender, bytes32 salt) public pure returns (bytes32 tokenId) {
tokenId = keccak256(abi.encode(PREFIX_INTERCHAIN_TOKEN_ID, sender, salt));
}
/**
* @notice Getter function for TokenManager implementation. This will mainly be called by TokenManager proxies
* to figure out their implementations.
* @return tokenManagerAddress The address of the TokenManager implementation.
*/
function tokenManagerImplementation(uint256 /*tokenManagerType*/) external view returns (address) {
return tokenManager;
}
/**
* @notice Getter function for the flow limit of an existing TokenManager with a given tokenId.
* @param tokenId The tokenId of the TokenManager.
* @return flowLimit_ The flow limit.
*/
function flowLimit(bytes32 tokenId) external view returns (uint256 flowLimit_) {
ITokenManager tokenManager_ = ITokenManager(validTokenManagerAddress(tokenId));
flowLimit_ = tokenManager_.flowLimit();
}
/**
* @notice Getter function for the flow out amount of an existing TokenManager with a given tokenId.
* @param tokenId The tokenId of the TokenManager.
* @return flowOutAmount_ The flow out amount.
*/
function flowOutAmount(bytes32 tokenId) external view returns (uint256 flowOutAmount_) {
ITokenManager tokenManager_ = ITokenManager(validTokenManagerAddress(tokenId));
flowOutAmount_ = tokenManager_.flowOutAmount();
}
/**
* @notice Getter function for the flow in amount of an existing TokenManager with a given tokenId.
* @param tokenId The tokenId of the TokenManager.
* @return flowInAmount_ The flow in amount.
*/
function flowInAmount(bytes32 tokenId) external view returns (uint256 flowInAmount_) {
ITokenManager tokenManager_ = ITokenManager(validTokenManagerAddress(tokenId));
flowInAmount_ = tokenManager_.flowInAmount();
}
/************\
USER FUNCTIONS
\************/
/**
* @notice Used to deploy remote custom TokenManagers.
* @dev At least the `gasValue` amount of native token must be passed to the function call. `gasValue` exists because this function can be
* part of a multicall involving multiple functions that could make remote contract calls.
* @param salt The salt to be used during deployment.
* @param destinationChain The name of the chain to deploy the TokenManager and standardized token to.
* @param tokenManagerType The type of token manager to be deployed. Cannot be NATIVE_INTERCHAIN_TOKEN.
* @param params The params that will be used to initialize the TokenManager.
* @param gasValue The amount of native tokens to be used to pay for gas for the remote deployment.
* @return tokenId The tokenId corresponding to the deployed TokenManager.
*/
function deployTokenManager(
bytes32 salt,
string calldata destinationChain,
TokenManagerType tokenManagerType,
bytes calldata params,
uint256 gasValue
) external payable whenNotPaused returns (bytes32 tokenId) {
// Custom token managers can't be deployed with native interchain token type, which is reserved for interchain tokens
if (tokenManagerType == TokenManagerType.NATIVE_INTERCHAIN_TOKEN) revert CannotDeploy(tokenManagerType);
address deployer = msg.sender;
if (deployer == interchainTokenFactory) {
deployer = TOKEN_FACTORY_DEPLOYER;
}
tokenId = interchainTokenId(deployer, salt);
emit InterchainTokenIdClaimed(tokenId, deployer, salt);
if (bytes(destinationChain).length == 0) {
_deployTokenManager(tokenId, tokenManagerType, params);
} else {
_deployRemoteTokenManager(tokenId, destinationChain, gasValue, tokenManagerType, params);
}
}
/**
* @notice Used to deploy an interchain token alongside a TokenManager in another chain.
* @dev At least the `gasValue` amount of native token must be passed to the function call. `gasValue` exists because this function can be
* part of a multicall involving multiple functions that could make remote contract calls.
* If minter is empty bytes, no additional minter is set on the token, only ITS is allowed to mint.
* If the token is being deployed on the current chain, minter should correspond to an EVM address (as bytes).
* Otherwise, an encoding appropriate to the destination chain should be used.
* @param salt The salt to be used during deployment.
* @param destinationChain The name of the destination chain to deploy to.
* @param name The name of the token to be deployed.
* @param symbol The symbol of the token to be deployed.
* @param decimals The decimals of the token to be deployed.
* @param minter The address that will be able to mint and burn the deployed token.
* @param gasValue The amount of native tokens to be used to pay for gas for the remote deployment.
* @return tokenId The tokenId corresponding to the deployed InterchainToken.
*/
function deployInterchainToken(
bytes32 salt,
string calldata destinationChain,
string memory name,
string memory symbol,
uint8 decimals,
bytes memory minter,
uint256 gasValue
) external payable whenNotPaused returns (bytes32 tokenId) {
address deployer = msg.sender;
if (deployer == interchainTokenFactory) deployer = TOKEN_FACTORY_DEPLOYER;
tokenId = interchainTokenId(deployer, salt);
if (bytes(destinationChain).length == 0) {
address tokenAddress = _deployInterchainToken(tokenId, minter, name, symbol, decimals);
_deployTokenManager(tokenId, TokenManagerType.NATIVE_INTERCHAIN_TOKEN, abi.encode(minter, tokenAddress));
} else {
_deployRemoteInterchainToken(tokenId, name, symbol, decimals, minter, destinationChain, gasValue);
}
}
/**
* @notice Returns the amount of token that this call is worth.
* @dev If `tokenAddress` is `0`, then value is in terms of the native token, otherwise it's in terms of the token address.
* @param sourceChain The source chain.
* @param sourceAddress The source address on the source chain.
* @param payload The payload sent with the call.
* @return address The token address.
* @return uint256 The value the call is worth.
*/
function contractCallValue(
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload
) public view virtual onlyRemoteService(sourceChain, sourceAddress) whenNotPaused returns (address, uint256) {
return _contractCallValue(payload);
}
/**
* @notice Express executes operations based on the payload and selector.
* @param commandId The unique message id.
* @param sourceChain The chain where the transaction originates from.
* @param sourceAddress The address of the remote ITS where the transaction originates from.
* @param payload The encoded data payload for the transaction.
*/
function expressExecute(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload
) public payable whenNotPaused {
uint256 messageType = abi.decode(payload, (uint256));
if (messageType != MESSAGE_TYPE_INTERCHAIN_TRANSFER) {
revert InvalidExpressMessageType(messageType);
}
if (gateway.isCommandExecuted(commandId)) revert AlreadyExecuted();
address expressExecutor = msg.sender;
bytes32 payloadHash = keccak256(payload);
emit ExpressExecuted(commandId, sourceChain, sourceAddress, payloadHash, expressExecutor);
_setExpressExecutor(commandId, sourceChain, sourceAddress, payloadHash, expressExecutor);
_expressExecute(commandId, sourceChain, payload);
}
/**
* @notice Uses the caller's tokens to fullfill a sendCall ahead of time. Use this only if you have detected an outgoing
* interchainTransfer that matches the parameters passed here.
* @param commandId The unique message id of the transfer being expressed.
* @param sourceChain the name of the chain where the interchainTransfer originated from.
* @param payload the payload of the receive token
*/
function _expressExecute(bytes32 commandId, string calldata sourceChain, bytes calldata payload) internal {
(, bytes32 tokenId, bytes memory sourceAddress, bytes memory destinationAddressBytes, uint256 amount, bytes memory data) = abi
.decode(payload, (uint256, bytes32, bytes, bytes, uint256, bytes));
address destinationAddress = destinationAddressBytes.toAddress();
IERC20 token;
{
(bool success, bytes memory returnData) = tokenHandler.delegatecall(
abi.encodeWithSelector(ITokenHandler.transferTokenFrom.selector, tokenId, msg.sender, destinationAddress, amount)
);
if (!success) revert TokenHandlerFailed(returnData);
(amount, token) = abi.decode(returnData, (uint256, IERC20));
}
// slither-disable-next-line reentrancy-events
emit InterchainTransferReceived(
commandId,
tokenId,
sourceChain,
sourceAddress,
destinationAddress,
amount,
data.length == 0 ? bytes32(0) : keccak256(data)
);
if (data.length != 0) {
bytes32 result = IInterchainTokenExpressExecutable(destinationAddress).expressExecuteWithInterchainToken(
commandId,
sourceChain,
sourceAddress,
data,
tokenId,
address(token),
amount
);
if (result != EXPRESS_EXECUTE_SUCCESS) revert ExpressExecuteWithInterchainTokenFailed(destinationAddress);
}
}
/**
* @notice Initiates an interchain transfer of a specified token to a destination chain.
* @dev The function retrieves the TokenManager associated with the tokenId.
* @param tokenId The unique identifier of the token to be transferred.
* @param destinationChain The destination chain to send the tokens to.
* @param destinationAddress The address on the destination chain to send the tokens to.
* @param amount The amount of tokens to be transferred.
* @param metadata Optional metadata for the call for additional effects (such as calling a destination contract).
*/
function interchainTransfer(
bytes32 tokenId,
string calldata destinationChain,
bytes calldata destinationAddress,
uint256 amount,
bytes calldata metadata,
uint256 gasValue
) external payable whenNotPaused {
string memory symbol;
(amount, symbol) = _takeToken(tokenId, msg.sender, amount, false);
(IGatewayCaller.MetadataVersion metadataVersion, bytes memory data) = _decodeMetadata(metadata);
_transmitInterchainTransfer(
tokenId,
msg.sender,
destinationChain,
destinationAddress,
amount,
metadataVersion,
data,
symbol,
gasValue
);
}
/**
* @notice Initiates an interchain call contract with interchain token to a destination chain.
* @param tokenId The unique identifier of the token to be transferred.
* @param destinationChain The destination chain to send the tokens to.
* @param destinationAddress The address on the destination chain to send the tokens to.
* @param amount The amount of tokens to be transferred.
* @param data Additional data to be passed along with the transfer.
*/
function callContractWithInterchainToken(
bytes32 tokenId,
string calldata destinationChain,
bytes calldata destinationAddress,
uint256 amount,
bytes memory data,
uint256 gasValue
) external payable whenNotPaused {
if (data.length == 0) revert EmptyData();
string memory symbol;
(amount, symbol) = _takeToken(tokenId, msg.sender, amount, false);
_transmitInterchainTransfer(
tokenId,
msg.sender,
destinationChain,
destinationAddress,
amount,
IGatewayCaller.MetadataVersion.CONTRACT_CALL,
data,
symbol,
gasValue
);
}
/******************\
TOKEN ONLY FUNCTIONS
\******************/
/**
* @notice Transmit an interchain transfer for the given tokenId.
* @dev Only callable by a token registered under a tokenId.
* @param tokenId The tokenId of the token (which must be the msg.sender).
* @param sourceAddress The address where the token is coming from.
* @param destinationChain The name of the chain to send tokens to.
* @param destinationAddress The destinationAddress for the interchainTransfer.
* @param amount The amount of token to give.
* @param metadata Optional metadata for the call for additional effects (such as calling a destination contract).
*/
function transmitInterchainTransfer(
bytes32 tokenId,
address sourceAddress,
string calldata destinationChain,
bytes memory destinationAddress,
uint256 amount,
bytes calldata metadata
) external payable whenNotPaused {
string memory symbol;
(amount, symbol) = _takeToken(tokenId, sourceAddress, amount, true);
(IGatewayCaller.MetadataVersion metadataVersion, bytes memory data) = _decodeMetadata(metadata);
_transmitInterchainTransfer(
tokenId,
sourceAddress,
destinationChain,
destinationAddress,
amount,
metadataVersion,
data,
symbol,
msg.value
);
}
/*************\
OWNER FUNCTIONS
\*************/
/**
* @notice Used to set a flow limit for a token manager that has the service as its operator.
* @param tokenIds An array of the tokenIds of the tokenManagers to set the flow limits of.
* @param flowLimits The flowLimits to set.
*/
function setFlowLimits(bytes32[] calldata tokenIds, uint256[] calldata flowLimits) external onlyRole(uint8(Roles.OPERATOR)) {
uint256 length = tokenIds.length;
if (length != flowLimits.length) revert LengthMismatch();
for (uint256 i; i < length; ++i) {
ITokenManager tokenManager_ = ITokenManager(validTokenManagerAddress(tokenIds[i]));
// slither-disable-next-line calls-loop
tokenManager_.setFlowLimit(flowLimits[i]);
}
}
/**
* @notice Used to set a trusted address for a chain.
* @param chain The chain to set the trusted address of.
* @param address_ The address to set as trusted.
*/
function setTrustedAddress(string memory chain, string memory address_) external onlyOwner {
_setTrustedAddress(chain, address_);
}
/**
* @notice Used to remove a trusted address for a chain.
* @param chain The chain to set the trusted address of.
*/
function removeTrustedAddress(string memory chain) external onlyOwner {
_removeTrustedAddress(chain);
}
/**
* @notice Allows the owner to pause/unpause the token service.
* @param paused Boolean value representing whether to pause or unpause.
*/
function setPauseStatus(bool paused) external onlyOwner {
if (paused) {
_pause();
} else {
_unpause();
}
}
/****************\
INTERNAL FUNCTIONS
\****************/
function _setup(bytes calldata params) internal override {
(address operator, string memory chainName_, string[] memory trustedChainNames, string[] memory trustedAddresses) = abi.decode(
params,
(address, string, string[], string[])
);
uint256 length = trustedChainNames.length;
if (operator == address(0)) revert ZeroAddress();
if (bytes(chainName_).length == 0 || keccak256(bytes(chainName_)) != chainNameHash) revert InvalidChainName();
if (length != trustedAddresses.length) revert LengthMismatch();
_addOperator(operator);
_setChainName(chainName_);
for (uint256 i; i < length; ++i) {
_setTrustedAddress(trustedChainNames[i], trustedAddresses[i]);
}
}
/**
* @notice Executes operations based on the payload and selector.
* @param commandId The unique message id.
* @param sourceChain The chain where the transaction originates from.
* @param sourceAddress The address of the remote ITS where the transaction originates from.
* @param payload The encoded data payload for the transaction.
*/
function execute(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload
) external onlyRemoteService(sourceChain, sourceAddress) whenNotPaused {
bytes32 payloadHash = keccak256(payload);
if (!gateway.validateContractCall(commandId, sourceChain, sourceAddress, payloadHash)) revert NotApprovedByGateway();
_execute(commandId, sourceChain, sourceAddress, payload, payloadHash);
}
/**
* @notice Returns the amount of token that this call is worth.
* @dev If `tokenAddress` is `0`, then value is in terms of the native token, otherwise it's in terms of the token address.
* @param sourceChain The source chain.
* @param sourceAddress The source address on the source chain.
* @param payload The payload sent with the call.
* @param symbol The symbol symbol for the call.
* @param amount The amount for the call.
* @return address The token address.
* @return uint256 The value the call is worth.
*/
function contractCallWithTokenValue(
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload,
string calldata symbol,
uint256 amount
) public view virtual onlyRemoteService(sourceChain, sourceAddress) whenNotPaused returns (address, uint256) {
_checkPayloadAgainstGatewayData(payload, symbol, amount);
return _contractCallValue(payload);
}
/**
* @notice Express executes with a gateway token operations based on the payload and selector.
* @param commandId The unique message id.
* @param sourceChain The chain where the transaction originates from.
* @param sourceAddress The address of the remote ITS where the transaction originates from.
* @param payload The encoded data payload for the transaction.
* @param tokenSymbol The symbol symbol for the call.
* @param amount The amount for the call.
*/
function expressExecuteWithToken(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload,
string calldata tokenSymbol,
uint256 amount
) external payable {
_checkPayloadAgainstGatewayData(payload, tokenSymbol, amount);
// It should be ok to ignore the symbol and amount since this info exists on the payload.
expressExecute(commandId, sourceChain, sourceAddress, payload);
}
function executeWithToken(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload,
string calldata tokenSymbol,
uint256 amount
) external onlyRemoteService(sourceChain, sourceAddress) whenNotPaused {
_executeWithToken(commandId, sourceChain, sourceAddress, payload, tokenSymbol, amount);
}
/**
* @notice Check that the tokenId from the payload is a token that is registered in the gateway with the proper tokenSymbol, with the right amount from the payload.
* Also check that the amount in the payload matches the one for the call.
* @param payload The payload for the call contract with token.
* @param tokenSymbol The tokenSymbol for the call contract with token.
* @param amount The amount for the call contract with token.
*/
function _checkPayloadAgainstGatewayData(bytes memory payload, string calldata tokenSymbol, uint256 amount) internal view {
// The same payload is decoded in both _checkPayloadAgainstGatewayData and _contractCallValue using different parameters.
// This is intentional, as using `uint256` instead of `bytes` improves gas efficiency without any functional difference.
(, bytes32 tokenId, , , uint256 amountInPayload) = abi.decode(payload, (uint256, bytes32, uint256, uint256, uint256));
if (validTokenAddress(tokenId) != gateway.tokenAddresses(tokenSymbol) || amount != amountInPayload)
revert InvalidGatewayTokenTransfer(tokenId, payload, tokenSymbol, amount);
}
/**
* @notice Processes the payload data for a send token call.
* @param commandId The unique message id.
* @param expressExecutor The address of the express executor. Equals `address(0)` if it wasn't expressed.
* @param sourceChain The chain where the transaction originates from.
* @param payload The encoded data payload to be processed.
*/
function _processInterchainTransferPayload(
bytes32 commandId,
address expressExecutor,
string memory sourceChain,
bytes memory payload
) internal {
bytes32 tokenId;
bytes memory sourceAddress;
address destinationAddress;
uint256 amount;
bytes memory data;
{
bytes memory destinationAddressBytes;
(, tokenId, sourceAddress, destinationAddressBytes, amount, data) = abi.decode(
payload,
(uint256, bytes32, bytes, bytes, uint256, bytes)
);
destinationAddress = destinationAddressBytes.toAddress();
}
// Return token to the existing express caller
if (expressExecutor != address(0)) {
// slither-disable-next-line unused-return
_giveToken(tokenId, expressExecutor, amount);
return;
}
address tokenAddress;
(amount, tokenAddress) = _giveToken(tokenId, destinationAddress, amount);
// slither-disable-next-line reentrancy-events
emit InterchainTransferReceived(
commandId,
tokenId,
sourceChain,
sourceAddress,
destinationAddress,
amount,
data.length == 0 ? bytes32(0) : keccak256(data)
);
if (data.length != 0) {
bytes32 result = IInterchainTokenExecutable(destinationAddress).executeWithInterchainToken(
commandId,
sourceChain,
sourceAddress,
data,
tokenId,
tokenAddress,
amount
);
if (result != EXECUTE_SUCCESS) revert ExecuteWithInterchainTokenFailed(destinationAddress);
}
}
/**
* @notice Processes a deploy token manager payload.
*/
function _processDeployTokenManagerPayload(bytes memory payload) internal {
(, bytes32 tokenId, TokenManagerType tokenManagerType, bytes memory params) = abi.decode(
payload,
(uint256, bytes32, TokenManagerType, bytes)
);
if (tokenManagerType == TokenManagerType.NATIVE_INTERCHAIN_TOKEN) revert CannotDeploy(tokenManagerType);
_deployTokenManager(tokenId, tokenManagerType, params);
}
/**
* @notice Processes a deploy interchain token manager payload.
* @param payload The encoded data payload to be processed.
*/
function _processDeployInterchainTokenPayload(bytes memory payload) internal {
(, bytes32 tokenId, string memory name, string memory symbol, uint8 decimals, bytes memory minterBytes) = abi.decode(
payload,
(uint256, bytes32, string, string, uint8, bytes)
);
address tokenAddress;
tokenAddress = _deployInterchainToken(tokenId, minterBytes, name, symbol, decimals);
_deployTokenManager(tokenId, TokenManagerType.NATIVE_INTERCHAIN_TOKEN, abi.encode(minterBytes, tokenAddress));
}
/**
* @notice Calls a contract on a specific destination chain with the given payload
* @dev This method also determines whether the ITS call should be routed via the ITS Hub.
* If the `trustedAddress(destinationChain) == 'hub'`, then the call is wrapped and routed to the ITS Hub destination.
* @param destinationChain The target chain where the contract will be called.
* @param payload The data payload for the transaction.
* @param gasValue The amount of gas to be paid for the transaction.
*/
function _callContract(
string memory destinationChain,
bytes memory payload,
IGatewayCaller.MetadataVersion metadataVersion,
uint256 gasValue
) internal {
string memory destinationAddress;
(destinationChain, destinationAddress, payload) = _getCallParams(destinationChain, payload);
(bool success, bytes memory returnData) = gatewayCaller.delegatecall(
abi.encodeWithSelector(
IGatewayCaller.callContract.selector,
destinationChain,
destinationAddress,
payload,
metadataVersion,
gasValue
)
);
if (!success) revert GatewayCallFailed(returnData);
}
/**
* @notice Calls a contract on a specific destination chain with the given payload and gateway token
* @param destinationChain The target chain where the contract will be called.
* @param payload The data payload for the transaction.
* @param gasValue The amount of gas to be paid for the transaction.
*/
function _callContractWithToken(
string memory destinationChain,
bytes memory payload,
string memory symbol,
uint256 amount,
IGatewayCaller.MetadataVersion metadataVersion,
uint256 gasValue
) internal {
string memory destinationAddress;
(destinationChain, destinationAddress, payload) = _getCallParams(destinationChain, payload);
(bool success, bytes memory returnData) = gatewayCaller.delegatecall(
abi.encodeWithSelector(
IGatewayCaller.callContractWithToken.selector,
destinationChain,
destinationAddress,
payload,
symbol,
amount,
metadataVersion,
gasValue
)
);
if (!success) revert GatewayCallFailed(returnData);
}
/**
* @dev Get the params for the cross-chain message, taking routing via ITS Hub into account.
*/
function _getCallParams(
string memory destinationChain,
bytes memory payload
) internal view returns (string memory, string memory, bytes memory) {
string memory destinationAddress = trustedAddress(destinationChain);
// Prevent sending directly to the ITS Hub chain. This is not supported yet, so fail early to prevent the user from having their funds stuck.
if (keccak256(abi.encodePacked(destinationChain)) == ITS_HUB_CHAIN_NAME_HASH) revert UntrustedChain();
// Check whether the ITS call should be routed via ITS hub for this destination chain
if (keccak256(abi.encodePacked(destinationAddress)) == ITS_HUB_ROUTING_IDENTIFIER_HASH) {
// Wrap ITS message in an ITS Hub message
payload = abi.encode(MESSAGE_TYPE_SEND_TO_HUB, destinationChain, payload);
destinationChain = ITS_HUB_CHAIN_NAME;
destinationAddress = trustedAddress(ITS_HUB_CHAIN_NAME);
}
// Check whether no trusted address was set for the destination chain
if (bytes(destinationAddress).length == 0) revert UntrustedChain();
return (destinationChain, destinationAddress, payload);
}
function _execute(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes memory payload,
bytes32 payloadHash
) internal {
uint256 messageType;
string memory originalSourceChain;
(messageType, originalSourceChain, payload) = _getExecuteParams(sourceChain, payload);
if (messageType == MESSAGE_TYPE_INTERCHAIN_TRANSFER) {
address expressExecutor = _getExpressExecutorAndEmitEvent(commandId, sourceChain, sourceAddress, payloadHash);
_processInterchainTransferPayload(commandId, expressExecutor, originalSourceChain, payload);
} else if (messageType == MESSAGE_TYPE_DEPLOY_TOKEN_MANAGER) {
_processDeployTokenManagerPayload(payload);
} else if (messageType == MESSAGE_TYPE_DEPLOY_INTERCHAIN_TOKEN) {
_processDeployInterchainTokenPayload(payload);
} else {
revert InvalidMessageType(messageType);
}
}
function _executeWithToken(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes memory payload,
string calldata tokenSymbol,
uint256 amount
) internal {
bytes32 payloadHash = keccak256(payload);
if (!gateway.validateContractCallAndMint(commandId, sourceChain, sourceAddress, payloadHash, tokenSymbol, amount))
revert NotApprovedByGateway();
uint256 messageType;
string memory originalSourceChain;
(messageType, originalSourceChain, payload) = _getExecuteParams(sourceChain, payload);
if (messageType != MESSAGE_TYPE_INTERCHAIN_TRANSFER) {
revert InvalidMessageType(messageType);
}
_checkPayloadAgainstGatewayData(payload, tokenSymbol, amount);
// slither-disable-next-line reentrancy-events
address expressExecutor = _getExpressExecutorAndEmitEvent(commandId, sourceChain, sourceAddress, payloadHash);
_processInterchainTransferPayload(commandId, expressExecutor, originalSourceChain, payload);
}
function _getMessageType(bytes memory payload) internal pure returns (uint256 messageType) {
if (payload.length < 32) revert InvalidPayload();
/// @solidity memory-safe-assembly
assembly {
messageType := mload(add(payload, 32))
}
}
/**
* @dev Return the parameters for the execute call, taking routing via ITS Hub into account.
*/
function _getExecuteParams(
string calldata sourceChain,
bytes memory payload
) internal view returns (uint256, string memory, bytes memory) {
// Read the first 32 bytes of the payload to determine the message type
uint256 messageType = _getMessageType(payload);
// True source chain, this is overridden if the ITS call is coming via the ITS hub
string memory originalSourceChain = sourceChain;
// Unwrap ITS message if coming from ITS hub
if (messageType == MESSAGE_TYPE_RECEIVE_FROM_HUB) {
if (keccak256(abi.encodePacked(sourceChain)) != ITS_HUB_CHAIN_NAME_HASH) revert UntrustedChain();
(, originalSourceChain, payload) = abi.decode(payload, (uint256, string, bytes));
// Check whether the original source chain is expected to be routed via the ITS Hub
if (trustedAddressHash(originalSourceChain) != ITS_HUB_ROUTING_IDENTIFIER_HASH) revert UntrustedChain();
// Get message type of the inner ITS message
messageType = _getMessageType(payload);
} else {
// Prevent receiving a direct message from the ITS Hub. This is not supported yet.
if (keccak256(abi.encodePacked(sourceChain)) == ITS_HUB_CHAIN_NAME_HASH) revert UntrustedChain();
}
return (messageType, originalSourceChain, payload);
}
/**
* @notice Deploys a token manager on a destination chain.
* @param tokenId The ID of the token.
* @param destinationChain The chain where the token manager will be deployed.