Verified contractExactMIT
BridgeConfig
Address0x5d2d08ba166a93963a205a06da301d16fac0f2c2
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.20
- Same code
Only this contract
Details
- Compiler
- solc 0.8.20+commit.a1b79de6
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- shanghai
- Via IR
- yes
- License
- MIT
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 23,994,110
- Creation transaction
- 0xcd75cc706e…7519ce8062
16 files
- contracts/BridgeConfig.solmain10.19 KB
- contracts/interfaces/IBridgeCommittee.sol1.53 KB
- contracts/interfaces/IBridgeConfig.sol3.22 KB
- contracts/utils/BridgeUtils.sol34.56 KB
- contracts/utils/CommitteeUpgradeable.sol3.28 KB
- contracts/utils/MessageVerifier.sol2.3 KB
- dependencies/@openzeppelin-contracts-5.0.1/interfaces/draft-IERC1822.sol880 B
- dependencies/@openzeppelin-contracts-5.0.1/proxy/ERC1967/ERC1967Utils.sol6.72 KB
- dependencies/@openzeppelin-contracts-5.0.1/proxy/beacon/IBeacon.sol472 B
- dependencies/@openzeppelin-contracts-5.0.1/token/ERC20/IERC20.sol2.78 KB
- dependencies/@openzeppelin-contracts-5.0.1/token/ERC20/extensions/IERC20Metadata.sol683 B
- dependencies/@openzeppelin-contracts-5.0.1/utils/Address.sol6.26 KB
- dependencies/@openzeppelin-contracts-5.0.1/utils/StorageSlot.sol3.93 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.0.1/proxy/utils/Initializable.sol8.91 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.0.1/proxy/utils/UUPSUpgradeable.sol6.59 KB
- dependencies/@openzeppelin-contracts-upgradeable-5.0.1/utils/ReentrancyGuardUpgradeable.sol4.36 KB
contracts/BridgeConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./utils/CommitteeUpgradeable.sol";
import "./interfaces/IBridgeConfig.sol";
/// @title BridgeConfig
/// @notice This contract manages a registry of supported tokens and supported chain IDs for the SuiBridge.
/// It also provides functions to convert token amounts to Sui decimal adjusted amounts and vice versa.
contract BridgeConfig is IBridgeConfig, CommitteeUpgradeable {
/* ========== STATE VARIABLES ========== */
uint8 public chainID;
mapping(uint64 tokenID => Token) public supportedTokens;
// price in USD (8 decimal precision) (e.g. 1 ETH = 2000 USD => 2000_00000000)
mapping(uint64 tokenID => uint64 tokenPrice) public tokenPrices;
mapping(uint8 chainId => bool isSupported) public supportedChains;
//invest info
//protocolType => tokenID => LPTokenID
mapping(uint64 => mapping(uint64 => uint64)) public tokenToLP;
//protocolType => LPTokenID => tokenID
mapping(uint64 => mapping(uint64 => uint64)) public lpToToken;
/* ========== INITIALIZER ========== */
/// @notice Constructor function for the BridgeConfig contract.
/// @dev the provided arrays must have the same length.
/// @param _committee The address of the BridgeCommittee contract.
/// @param _chainID The ID of the chain this contract is deployed on.
/// @param _supportedTokens The addresses of the supported tokens.
/// @param _tokenPrices An array of token prices (with 8 decimal precision).
/// @param _supportedChains array of supported chain IDs.
function initialize(
address _committee,
uint8 _chainID,
address[] memory _supportedTokens,
uint64[] memory _tokenPrices,
uint64[] memory _tokenIds,
uint8[] memory _suiDecimals,
uint8[] memory _supportedChains,
uint64 _protocolType,
uint64 _tokenID,
uint64 _lpTokenId
) external initializer {
__CommitteeUpgradeable_init(_committee);
require(
_supportedTokens.length == _tokenPrices.length, "BridgeConfig: Invalid token prices"
);
require(
_supportedTokens.length == _tokenIds.length, "BridgeConfig: Invalid token IDs"
);
require(
_supportedTokens.length == _suiDecimals.length, "BridgeConfig: Invalid Sui decimals"
);
for (uint8 i; i < _tokenIds.length; i++) {
// `is_native` is hardcoded to `true` because we only support Eth native tokens
// at the moment. This needs to change when we support tokens native on other chains.
supportedTokens[_tokenIds[i]] = Token(_supportedTokens[i], _suiDecimals[i], true);
}
for (uint8 i; i < _supportedChains.length; i++) {
require(_supportedChains[i] != _chainID, "BridgeConfig: Cannot support self");
supportedChains[_supportedChains[i]] = true;
}
for (uint8 i; i < _tokenPrices.length; i++) {
tokenPrices[_tokenIds[i]] = _tokenPrices[i];
}
tokenToLP[_protocolType][_tokenID] = _lpTokenId;
lpToToken[_protocolType][_lpTokenId] = _tokenID;
chainID = _chainID;
}
/* ========== VIEW FUNCTIONS ========== */
/// @notice Returns the address of the token with the given ID.
/// @param tokenID The ID of the token.
/// @return address of the provided token.
function tokenAddressOf(uint64 tokenID) public view override returns (address) {
return supportedTokens[tokenID].tokenAddress;
}
/// @notice Returns the sui decimal places of the token with the given ID.
/// @param tokenID The ID of the token.
/// @return amount of sui decimal places of the provided token.
function tokenSuiDecimalOf(uint64 tokenID) public view override returns (uint8) {
return supportedTokens[tokenID].suiDecimal;
}
/// @notice Returns the price of the token with the given ID.
/// @param tokenID The ID of the token.
/// @return price of the provided token.
function tokenPriceOf(uint64 tokenID) public view override returns (uint64) {
return tokenPrices[tokenID];
}
function investLpTokenIdOf(uint64 protocolType,uint64 underlyingTokenId) public view override returns (uint64) {
return tokenToLP[protocolType][underlyingTokenId];
}
function underlyingTokenIdOf(uint64 protocolType,uint64 lpTokenId) public view override returns (uint64) {
return lpToToken[protocolType][lpTokenId];
}
/// @notice Returns whether a token is supported in SuiBridge with the given ID.
/// @param tokenID The ID of the token.
/// @return true if the token is supported, false otherwise.
function isTokenSupported(uint64 tokenID) public view override returns (bool) {
return supportedTokens[tokenID].tokenAddress != address(0);
}
/// @notice Returns whether a chain is supported in SuiBridge with the given ID.
/// @param chainId The ID of the chain.
/// @return true if the chain is supported, false otherwise.
function isChainSupported(uint8 chainId) public view override returns (bool) {
return supportedChains[chainId];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/// @notice Adds a LP token ID with the provided message if the provided signatures are valid.
/// @param signatures array of signatures to validate the message.
/// @param message BridgeMessage containing the add LP token payload.
/// @dev The function will revert if the payload length is invalid.
/// Add LP token payload is 24 bytes.
/// bytes 0-7 : protocol type (uint64)
/// bytes 8-15 : token ID (uint64)
/// bytes 16-23 : LP token ID (uint64)
/// @dev The function will revert if the token is already added.
function addLpTokenIdWithSignatures(
bytes[] memory signatures,
BridgeUtils.Message memory message
)
external
nonReentrant
verifyMessageAndSignatures(message, signatures, BridgeUtils.ADD_LP_TOKEN_ID)
{
(uint64 protocolType, uint64 tokenID, uint64 lpTokenId) = BridgeUtils.decodeAddLpTokenPayload(message.payload);
require(tokenToLP[protocolType][tokenID] == 0, "BridgeConfig: LPToken already added");
tokenToLP[protocolType][tokenID] = lpTokenId;
lpToToken[protocolType][lpTokenId] = tokenID;
emit LpTokenIdAdded(message.nonce,protocolType,tokenID,lpTokenId);
}
function updateTokenDecimal(uint64 tokenID, uint8 suiDecimal) external {
require(msg.sender == address(0x4Eb6688CFaDa8CB85A33eF42e330e96597D855AA), "BridgeConfig: Only Governance can update token decimal");
// require(isTokenSupported(tokenID), "BridgeConfig: Unsupported token");
supportedTokens[tokenID].suiDecimal = suiDecimal;
}
/// @notice Updates the token price with the provided message if the provided signatures are valid.
/// @param signatures array of signatures to validate the message.
/// @param message BridgeMessage containing the update token price payload.
function updateTokenPriceWithSignatures(
bytes[] memory signatures,
BridgeUtils.Message memory message
)
external
nonReentrant
verifyMessageAndSignatures(message, signatures, BridgeUtils.UPDATE_TOKEN_PRICE)
{
// decode the update token payload
(uint64 tokenID, uint64 price) = BridgeUtils.decodeUpdateTokenPricePayload(message.payload);
_updateTokenPrice(tokenID, price);
emit TokenPriceUpdatedV2(message.nonce, tokenID, price);
}
function addTokensWithSignatures(bytes[] memory signatures, BridgeUtils.Message memory message)
external
nonReentrant
verifyMessageAndSignatures(message, signatures, BridgeUtils.ADD_EVM_TOKENS)
{
// decode the update token payload
(
bool native,
uint64[] memory tokenIDs,
address[] memory tokenAddresses,
uint8[] memory suiDecimals,
uint64[] memory _tokenPrices
) = BridgeUtils.decodeAddTokensPayload(message.payload);
// update the token
for (uint8 i; i < tokenIDs.length; i++) {
_addToken(tokenIDs[i], tokenAddresses[i], suiDecimals[i], _tokenPrices[i], native);
}
emit TokensAddedV2(message.nonce, tokenIDs, tokenAddresses, suiDecimals, _tokenPrices);
}
/* ========== PRIVATE FUNCTIONS ========== */
/// @notice Updates the price of the token with the provided ID.
/// @param tokenID The ID of the token to update.
/// @param tokenPrice The price of the token.
function _updateTokenPrice(uint64 tokenID, uint64 tokenPrice) private {
require(isTokenSupported(tokenID), "BridgeConfig: Unsupported token");
require(tokenPrice > 0, "BridgeConfig: Invalid token price");
tokenPrices[tokenID] = tokenPrice;
}
/// @notice Updates the token with the provided ID.
/// @param tokenID The ID of the token to update.
/// @param tokenAddress The address of the token.
/// @param suiDecimal The decimal places of the token.
/// @param tokenPrice The price of the token.
/// @param native Whether the token is native to the chain.
function _addToken(
uint64 tokenID,
address tokenAddress,
uint8 suiDecimal,
uint64 tokenPrice,
bool native
) private {
require(tokenAddress != address(0), "BridgeConfig: Invalid token address");
require(suiDecimal > 0, "BridgeConfig: Invalid Sui decimal");
require(tokenPrice > 0, "BridgeConfig: Invalid token price");
supportedTokens[tokenID] = Token(tokenAddress, suiDecimal, native);
tokenPrices[tokenID] = tokenPrice;
}
/* ========== MODIFIERS ========== */
/// @notice Requires the given token to be supported.
/// @param tokenID The ID of the token to check.
modifier tokenSupported(uint64 tokenID) {
require(isTokenSupported(tokenID), "BridgeConfig: Unsupported token");
_;
}
}
contracts/interfaces/IBridgeCommittee.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "../utils/BridgeUtils.sol";
import "./IBridgeConfig.sol";
/// @title IBridgeCommittee
/// @notice Interface for the BridgeCommittee contract.
interface IBridgeCommittee {
/// @notice Verifies the provided signatures for the given message by aggregating and validating the
/// stake of each signer against the required stake of the given message type.
/// @dev The function will revert if the total stake of the signers is less than the required stake.
/// @param signatures The array of signatures to be verified.
/// @param message The `BridgeUtils.Message` to be verified.
function verifySignatures(bytes[] memory signatures, BridgeUtils.Message memory message)
external
view;
/// @notice Returns the interface of the BridgeConfig contract.
/// @return The interface of the BridgeConfig contract.
function config() external view returns (IBridgeConfig);
/* ========== EVENTS ========== */
/// @notice Emitted when the blocklist is updated.
/// @param nonce The governance action nonce.
/// @param updatedMembers The addresses of the updated committee members.
/// @param isBlocklisted A boolean indicating whether the committee members are blocklisted or not.
event BlocklistUpdatedV2(uint64 nonce, address[] updatedMembers, bool isBlocklisted);
/// @dev (deprecated in favor of BlocklistUpdatedV2)
event BlocklistUpdated(address[] updatedMembers, bool isBlocklisted);
}
contracts/interfaces/IBridgeConfig.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title IBridgeConfig
/// @dev Interface for the BridgeConfig contract.
interface IBridgeConfig {
/* ========== STRUCTS ========== */
/// @notice The data struct for the supported bridge tokens.
struct Token {
address tokenAddress;
uint8 suiDecimal;
bool native;
}
/* ========== VIEW FUNCTIONS ========== */
/// @notice Returns the address of the token with the given ID.
/// @param tokenID The ID of the token.
/// @return address of the provided token.
function tokenAddressOf(uint64 tokenID) external view returns (address);
/// @notice Returns the sui decimal places of the token with the given ID.
/// @param tokenID The ID of the token.
/// @return amount of sui decimal places of the provided token.
function tokenSuiDecimalOf(uint64 tokenID) external view returns (uint8);
/// @notice Returns the price of the token with the given ID.
/// @param tokenID The ID of the token.
/// @return price of the provided token.
function tokenPriceOf(uint64 tokenID) external view returns (uint64);
/// @notice Returns the supported status of the token with the given ID.
/// @param tokenID The ID of the token.
/// @return true if the token is supported, false otherwise.
function isTokenSupported(uint64 tokenID) external view returns (bool);
/// @notice Returns whether a chain is supported in SuiBridge with the given ID.
/// @param chainId The ID of the chain.
/// @return true if the chain is supported, false otherwise.
function isChainSupported(uint8 chainId) external view returns (bool);
/// @notice Returns the chain ID of the bridge.
function chainID() external view returns (uint8);
function investLpTokenIdOf(uint64 protocolType,uint64 underlyingTokenId) external view returns (uint64);
function underlyingTokenIdOf(uint64 protocolType,uint64 lpTokenId) external view returns (uint64);
/// @notice Event for the addition of a new token.
/// @param nonce The governance action nonce.
/// @param tokenIDs The IDs of the tokens added.
/// @param tokenAddresses The addresses of the tokens added.
/// @param suiDecimals The added token's decimal places on Sui.
/// @param tokenPrices The prices of the tokens added in USD.
event TokensAddedV2(
uint64 nonce,
uint64[] tokenIDs,
address[] tokenAddresses,
uint8[] suiDecimals,
uint64[] tokenPrices
);
/// @dev (deprecated in favor of TokensAddedV2)
event TokenAdded(uint64 tokenID, address tokenAddress, uint8 suiDecimal, uint64 tokenPrice);
/// @notice Event for the price update of a token.
/// @param nonce The governance action nonce.
/// @param tokenID The ID of the token updated.
/// @param tokenPrice The new price of the token in USD.
event TokenPriceUpdatedV2(uint64 nonce, uint64 tokenID, uint64 tokenPrice);
/// @dev (deprecated in favor of TokenPriceUpdatedV2)
event TokenPriceUpdated(uint64 tokenID, uint64 tokenPrice);
event LpTokenIdAdded(uint64 nonce,uint64 protocolType,uint64 underlyingTokenId,uint64 lpTokenId);
}
contracts/utils/BridgeUtils.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/// @title BridgeUtils
/// @notice This library defines the message format and constants for the Sui native bridge. It also
/// provides functions to encode and decode bridge messages and their payloads.
/// @dev This library only utilizes internal functions to enable upgradeability via the OpenZeppelin
/// UUPS proxy pattern (external libraries are not supported).
library BridgeUtils {
/* ========== STRUCTS ========== */
/// @dev A struct that represents a bridge message
/// @param messageType The type of the message, such as token transfer, blocklist, etc.
/// @param version The version of the message format
/// @param nonce The nonce of the message, used to prevent replay attacks
/// @param chainID The chain ID of the source chain (for token transfer messages this is the source chain)
/// @param payload The payload of the message, which depends on the message type
struct Message {
uint8 messageType;
uint8 version;
uint64 nonce;
uint8 chainID;
bytes payload;
}
/// @dev A struct that represents a token transfer payload
/// @param senderAddressLength The length of the sender address in bytes
/// @param senderAddress The address of the sender on the source chain
/// @param targetChain The chain ID of the target chain
/// @param recipientAddressLength The length of the target address in bytes
/// @param recipientAddress The address of the recipient on the target chain
/// @param tokenID The ID of the token to be transferred
/// @param amount The amount of the token to be transferred
struct TokenTransferPayload {
uint8 senderAddressLength;
bytes senderAddress;
uint8 targetChain;
uint8 recipientAddressLength;
address recipientAddress;
uint64 tokenID;
uint64 amount;
bytes txHash;
uint8 eventIdx;
}
/// @dev A struct that represents a token transfer payload
/// @param senderAddressLength The length of the sender address in bytes
/// @param senderAddress The address of the sender on the source chain
/// @param targetChain The chain ID of the target chain
/// @param recipientAddressLength The length of the target address in bytes
/// @param recipientAddress The address of the recipient on the target chain
/// @param tokenID The ID of the token to be transferred
/// @param amount The amount of the token to be transferred
struct TokenTransferPayloadV2 {
uint8 senderAddressLength;
bytes senderAddress;
uint8 targetChain;
uint8 recipientAddressLength;
address recipientAddress;
uint64 tokenID;
uint64 amount;
bytes txHash;
uint16 eventIdx;
}
/// @dev A struct that represents a defi transfer payload
/// @param senderAddressLength The length of the sender address in bytes
/// @param senderAddress The address of the sender on the source chain
/// @param targetChain The chain ID of the target chain
/// @param amount The amount of the token to be transferred
/// @param protocolType The type of the protocol, such as aave, compound, curve, etc.
/// @param protocolVersion The version of the protocol
/// @param protocolTokenID The ID of the token in the protocol
/// @param actionType The type of the action, such as stake, unstake, etc.
struct DefiTransferPayload {
uint8 senderAddressLength;
bytes senderAddress;
uint8 targetChain;
uint64 amount;
bytes txHash;
uint16 eventIdx;
uint64 protocolType;
uint64 protocolVersion;
uint64 protocolTokenID;
uint8 actionType;
uint64 principalAmount;
}
/* ========== CONSTANTS ========== */
// message Ids
uint8 public constant TOKEN_TRANSFER = 0;
uint8 public constant BLOCKLIST = 1;
uint8 public constant EMERGENCY_OP = 2;
uint8 public constant UPDATE_BRIDGE_LIMIT = 3;
uint8 public constant UPDATE_TOKEN_PRICE = 4;
uint8 public constant UPGRADE = 5;
uint8 public constant ADD_EVM_TOKENS = 7;
uint8 public constant UPDATE_BRIDGE_SINGLE_TRANSFER_LIMIT = 19;
uint8 public constant DEFI=23;
uint8 public constant UPDATE_INVEST_ADDRESS =26;
uint8 public constant ADD_LP_TOKEN_ID =27;
// Message type stake requirements
uint32 public constant TRANSFER_STAKE_REQUIRED = 3334;
uint32 public constant FREEZING_STAKE_REQUIRED = 450;
uint32 public constant UNFREEZING_STAKE_REQUIRED = 5001;
uint32 public constant UPGRADE_STAKE_REQUIRED = 5001;
uint16 public constant BLOCKLIST_STAKE_REQUIRED = 5001;
uint32 public constant BRIDGE_LIMIT_STAKE_REQUIRED = 5001;
uint32 public constant UPDATE_TOKEN_PRICE_STAKE_REQUIRED = 5001;
uint32 public constant ADD_EVM_TOKENS_STAKE_REQUIRED = 5001;
uint32 public constant UPDATE_BRIDGE_SINGLE_TRANSFER_LIMIT_STAKE_REQUIRED =5001;
uint32 public constant DEFI_STAKE_REQUIRED = 3334;
uint32 public constant ADD_LP_TOKEN_ID_STAKE_REQUIRED = 5001;
uint32 public constant UPDATE_INVEST_ADDRESS_STAKE_REQUIRED = 5001;
// token Ids
uint64 public constant SUI = 0;
uint64 public constant BTC = 1;
uint64 public constant ETH = 2;
uint64 public constant USDC = 3;
uint64 public constant USDT = 4;
uint64 public constant BNB = 6;
uint64 public constant OP =7;
uint64 public constant ARB =8;
uint64 public constant POL =9;
uint64 public constant AVAX =10;
string public constant MESSAGE_PREFIX = "SUI_BRIDGE_MESSAGE";
/* ========== INTERNAL FUNCTIONS ========== */
/// @notice Encodes a bridge message into bytes, using abi.encodePacked to concatenate the message fields.
/// @param message The bridge message to be encoded.
/// @return The encoded message as bytes.
function encodeMessage(Message memory message) internal pure returns (bytes memory) {
bytes memory prefixTypeAndVersion =
abi.encodePacked(MESSAGE_PREFIX, message.messageType, message.version);
bytes memory nonce = abi.encodePacked(message.nonce);
bytes memory chainID = abi.encodePacked(message.chainID);
return bytes.concat(prefixTypeAndVersion, nonce, chainID, message.payload);
}
/// @notice Computes the hash of a bridge message using keccak256.
/// @param _message The bridge message to be hashed.
/// @return The hash of the message.
function computeHash(Message memory _message) internal pure returns (bytes32) {
return keccak256(encodeMessage(_message));
}
/// @notice returns the required stake for the provided message type.
/// @dev The function will revert if the message type is invalid.
/// @param _message The bridge message to be used to determine the required stake.
/// @return The required stake for the provided message type.
function requiredStake(Message memory _message) internal pure returns (uint32) {
if (_message.messageType == TOKEN_TRANSFER) {
return TRANSFER_STAKE_REQUIRED;
} else if (_message.messageType == BLOCKLIST) {
return BLOCKLIST_STAKE_REQUIRED;
} else if (_message.messageType == EMERGENCY_OP) {
bool isFreezing = decodeEmergencyOpPayload(_message.payload);
if (isFreezing) return FREEZING_STAKE_REQUIRED;
return UNFREEZING_STAKE_REQUIRED;
} else if (_message.messageType == UPDATE_BRIDGE_LIMIT) {
return BRIDGE_LIMIT_STAKE_REQUIRED;
} else if (_message.messageType == UPDATE_TOKEN_PRICE) {
return UPDATE_TOKEN_PRICE_STAKE_REQUIRED;
} else if (_message.messageType == UPGRADE) {
return UPGRADE_STAKE_REQUIRED;
} else if (_message.messageType == ADD_EVM_TOKENS) {
return ADD_EVM_TOKENS_STAKE_REQUIRED;
} else if (_message.messageType == UPDATE_BRIDGE_SINGLE_TRANSFER_LIMIT){
return UPDATE_BRIDGE_SINGLE_TRANSFER_LIMIT_STAKE_REQUIRED;
}else if(_message.messageType == DEFI){
return DEFI_STAKE_REQUIRED;
}else if(_message.messageType == ADD_LP_TOKEN_ID){
return ADD_LP_TOKEN_ID_STAKE_REQUIRED;
}else if(_message.messageType == UPDATE_INVEST_ADDRESS){
return UPDATE_INVEST_ADDRESS_STAKE_REQUIRED;
}else{
revert("BridgeUtils: Invalid message type");
}
}
/// @notice Converts the provided token amount to the Sui decimal adjusted amount.
/// @param erc20Decimal The erc20 decimal value for the token.
/// @param suiDecimal The sui decimal value for the token.
/// @param amount The ERC20 amount of the tokens to convert to Sui.
/// @return Sui converted amount.
function convertERC20ToSuiDecimal(uint8 erc20Decimal, uint8 suiDecimal, uint256 amount)
internal
pure
returns (uint64)
{
require(amount > 0, "BridgeUtils: Insufficient amount provided");
if (erc20Decimal == suiDecimal) {
// ensure provided amount is greater than 0
require(amount > 0, "BridgeUtils: Insufficient amount provided");
// Ensure converted amount fits within uint64
require(amount <= type(uint64).max, "BridgeUtils: Amount too large for uint64");
return uint64(amount);
}
uint256 adjustedAmount;
if (erc20Decimal > suiDecimal) {
uint256 factor = 10 ** (erc20Decimal - suiDecimal);
adjustedAmount = amount / factor;
} else {
uint256 factor = 10 ** (suiDecimal - erc20Decimal);
adjustedAmount = amount * factor;
}
require(adjustedAmount > 0, "BridgeUtils: Resulting amount too small");
require(adjustedAmount <= type(uint64).max, "BridgeUtils: Amount too large for uint64");
return uint64(adjustedAmount);
}
/// @notice Converts the provided Sui decimal adjusted amount to the ERC20 token amount.
/// @param erc20Decimal The erc20 decimal value for the token.
/// @param suiDecimal The sui decimal value for the token.
/// @param amount The Sui amount of the tokens to convert to ERC20.
/// @return ERC20 converted amount.
function convertSuiToERC20Decimal(
uint8 erc20Decimal,
uint8 suiDecimal,
uint64 amount
) internal pure returns (uint256) {
require(amount > 0, "BridgeUtils: Amount must be greater than zero");
if (suiDecimal == erc20Decimal) {
return uint256(amount);
}
uint256 adjustedAmount;
if (erc20Decimal > suiDecimal) {
// Upscale: increase precision
uint256 factor = 10 ** (erc20Decimal - suiDecimal);
adjustedAmount = uint256(amount) * factor;
} else {
// Downscale: reduce precision, may lose precision
uint256 factor = 10 ** (suiDecimal - erc20Decimal);
adjustedAmount = uint256(amount) / factor;
require(adjustedAmount > 0, "BridgeUtils: Resulting amount too small");
}
return adjustedAmount;
}
/// @notice Decodes a token transfer payload from bytes to a TokenTransferPayload struct.
/// @dev The function will revert if the payload length is invalid.
/// TokenTransfer payload is 64 bytes.
/// byte 0 : sender address length
/// bytes 1-32 : sender address (as we only support Sui now, it has to be 32 bytes long)
/// bytes 33 : target chain id
/// byte 34 : target address length
/// bytes 35-54 : target address
/// byte 55 : token id
/// bytes 56-63 : amount
/// @param _payload The payload to be decoded.
/// @return The decoded token transfer payload as a TokenTransferPayload struct.
function decodeTokenTransferPayload(bytes memory _payload)
internal
pure
returns (TokenTransferPayload memory)
{
require(_payload.length >= 64, "BridgeUtils: TokenTransferPayload must be at least 64 bytes");
uint8 senderAddressLength = uint8(_payload[0]);
require(
senderAddressLength == 32,
"BridgeUtils: Invalid sender address length, Sui address must be 32 bytes"
);
// used to offset already read bytes
uint8 offset = 1;
// extract sender address from payload bytes 1-32
bytes memory senderAddress = new bytes(senderAddressLength);
for (uint256 i; i < senderAddressLength; i++) {
senderAddress[i] = _payload[i + offset];
}
// move offset past the sender address length
offset += senderAddressLength;
// target chain is a single byte
uint8 targetChain = uint8(_payload[offset++]);
// target address length is a single byte
uint8 recipientAddressLength = uint8(_payload[offset++]);
require(
recipientAddressLength == 20,
"BridgeUtils: Invalid target address length, EVM address must be 20 bytes"
);
// extract target address from payload (35-54)
address recipientAddress;
// why `add(recipientAddressLength, offset)`?
// At this point, offset = 35, recipientAddressLength = 20. `mload(add(payload, 55))`
// reads the next 32 bytes from bytes 23 in paylod, because the first 32 bytes
// of payload stores its length. So in reality, bytes 23 - 54 is loaded. During
// casting to address (20 bytes), the least sigificiant bytes are retained, namely
// `recipientAddress` is bytes 35-54
assembly {
recipientAddress := mload(add(_payload, add(recipientAddressLength, offset)))
}
// move offset past the target address length
offset += recipientAddressLength;
// token id
uint8 tokenIDLength = 8;
uint64 tokenID;
assembly {
tokenID := shr(192, mload(add(add(_payload, 0x20), offset)))
}
offset += tokenIDLength;
// extract amount from payload
uint64 amount;
uint8 amountLength = 8; // uint64 = 8 bits
// Why `add(amountLength, offset)`?
// At this point, offset = 56, amountLength = 8. `mload(add(payload, 64))`
// reads the next 32 bytes from bytes 32 in paylod, because the first 32 bytes
// of payload stores its length. So in reality, bytes 32 - 63 is loaded. During
// casting to uint64 (8 bytes), the least sigificiant bytes are retained, namely
// `recipientAddress` is bytes 56-63
assembly {
amount := mload(add(_payload, add(amountLength, offset)))
}
// move offset past the amount
offset = offset + amountLength;
// extract tx hash from payload
bytes memory txHash = new bytes(_payload.length - offset - 1); // -1 for eventIdx
for (uint256 i; i < _payload.length - offset - 1; i++) {
txHash[i] = _payload[i + offset];
}
// move offset past the tx hash
offset = offset + uint8(txHash.length);
// event idx is a single byte
uint8 eventIdx = uint8(_payload[offset]);
return TokenTransferPayload(
senderAddressLength,
senderAddress,
targetChain,
recipientAddressLength,
recipientAddress,
tokenID,
amount,
txHash,
eventIdx
);
}
/// @notice Decodes a token transfer payload from bytes to a TokenTransferPayload struct.
/// @dev The function will revert if the payload length is invalid.
/// TokenTransfer payload is 64 bytes.
/// byte 0 : sender address length
/// bytes 1-32 : sender address (as we only support Sui now, it has to be 32 bytes long)
/// bytes 33 : target chain id
/// byte 34 : target address length
/// bytes 35-54 : target address
/// byte 55 : token id
/// bytes 56-63 : amount
/// @param _payload The payload to be decoded.
/// @return The decoded token transfer payload as a TokenTransferPayload struct.
function decodeTokenTransferPayloadV2(bytes memory _payload)
internal
pure
returns (TokenTransferPayloadV2 memory)
{
require(_payload.length >= 64, "BridgeUtils: TokenTransferPayload must be at least 64 bytes");
uint8 senderAddressLength = uint8(_payload[0]);
require(
senderAddressLength == 32,
"BridgeUtils: Invalid sender address length, Sui address must be 32 bytes"
);
// used to offset already read bytes
uint8 offset = 1;
// extract sender address from payload bytes 1-32
bytes memory senderAddress = new bytes(senderAddressLength);
for (uint256 i; i < senderAddressLength; i++) {
senderAddress[i] = _payload[i + offset];
}
// move offset past the sender address length
offset += senderAddressLength;
// target chain is a single byte
uint8 targetChain = uint8(_payload[offset++]);
// target address length is a single byte
uint8 recipientAddressLength = uint8(_payload[offset++]);
require(
recipientAddressLength == 20,
"BridgeUtils: Invalid target address length, EVM address must be 20 bytes"
);
// extract target address from payload (35-54)
address recipientAddress;
// why `add(recipientAddressLength, offset)`?
// At this point, offset = 35, recipientAddressLength = 20. `mload(add(payload, 55))`
// reads the next 32 bytes from bytes 23 in paylod, because the first 32 bytes
// of payload stores its length. So in reality, bytes 23 - 54 is loaded. During
// casting to address (20 bytes), the least sigificiant bytes are retained, namely
// `recipientAddress` is bytes 35-54
assembly {
recipientAddress := mload(add(_payload, add(recipientAddressLength, offset)))
}
// move offset past the target address length
offset += recipientAddressLength;
// token id
uint8 tokenIDLength = 8;
uint64 tokenID;
assembly {
tokenID := shr(192, mload(add(add(_payload, 0x20), offset)))
}
offset += tokenIDLength;
// extract amount from payload
uint64 amount;
uint8 amountLength = 8; // uint64 = 8 bits
// Why `add(amountLength, offset)`?
// At this point, offset = 56, amountLength = 8. `mload(add(payload, 64))`
// reads the next 32 bytes from bytes 32 in paylod, because the first 32 bytes
// of payload stores its length. So in reality, bytes 32 - 63 is loaded. During
// casting to uint64 (8 bytes), the least sigificiant bytes are retained, namely
// `recipientAddress` is bytes 56-63
assembly {
amount := mload(add(_payload, add(amountLength, offset)))
}
// move offset past the amount
offset = offset + amountLength;
// extract tx hash from payload
bytes memory txHash = new bytes(_payload.length - offset - 2); // -1 for eventIdx
for (uint256 i; i < _payload.length - offset - 2; i++) {
txHash[i] = _payload[i + offset];
}
// move offset past the tx hash
offset = offset + uint8(txHash.length);
uint16 eventIdx;
assembly {
eventIdx := shr(240, mload(add(_payload, add(0x20, offset))))
}
return TokenTransferPayloadV2(
senderAddressLength,
senderAddress,
targetChain,
recipientAddressLength,
recipientAddress,
tokenID,
amount,
txHash,
eventIdx
);
}
/// @dev A struct that represents a defi transfer payload
/// @param _payload The payload to be decoded.
/// @return The decoded defi transfer payload as a DefiTransferPayload struct.
function decodeDefiTransferPayload(bytes memory _payload)
internal
pure
returns (DefiTransferPayload memory)
{
require(_payload.length >= 67, "BridgeUtils: DefiTransferPayload must be at least 67 bytes");
uint8 senderAddressLength = uint8(_payload[0]);
require(
senderAddressLength == 32,
"BridgeUtils: Invalid sender address length, Sui address must be 32 bytes"
);
// used to offset already read bytes
uint8 offset = 1;
// extract sender address from payload bytes 1-32
bytes memory senderAddress = new bytes(senderAddressLength);
for (uint256 i; i < senderAddressLength; i++) {
senderAddress[i] = _payload[i + offset];
}
// move offset past the sender address length
offset += senderAddressLength;
// target chain is a single byte
uint8 targetChain = uint8(_payload[offset++]);
// extract amount from payload
uint64 amount;
uint8 amountLength = 8; // uint64 = 8 bytes
// extract amount from payload
assembly {
amount := mload(add(_payload, add(amountLength, offset)))
}
// move offset past the amount
offset = offset + amountLength;
// extract tx hash from payload
// Calculate transaction hash length (remaining bytes minus fixed-size fields at the end)
uint256 txHashLength = _payload.length - offset - 2 - 8 - 8 - 8 - 1 - 8; // -2 eventIdx, -8 protocolType, -8 protocolVersion, -8 protocolTokenID, -1 actionType, -8 principalAmount
bytes memory txHash = new bytes(txHashLength);
for (uint256 i; i < txHashLength; i++) {
txHash[i] = _payload[i + offset];
}
// move offset past the tx hash
offset = offset + uint8(txHash.length);
uint16 eventIdx;
assembly {
eventIdx := shr(240, mload(add(_payload, add(0x20, offset))))
}
offset += 2; // uint16 = 2 bytes
// extract protocolType (uint64)
uint64 protocolType;
assembly {
protocolType := shr(192, mload(add(add(_payload, 0x20), offset)))
}
offset += 8; // uint64 = 8 bytes
// extract protocolVersion (uint64)
uint64 protocolVersion;
assembly {
protocolVersion :=shr(192, mload(add(add(_payload, 0x20), offset)))
}
offset += 8; // uint64 = 8 bytes
uint64 protocolTokenID;
assembly {
protocolTokenID := shr(192, mload(add(add(_payload, 0x20), offset)))
}
offset += 8;
// extract actionType (uint8)
uint8 actionType = uint8(_payload[offset]);
offset += 1;
// extract principalAmount (uint64)
uint64 principalAmount;
assembly {
principalAmount := shr(192, mload(add(add(_payload, 0x20), offset)))
}
// offset += 8;
return DefiTransferPayload(
senderAddressLength,
senderAddress,
targetChain,
amount,
txHash,
eventIdx,
protocolType,
protocolVersion,
protocolTokenID,
actionType,
principalAmount
);
}
function decodeInvestAddressPayload(bytes memory _payload) internal pure returns (address) {
require(_payload.length == 20, "BridgeUtils: Invalid payload length");
address investAddress;
assembly {
investAddress := shr(96, mload(add(_payload, 0x20)))
}
return investAddress;
}
/// @notice Decodes a blocklist payload from bytes to a boolean and an array of addresses.
/// @dev The function will revert if the payload length is invalid.
/// Blocklist payload is 2 + 20 * n bytes.
/// byte 0 : blocklist type (0 = blocklist, 1 = unblocklist)
/// byte 1 : number of addresses in the blocklist
/// bytes 2-n : addresses
/// @param _payload The payload to be decoded.
/// @return blocklisting status and the array of addresses to be blocklisted/unblocklisted.
function decodeBlocklistPayload(bytes memory _payload)
internal
pure
returns (bool, address[] memory)
{
uint8 blocklistType = uint8(_payload[0]);
uint8 membersLength = uint8(_payload[1]);
address[] memory members = new address[](membersLength);
uint8 offset = 2;
require((_payload.length - offset) % 20 == 0, "BridgeUtils: Invalid payload length");
for (uint8 i; i < membersLength; i++) {
// Calculate the starting index for each address
offset += i * 20;
address member;
// Extract each address
assembly {
member := mload(add(add(_payload, 20), offset))
}
// Store the extracted address
members[i] = member;
}
// blocklistType: 0 = blocklist, 1 = unblocklist
bool blocklisted = (blocklistType == 0);
return (blocklisted, members);
}
/// @notice Decodes an emergency operation payload from bytes to a boolean.
/// @dev The function will revert if the payload length is invalid.
/// Emergency operation payload is a single byte.
/// byte 0 : operation type (0 = freezing, 1 = unfreezing)
/// @param _payload The payload to be decoded.
/// @return The emergency operation type.
function decodeEmergencyOpPayload(bytes memory _payload) internal pure returns (bool) {
require(_payload.length == 1, "BridgeUtils: Invalid payload length");
uint8 emergencyOpCode = uint8(_payload[0]);
require(emergencyOpCode <= 1, "BridgeUtils: Invalid op code");
return emergencyOpCode == 0;
}
/// @notice Decodes an update limit payload from bytes to a chain ID and a new limit.
/// @dev The function will revert if the payload length is invalid.
/// Update limit payload is 9 bytes.
/// byte 0 : chain ID
/// bytes 1-8 : new limit
/// @param _payload The payload to be decoded.
/// @return senderChainID the sending chain ID to update the limit of.
/// @return newLimit the new limit of the sending chain ID.
function decodeUpdateLimitPayload(bytes memory _payload)
internal
pure
returns (uint8 senderChainID, uint64 newLimit)
{
require(_payload.length == 9, "BridgeUtils: Invalid payload length");
senderChainID = uint8(_payload[0]);
// Extracts the uint64 value by loading 32 bytes starting just after the first byte.
// Position uint64 to the least significant bits by shifting it 192 bits to the right.
assembly {
newLimit := shr(192, mload(add(add(_payload, 0x20), 1)))
}
}
/// @notice Decodes an update limit payload from bytes to a chain ID and a new limit.
/// @dev The function will revert if the payload length is invalid.
/// Update limit payload is 9 bytes.
/// byte 0 : chain ID
/// bytes 1-8 : new limit
/// @param _payload The payload to be decoded.
/// @return senderChainID the sending chain ID to update the limit of.
/// @return newLimit the new limit of the sending chain ID.
function decodeUpdateSingleTransferLimitPayload(bytes memory _payload)
internal
pure
returns (uint8 senderChainID, uint64 newLimit)
{
require(_payload.length == 9, "BridgeUtils: Invalid payload length");
senderChainID = uint8(_payload[0]);
assembly {
newLimit := shr(192, mload(add(add(_payload, 0x20), 1)))
//newLimit := mload(add(add(_payload, 0x20), 1))
}
}
/// @notice Decodes an upgrade payload from bytes to a proxy address, an implementation address,
/// and call data.
/// @dev The function will revert if the payload length is invalid. The payload is expected to be
/// abi encoded.
/// @param _payload The payload to be decoded.
/// @return proxy the address of the proxy to be upgraded.
/// @return implementation the address of the new implementation contract.
/// @return callData the call data to be used in the upgrade.
function decodeUpgradePayload(bytes memory _payload)
internal
pure
returns (address, address, bytes memory)
{
(address proxy, address implementation, bytes memory callData) =
abi.decode(_payload, (address, address, bytes));
return (proxy, implementation, callData);
}
/// @notice Decodes an update token price payload from bytes to a token ID and a new price.
/// @dev The function will revert if the payload length is invalid.
/// Update token price payload is 9 bytes.
/// byte 0-7 : token ID
/// bytes 8-15 : new price
/// @param _payload The payload to be decoded.
/// @return tokenID the token ID to update the price of.
/// @return tokenPrice the new price of the token.
function decodeUpdateTokenPricePayload(bytes memory _payload)
internal
pure
returns (uint64 tokenID, uint64 tokenPrice)
{
require(_payload.length == 16, "BridgeMessage: Invalid payload length");
assembly {
tokenID := shr(192, mload(add(add(_payload, 0x20), 0)))
}
// Extracts the uint64 value by loading 32 bytes starting just after the first byte.
// Position uint64 to the least significant bits by shifting it 192 bits to the right.
assembly {
tokenPrice := shr(192, mload(add(add(_payload, 0x20), 8)))
}
}
/// @notice Decodes an add LP token payload from bytes to protocol type, token ID, and LP token ID.
/// @dev The function will revert if the payload length is invalid.
/// Add LP token payload is 24 bytes.
/// bytes 0-7 : protocol type (uint64)
/// bytes 8-15 : token ID (uint64)
/// bytes 16-23 : LP token ID (uint64)
/// @param _payload The payload to be decoded.
/// @return protocolType The protocol type identifier.
/// @return tokenID The underlying token ID.
/// @return lpTokenId The LP token ID associated with the underlying token
function decodeAddLpTokenPayload(bytes memory _payload)
internal
pure
returns(uint64 protocolType,uint64 tokenID, uint64 lpTokenId )
{
require(_payload.length >= 24, "BridgeUtils: AddLpTokenPayload must be at least 24 bytes");
uint8 offset = 0;
// Extract protocol type (uint64 - 8 bytes)
assembly {
protocolType := shr(192, mload(add(add(_payload, 0x20), offset)))
}
offset += 8;
// Extract token ID (uint64 - 8 bytes)
assembly {
tokenID := shr(192, mload(add(add(_payload, 0x20), offset)))
}
offset += 8;
// Extract LP token ID (uint64 - 8 bytes)
assembly {
lpTokenId := shr(192, mload(add(add(_payload, 0x20), offset)))
}
return (protocolType, tokenID, lpTokenId);
}
/// @notice Decodes an add token payload from bytes to a token ID, a token address, and a token price.
/// @dev The function will revert if the payload length is invalid.
/// Add token payload is 5 + 2n + 20n + 8n bytes (assuming all arrays are of length n).
/// byte 0 : is native
/// byte 1 : number of token IDs
/// byte 2 -> n : token IDs
/// byte n + 1 : number of addresses
/// bytes n + 2 -> m : addresses
/// byte m + 1 : number of sui decimals
/// bytes m + 2 -> i : sui decimals
/// byte i + 1 : number of prices
/// bytes i + 2 -> j : prices (uint64)
/// @param _payload The payload to be decoded.
/// @return native whether the token is native to the chain.
/// @return tokenIDs the token ID to be added.
/// @return tokenAddresses the address of the token to be added.
/// @return suiDecimals the Sui decimal places of the tokens to be added.
/// @return tokenPrices the price of the tokens to be added.
function decodeAddTokensPayload(bytes memory _payload)
internal
pure
returns (
bool native,
uint64[] memory tokenIDs,
address[] memory tokenAddresses,
uint8[] memory suiDecimals,
uint64[] memory tokenPrices
)
{
native = _payload[0] != bytes1(0);
uint8 tokenCount = uint8(_payload[1]);
// Calculate the starting index for each token ID
uint8 offset = 2;
tokenIDs = new uint64[](tokenCount);
for (uint8 i; i < tokenCount; i++) {
uint64 tokenID;
assembly {
tokenID := shr(192, mload(add(add(_payload, 0x20), offset)))
}
offset += 8;
tokenIDs[i] = tokenID;
}
uint8 addressCount = uint8(_payload[offset++]);
tokenAddresses = new address[](addressCount);
for (uint8 i; i < addressCount; i++) {
// Calculate the starting index for each address
address tokenAddress;
// Extract each address
assembly {
tokenAddress := mload(add(add(_payload, 20), offset))
}
offset += 20;
// Store the extracted address
tokenAddresses[i] = tokenAddress;
}
uint8 decimalCount = uint8(_payload[offset++]);
suiDecimals = new uint8[](decimalCount);
for (uint8 i; i < decimalCount; i++) {
suiDecimals[i] = uint8(_payload[offset++]);
}
uint8 priceCount = uint8(_payload[offset++]);
tokenPrices = new uint64[](priceCount);
for (uint8 i; i < priceCount; i++) {
// Calculate the starting index for each price
uint64 tokenPrice;
// Extract each price
assembly {
tokenPrice := shr(192, mload(add(add(_payload, 0x20), offset)))
}
offset += 8;
// Store the extracted price
tokenPrices[i] = tokenPrice;
}
}
}
contracts/utils/CommitteeUpgradeable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "../interfaces/IBridgeCommittee.sol";
import "./MessageVerifier.sol";
/// @title CommitteeUpgradeable
/// @notice This contract enables message signature verification using a BridgeCommittee contract,
/// in addition to providing an interface for upgradeability via signed message verification.
/// @dev The contract is intended to be inherited by contracts that require message verification and
/// upgradeability.
abstract contract CommitteeUpgradeable is
UUPSUpgradeable,
MessageVerifier,
ReentrancyGuardUpgradeable
{
/* ========== STATE VARIABLES ========== */
bool private _upgradeAuthorized;
// upgradeablity storage gap
uint256[50] private __gap;
/* ========== INITIALIZER ========== */
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function __CommitteeUpgradeable_init(address _committee) internal onlyInitializing {
__ReentrancyGuard_init();
__MessageVerifier_init(_committee);
committee = IBridgeCommittee(_committee);
}
/* ========== EXTERNAL FUNCTIONS ========== */
/// @notice Enables the upgrade of the inheriting contract by verifying the provided signatures.
/// @dev The function will revert if the provided signatures or message is invalid.
/// @param signatures The array of signatures to be verified.
/// @param message The BridgeUtils to be verified.
function upgradeWithSignatures(bytes[] memory signatures, BridgeUtils.Message memory message)
external
nonReentrant
verifyMessageAndSignatures(message, signatures, BridgeUtils.UPGRADE)
{
// decode the upgrade payload
(address proxy, address implementation, bytes memory callData) =
BridgeUtils.decodeUpgradePayload(message.payload);
// verify proxy address
require(proxy == address(this), "CommitteeUpgradeable: Invalid proxy address");
// authorize upgrade
_upgradeAuthorized = true;
// upgrade contract
upgradeToAndCall(implementation, callData);
emit ContractUpgraded(message.nonce, proxy, implementation);
}
/* ========== INTERNAL FUNCTIONS ========== */
/// @notice Authorizes the upgrade of the inheriting contract.
/// @dev The _upgradeAuthorized state variable can only be set with the upgradeWithSignatures
/// function, meaning that the upgrade can only be authorized by the committee.
function _authorizeUpgrade(address) internal override {
require(_upgradeAuthorized, "CommitteeUpgradeable: Unauthorized upgrade");
_upgradeAuthorized = false;
}
/// @notice Event emitted when the contract is upgraded
/// @param nonce The nonce of the upgrade message.
/// @param proxy The address of the proxy contract.
/// @param implementation The address of the new implementation.
event ContractUpgraded(uint256 nonce, address proxy, address implementation);
}
contracts/utils/MessageVerifier.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "../interfaces/IBridgeCommittee.sol";
/// @title MessageVerifier
/// @notice This contract provides an interface to verify messages and their signatures
/// using a BridgeCommittee contract. This contract is also responsible for maintaining
/// nonces for each message type to prevent replay attacks.
/// @dev The contract is intended to be inherited by contracts that require message and signature
/// verification.
abstract contract MessageVerifier is Initializable {
/* ========== STATE VARIABLES ========== */
IBridgeCommittee public committee;
mapping(uint8 messageType => uint64 nonce) public nonces;
/* ========== INITIALIZER ========== */
function __MessageVerifier_init(address _committee) internal onlyInitializing {
committee = IBridgeCommittee(_committee);
}
/* ========== MODIFIERS ========== */
/// @notice Verifies the provided message and signatures using the BridgeCommittee contract.
/// @dev The function will revert if the message type does not match the expected type,
/// if the signatures are invalid, or if the message nonce is invalid.
/// @param message The BridgeUtils to be verified.
/// @param signatures The array of signatures to be verified.
/// @param messageType The expected message type of the provided message.
modifier verifyMessageAndSignatures(
BridgeUtils.Message memory message,
bytes[] memory signatures,
uint8 messageType
) {
// verify message type
require(message.messageType == messageType, "MessageVerifier: message does not match type");
// verify signatures
committee.verifySignatures(signatures, message);
// increment message type nonce
if (messageType != BridgeUtils.TOKEN_TRANSFER && messageType!=BridgeUtils.DEFI) {
// verify chain ID
require(
message.chainID == committee.config().chainID(), "MessageVerifier: Invalid chain ID"
);
require(message.nonce == nonces[message.messageType], "MessageVerifier: Invalid nonce");
nonces[message.messageType]++;
}
_;
}
}
dependencies/@openzeppelin-contracts-5.0.1/interfaces/draft-IERC1822.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
dependencies/@openzeppelin-contracts-5.0.1/proxy/ERC1967/ERC1967Utils.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.20;
import {IBeacon} from "../beacon/IBeacon.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*/
library ERC1967Utils {
// We re-declare ERC-1967 events here because they can't be used directly from IERC1967.
// This will be fixed in Solidity 0.8.21. At that point we should remove these events.
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
dependencies/@openzeppelin-contracts-5.0.1/proxy/beacon/IBeacon.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
dependencies/@openzeppelin-contracts-5.0.1/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
dependencies/@openzeppelin-contracts-5.0.1/token/ERC20/extensions/IERC20Metadata.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
dependencies/@openzeppelin-contracts-5.0.1/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
dependencies/@openzeppelin-contracts-5.0.1/utils/StorageSlot.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
dependencies/@openzeppelin-contracts-upgradeable-5.0.1/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
dependencies/@openzeppelin-contracts-upgradeable-5.0.1/proxy/utils/UUPSUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.20;
import {IERC1822Proxiable} from "@openzeppelin/contracts/interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Utils.sol";
import {Initializable} from "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC1967-compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
dependencies/@openzeppelin-contracts-upgradeable-5.0.1/utils/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// On the first call to nonReentrant, _status will be NOT_ENTERED
if ($._status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
$._status = ENTERED;
}
function _nonReentrantAfter() private {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
$._status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
Compiler settingsShow
{
"viaIR": true,
"metadata": {
"appendCBOR": true,
"bytecodeHash": "ipfs",
"useLiteralContent": false
},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "shanghai",
"remappings": [
"@forge-std/=dependencies/forge-std-1.9.2/src/",
"@openzeppelin/foundry-upgrades/=dependencies/openzeppelin-foundry-upgrades-0.3.1/src/",
"@openzeppelin/contracts/=dependencies/@openzeppelin-contracts-5.0.1/",
"@openzeppelin/contracts-upgradeable/=dependencies/@openzeppelin-contracts-upgradeable-5.0.1/",
"@forge-std-1.9.2/=dependencies/forge-std-1.9.2/",
"@openzeppelin-foundry-upgrades-0.3.1/=dependencies/openzeppelin-foundry-upgrades-0.3.1/",
"@openzeppelin-contracts-upgradeable-5.0.1/=dependencies/@openzeppelin-contracts-upgradeable-5.0.1/",
"@openzeppelin-contracts-5.0.1/=dependencies/@openzeppelin-contracts-5.0.1/",
"ds-test/=dependencies/openzeppelin-foundry-upgrades-0.3.1/lib/solidity-stringutils/lib/ds-test/src/",
"forge-std-1.9.2/=dependencies/forge-std-1.9.2/src/",
"forge-std/=dependencies/openzeppelin-foundry-upgrades-0.3.1/lib/forge-std/src/",
"openzeppelin-foundry-upgrades-0.3.1/=dependencies/openzeppelin-foundry-upgrades-0.3.1/src/",
"openzeppelin-foundry-upgrades/=dependencies/openzeppelin-foundry-upgrades-0.3.1/src/",
"solidity-stringutils/=dependencies/openzeppelin-foundry-upgrades-0.3.1/lib/solidity-stringutils/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.