Source Code
Overview
S Balance
S Value
$0.00Latest 1 from a total of 1 transactions
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| _become | 20541234 | 285 days ago | IN | 0 S | 0.0018071 |
View more zero value Internal Transactions in Advanced View mode
Advanced mode:
Cross-Chain Transactions
Loading...
Loading
Contract Name:
RegistryV1
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
Yes with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "../interfaces/IRegistryV1.sol";
import "../interfaces/ITradingFloorV1.sol";
import "../interfaces/ChipEnumsV1.sol";
import "./RegistryStorage.sol";
import "./RegistryProxy.sol";
import "../unifiedDeployment/factories/LexProxiesFactory.sol";
import "../unifiedDeployment/factories/ChipsFactory.sol";
/**
* @title RegistryV1
* @dev Main administration contract for the Lynx platform, keeping track of all the system's contracts and their versions
* Version notes :
* 1.01 :
* - Adds 'ILynxVersionedContract' interface
* - Opens up the 'addNewSettlementAssetInTradingFloor' function
*/
contract RegistryV1 is
RegistryStorage,
IRegistryV1Functionality,
ILynxVersionedContract
{
event AddressUpdated(string indexed name, address a);
event NewVersionPublished(
uint256 indexed version,
bytes32 indexed contractNameHash,
address contractImplementation
);
event FeesManagerSet(address indexed asset, address indexed feesManager);
event TradingFloorSupported(address indexed tradingFloor);
event SettlementAssetForTradingFloorAdded(
address indexed tradingFloor,
address indexed settlementAsset,
address indexed lexPool,
address poolAccountant
);
event ValidChipSpenderTargetByRoleSet(
address indexed chip,
string indexed role,
address indexed spender
);
event ValidChipBurnHandlerSet(
address indexed chip,
address indexed burnHandler
);
// ***** Constants (ILynxVersionedContract interface) *****
string public constant CONTRACT_NAME = "Registry";
string public constant CONTRACT_VERSION = "1010"; // 1.01
// ***** Views (ILynxVersionedContract interface) *****
function getContractName() external pure override returns (string memory) {
return CONTRACT_NAME;
}
function getContractVersion() external pure override returns (string memory) {
return CONTRACT_VERSION;
}
// ***** Initialization functions *****
/**
* @notice Part of the Proxy mechanism
*/
function _become(RegistryProxy registryProxy) public {
require(msg.sender == registryProxy.admin(), "!proxy.admin");
require(registryProxy._acceptImplementation() == 0, "fail");
}
// ***** Global Lock functions *****
modifier onlyLockOwner() {
require(msg.sender == systemLockOwner, "!LockOwner");
_;
}
function lock() external override {
require(validSystemLockOwners[msg.sender], "!ValidLocker");
require(systemLockOwner == address(0), "AlreadyLocked");
systemLockOwner = msg.sender;
}
function freeLock() external override onlyLockOwner {
systemLockOwner = address(0);
}
function isTradersPortalAndLocker(
address _address
) external view returns (bool) {
return (systemLockOwner == _address) && (_address == tradersPortal);
}
function isTriggersAndLocker(address _address) external view returns (bool) {
return (systemLockOwner == _address) && (_address == triggers);
}
function isTradersPortalOrTriggersAndLocker(
address _address
) external view returns (bool) {
return
(systemLockOwner == _address) &&
(_address == tradersPortal || _address == triggers);
}
// ***** Views *****
/**
* @return true if the given implementation is valid for the given proxy name
*/
function isImplementationValidForProxy(
bytes32 proxyNameHash,
address _implementation
) external view returns (bool) {
require(_implementation != address(0), "ZERO_ADDRESS");
address latestImplementation = getLatestImplementationForProxyByHashInternal(
proxyNameHash
);
return latestImplementation == _implementation;
}
/**
* @return The address of the latest implementation version for the given proxy name hash
*/
function getLatestImplementationForProxyByHash(
bytes32 proxyNameHash
) external view returns (address) {
return getLatestImplementationForProxyByHashInternal(proxyNameHash);
}
/**
* @return The address of the latest implementation version for the given proxy name
*/
function getLatestImplementationForProxyByName(
string calldata proxyName
) external view returns (address) {
bytes32 nameHash = keccak256(abi.encodePacked(proxyName));
return getLatestImplementationForProxyByHashInternal(nameHash);
}
/**
* @return An array of all supported trading floors
*/
function getAllSupportedTradingFloors()
external
view
returns (address[] memory)
{
return supportedTradingFloors;
}
/**
* @return An array of all supported settlement assets
*/
function getSettlementAssetsForTradingFloor(
address _tradingFloor
) external view returns (address[] memory) {
return settlementAssetsForTradingFloor[_tradingFloor];
}
/**
* @return The address matching for the given role
*/
function getDynamicRoleAddress(
string calldata _role
) external view returns (address) {
bytes32 roleHash = keccak256(abi.encodePacked(_role));
return dynamicRoleAddresses[roleHash];
}
/**
* @return The spender role address that is set for this chip
*/
function getValidSpenderTargetForChipByRole(
address chip,
string calldata role
) external view returns (address) {
bytes32 roleHash = keccak256(abi.encodePacked(role));
return validSpenderTargetForChipByRole[chip][roleHash];
}
// ***** Admin Functions *****
/**
* Setter for any dynamic roles addresses
*/
function setDynamicRoleAddress(
string calldata _role,
address _address
) external onlyAdmin {
bytes32 roleHash = keccak256(abi.encodePacked(_role));
dynamicRoleAddresses[roleHash] = _address;
emit AddressUpdated(_role, _address);
}
/**
* Setter for the 'OrderBook' contract
*/
function setOrderBook(address _orderBook) external onlyAdmin {
updateLockerAddressInternal(orderBook, _orderBook, "orderBook");
orderBook = _orderBook;
}
/**
* Setter for the 'TradersPortal' contract
*/
function setTradersPortal(address _tradersPortal) external onlyAdmin {
updateLockerAddressInternal(tradersPortal, _tradersPortal, "tradersPortal");
tradersPortal = _tradersPortal;
}
/**
* Setter for the 'Triggers' contract
*/
function setTriggers(address _triggers) external onlyAdmin {
updateLockerAddressInternal(triggers, _triggers, "triggers");
triggers = _triggers;
}
/**
* Setter for the 'TradeIntentsVerifier' contract
*/
function setTradeIntentsVerifier(
address _tradeIntentsVerifier
) external onlyAdmin {
tradeIntentsVerifier = _tradeIntentsVerifier;
emit AddressUpdated("tradeIntentsVerifier", _tradeIntentsVerifier);
}
/**
* Setter for the 'LiquidityIntentsVerifier' contract
*/
function setLiquidityIntentsVerifier(
address _liquidityIntentsVerifier
) external onlyAdmin {
liquidityIntentsVerifier = _liquidityIntentsVerifier;
emit AddressUpdated("liquidityIntentsVerifier", _liquidityIntentsVerifier);
}
/**
* Setter for the 'ChipsIntentsVerifier' contract
*/
function setChipsIntentsVerifier(
address _chipsIntentsVerifier
) external onlyAdmin {
chipsIntentsVerifier = _chipsIntentsVerifier;
emit AddressUpdated("chipsIntentsVerifier", _chipsIntentsVerifier);
}
/**
* Sets lex proxies factory role for a specific asset
*/
function setLexProxiesFactory(address _lexProxiesFactory) external onlyAdmin {
lexProxiesFactory = _lexProxiesFactory;
emit AddressUpdated("lexProxiesFactory", _lexProxiesFactory);
}
/**
* Sets chips factory role for a specific asset
*/
function setChipsFactory(address _chipsFactory) external onlyAdmin {
chipsFactory = _chipsFactory;
emit AddressUpdated("chipsFactory", _chipsFactory);
}
/**
* Sets fee manager role for a specific asset
*/
function setFeesManager(
address asset,
address feesManager
) external onlyAdmin {
feesManagers[asset] = feesManager;
emit FeesManagerSet(asset, feesManager);
}
/**
* Allows setting/unsetting of valid spender targets for chips by specific roles
*/
function setValidChipSpenderTargetByRole(
address chip,
string calldata role,
address spender
) external onlyAdmin {
setValidChipSpenderByRoleInternal(chip, role, spender);
}
/**
* Allows setting/unsetting of valid burn handlers for chips
*/
function setValidChipBurnHandler(
address chip,
address burnHandler
) external onlyAdmin {
setValidChipBurnHandlerInternal(chip, burnHandler);
}
/**
* Publish version for a single contract
*/
function publishNewSystemVersionSingle(
uint256 versionToPublish,
bytes32 contractNameHash,
address contractImplementation
) external onlyAdmin {
publishNewSystemVersionSingleInternal(
versionToPublish,
contractNameHash,
contractImplementation
);
}
/**
* Publish version for multiple contracts
*/
function publishNewSystemVersionBatch(
uint256 versionToPublish,
bytes32[] calldata contractNameHashes,
address[] calldata contractImplementations
) external onlyAdmin {
require(
contractNameHashes.length == contractImplementations.length,
"Arrays must be 1:1"
);
for (uint256 i = 0; i < contractNameHashes.length; i++) {
bytes32 contractNameHash = contractNameHashes[i];
address contractImplementation = contractImplementations[i];
publishNewSystemVersionSingleInternal(
versionToPublish,
contractNameHash,
contractImplementation
);
}
}
/**
* Supports a new Trading floor contract
*/
function supportTradingFloor(address _tradingFloor) external onlyAdmin {
isTradingFloorSupported[_tradingFloor] = true;
supportedTradingFloors.push(_tradingFloor);
emit TradingFloorSupported(_tradingFloor);
}
/**
* Adds a new settlement asset for a trading floor
*/
function addNewSettlementAssetInTradingFloor(
address _tradingFloor,
address _lexPool
) external {
require(
_tradingFloor != address(0) && _lexPool != address(0),
"CANNOT_BE_ZERO_ADDRESS"
);
require(
isTradingFloorSupported[_tradingFloor],
"UNSUPPORTED_TRADING_FLOOR"
);
address _poolAccountant = ILexPoolV1(_lexPool).poolAccountant();
address _asset = address(ILexPoolV1(_lexPool).underlying());
require(
address(IPoolAccountantV1(_poolAccountant).lexPool()) == _lexPool,
"LEX_POOL_MISMATCH"
);
LexProxiesFactory.LexProxyContractsStruct
memory factoryDeployedLexContracts = LexProxiesFactory(lexProxiesFactory)
.getLexProxyContractsForChip(_asset);
require(
factoryDeployedLexContracts.lexPoolProxy == _lexPool,
"UNAUTHORIZED_LEX_POOL"
);
require(
factoryDeployedLexContracts.poolAccountantProxy == _poolAccountant,
"UNAUTHORIZED_POOL_ACCOUNTANT"
);
require(
ChipsFactory(chipsFactory).isChipDeployedByFactory(_asset),
"UNAUTHORIZED_CHIP"
);
// Adds the LexPool as a valid system locker
validSystemLockOwners[_lexPool] = true;
// Add the settlement asset to the TradingFloor's list
settlementAssetsForTradingFloor[_tradingFloor].push(_asset);
// Add the settlement asset in the TradingFloor itself
ITradingFloorV1(_tradingFloor).supportNewSettlementAsset(
_asset,
_lexPool,
_poolAccountant
);
// Set the TradingFloor as a valid spender for the chip
string memory tradingFloorRole = "TradingFloor";
setValidChipSpenderByRoleInternal(_asset, tradingFloorRole, _tradingFloor);
// Set the LexPool as a valid spender for the chip
string memory lexPoolRole = "LexPool";
setValidChipSpenderByRoleInternal(_asset, lexPoolRole, _lexPool);
// Set the ChipsIntentsVerifier as a valid spender for the chip
string memory chipsIntentsVerifierRole = "ChipsIntentsVerifier";
setValidChipSpenderByRoleInternal(
_asset,
chipsIntentsVerifierRole,
chipsIntentsVerifier
);
// Event
emit SettlementAssetForTradingFloorAdded(
_tradingFloor,
_asset,
_lexPool,
_poolAccountant
);
}
// ***** Internal Views *****
function getLatestImplementationForProxyByHashInternal(
bytes32 proxyNameHash
) internal view returns (address) {
uint256 latestVersionNumber = latestVersions[proxyNameHash];
return implementations[latestVersionNumber][proxyNameHash];
}
// ***** Internal Logic *****
/**
* Handles version publishing for a single versioned contract
*/
function publishNewSystemVersionSingleInternal(
uint256 versionToPublish,
bytes32 contractNameHash,
address contractImplementation
) internal {
uint256 latestSystemVersion = latestVersions[contractNameHash];
require(
versionToPublish > latestSystemVersion,
"MUST_PUBLISH_NEWER_VERSION"
);
require(contractImplementation != address(0), "IMPLEMENTATION_ZERO");
latestVersions[contractNameHash] = versionToPublish;
implementations[versionToPublish][
contractNameHash
] = contractImplementation;
emit NewVersionPublished(
versionToPublish,
contractNameHash,
contractImplementation
);
}
/**
* Utility function to handle the "valid lockers" mechanism
*/
function updateLockerAddressInternal(
address _currentLocker,
address _newLocker,
string memory name
) internal {
require(_newLocker != address(0), "CANNOT_BE_ZERO_ADDRESS");
validSystemLockOwners[_currentLocker] = false;
validSystemLockOwners[_newLocker] = true;
emit AddressUpdated(name, _newLocker);
}
function setValidChipSpenderByRoleInternal(
address chip,
string memory role,
address spender
) internal {
bytes32 roleHash = keccak256(abi.encodePacked(role));
address currentSpenderByRole = validSpenderTargetForChipByRole[chip][
roleHash
];
// Sanity
require(currentSpenderByRole != spender, "ALREADY_SET");
// Storage update
validSpenderTargetForChipByRole[chip][roleHash] = spender;
// Event
emit ValidChipSpenderTargetByRoleSet(chip, role, spender);
}
function setValidChipBurnHandlerInternal(
address chip,
address burnHandler
) internal {
address currentBurnHandler = validBurnHandlerForChip[chip];
// Sanity
require(currentBurnHandler != burnHandler, "ALREADY_SET");
// Storage update
validBurnHandlerForChip[chip] = burnHandler;
// Event
emit ValidChipBurnHandlerSet(chip, burnHandler);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { ILayerZeroEndpointV2 } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
/**
* @title IOAppCore
*/
interface IOAppCore {
// Custom error messages
error OnlyPeer(uint32 eid, bytes32 sender);
error NoPeer(uint32 eid);
error InvalidEndpointCall();
error InvalidDelegate();
// Event emitted when a peer (OApp) is set for a corresponding endpoint
event PeerSet(uint32 eid, bytes32 peer);
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*/
function oAppVersion() external view returns (uint64 senderVersion, uint64 receiverVersion);
/**
* @notice Retrieves the LayerZero endpoint associated with the OApp.
* @return iEndpoint The LayerZero endpoint as an interface.
*/
function endpoint() external view returns (ILayerZeroEndpointV2 iEndpoint);
/**
* @notice Retrieves the peer (OApp) associated with a corresponding endpoint.
* @param _eid The endpoint ID.
* @return peer The peer address (OApp instance) associated with the corresponding endpoint.
*/
function peers(uint32 _eid) external view returns (bytes32 peer);
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*/
function setPeer(uint32 _eid, bytes32 _peer) external;
/**
* @notice Sets the delegate address for the OApp Core.
* @param _delegate The address of the delegate to be set.
*/
function setDelegate(address _delegate) external;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @title IOAppMsgInspector
* @dev Interface for the OApp Message Inspector, allowing examination of message and options contents.
*/
interface IOAppMsgInspector {
// Custom error message for inspection failure
error InspectionFailed(bytes message, bytes options);
/**
* @notice Allows the inspector to examine LayerZero message contents and optionally throw a revert if invalid.
* @param _message The message payload to be inspected.
* @param _options Additional options or parameters for inspection.
* @return valid A boolean indicating whether the inspection passed (true) or failed (false).
*
* @dev Optionally done as a revert, OR use the boolean provided to handle the failure.
*/
function inspect(bytes calldata _message, bytes calldata _options) external view returns (bool valid);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
/**
* @dev Struct representing enforced option parameters.
*/
struct EnforcedOptionParam {
uint32 eid; // Endpoint ID
uint16 msgType; // Message Type
bytes options; // Additional options
}
/**
* @title IOAppOptionsType3
* @dev Interface for the OApp with Type 3 Options, allowing the setting and combining of enforced options.
*/
interface IOAppOptionsType3 {
// Custom error message for invalid options
error InvalidOptions(bytes options);
// Event emitted when enforced options are set
event EnforcedOptionSet(EnforcedOptionParam[] _enforcedOptions);
/**
* @notice Sets enforced options for specific endpoint and message type combinations.
* @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
*/
function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) external;
/**
* @notice Combines options for a given endpoint and message type.
* @param _eid The endpoint ID.
* @param _msgType The OApp message type.
* @param _extraOptions Additional options passed by the caller.
* @return options The combination of caller specified options AND enforced options.
*/
function combineOptions(
uint32 _eid,
uint16 _msgType,
bytes calldata _extraOptions
) external view returns (bytes memory options);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { ILayerZeroReceiver, Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol";
interface IOAppReceiver is ILayerZeroReceiver {
/**
* @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.
* @param _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @param _message The lzReceive payload.
* @param _sender The sender address.
* @return isSender Is a valid sender.
*
* @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer.
* @dev The default sender IS the OAppReceiver implementer.
*/
function isComposeMsgSender(
Origin calldata _origin,
bytes calldata _message,
address _sender
) external view returns (bool isSender);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IOAppOptionsType3, EnforcedOptionParam } from "../interfaces/IOAppOptionsType3.sol";
/**
* @title OAppOptionsType3
* @dev Abstract contract implementing the IOAppOptionsType3 interface with type 3 options.
*/
abstract contract OAppOptionsType3 is IOAppOptionsType3, Ownable {
uint16 internal constant OPTION_TYPE_3 = 3;
// @dev The "msgType" should be defined in the child contract.
mapping(uint32 eid => mapping(uint16 msgType => bytes enforcedOption)) public enforcedOptions;
/**
* @dev Sets the enforced options for specific endpoint and message type combinations.
* @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.
* @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.
* eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay
* if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().
*/
function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) public virtual onlyOwner {
_setEnforcedOptions(_enforcedOptions);
}
/**
* @dev Sets the enforced options for specific endpoint and message type combinations.
* @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options.
*
* @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc.
* @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType.
* eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay
* if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose().
*/
function _setEnforcedOptions(EnforcedOptionParam[] memory _enforcedOptions) internal virtual {
for (uint256 i = 0; i < _enforcedOptions.length; i++) {
// @dev Enforced options are only available for optionType 3, as type 1 and 2 dont support combining.
_assertOptionsType3(_enforcedOptions[i].options);
enforcedOptions[_enforcedOptions[i].eid][_enforcedOptions[i].msgType] = _enforcedOptions[i].options;
}
emit EnforcedOptionSet(_enforcedOptions);
}
/**
* @notice Combines options for a given endpoint and message type.
* @param _eid The endpoint ID.
* @param _msgType The OAPP message type.
* @param _extraOptions Additional options passed by the caller.
* @return options The combination of caller specified options AND enforced options.
*
* @dev If there is an enforced lzReceive option:
* - {gasLimit: 200k, msg.value: 1 ether} AND a caller supplies a lzReceive option: {gasLimit: 100k, msg.value: 0.5 ether}
* - The resulting options will be {gasLimit: 300k, msg.value: 1.5 ether} when the message is executed on the remote lzReceive() function.
* @dev This presence of duplicated options is handled off-chain in the verifier/executor.
*/
function combineOptions(
uint32 _eid,
uint16 _msgType,
bytes calldata _extraOptions
) public view virtual returns (bytes memory) {
bytes memory enforced = enforcedOptions[_eid][_msgType];
// No enforced options, pass whatever the caller supplied, even if it's empty or legacy type 1/2 options.
if (enforced.length == 0) return _extraOptions;
// No caller options, return enforced
if (_extraOptions.length == 0) return enforced;
// @dev If caller provided _extraOptions, must be type 3 as its the ONLY type that can be combined.
if (_extraOptions.length >= 2) {
_assertOptionsType3(_extraOptions);
// @dev Remove the first 2 bytes containing the type from the _extraOptions and combine with enforced.
return bytes.concat(enforced, _extraOptions[2:]);
}
// No valid set of options was found.
revert InvalidOptions(_extraOptions);
}
/**
* @dev Internal function to assert that options are of type 3.
* @param _options The options to be checked.
*/
function _assertOptionsType3(bytes memory _options) internal pure virtual {
uint16 optionsType;
assembly {
optionsType := mload(add(_options, 2))
}
if (optionsType != OPTION_TYPE_3) revert InvalidOptions(_options);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
// @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers
// solhint-disable-next-line no-unused-import
import { OAppSender, MessagingFee, MessagingReceipt } from "./OAppSender.sol";
// @dev Import the 'Origin' so it's exposed to OApp implementers
// solhint-disable-next-line no-unused-import
import { OAppReceiver, Origin } from "./OAppReceiver.sol";
import { OAppCore } from "./OAppCore.sol";
/**
* @title OApp
* @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality.
*/
abstract contract OApp is OAppSender, OAppReceiver {
/**
* @dev Constructor to initialize the OApp with the provided endpoint and owner.
* @param _endpoint The address of the LOCAL LayerZero endpoint.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*/
constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {}
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol implementation.
* @return receiverVersion The version of the OAppReceiver.sol implementation.
*/
function oAppVersion()
public
pure
virtual
override(OAppSender, OAppReceiver)
returns (uint64 senderVersion, uint64 receiverVersion)
{
return (SENDER_VERSION, RECEIVER_VERSION);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IOAppCore, ILayerZeroEndpointV2 } from "./interfaces/IOAppCore.sol";
/**
* @title OAppCore
* @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations.
*/
abstract contract OAppCore is IOAppCore, Ownable {
// The LayerZero endpoint associated with the given OApp
ILayerZeroEndpointV2 public immutable endpoint;
// Mapping to store peers associated with corresponding endpoints
mapping(uint32 eid => bytes32 peer) public peers;
/**
* @dev Constructor to initialize the OAppCore with the provided endpoint and delegate.
* @param _endpoint The address of the LOCAL Layer Zero endpoint.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*
* @dev The delegate typically should be set as the owner of the contract.
*/
constructor(address _endpoint, address _delegate) {
endpoint = ILayerZeroEndpointV2(_endpoint);
if (_delegate == address(0)) revert InvalidDelegate();
endpoint.setDelegate(_delegate);
}
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
* @dev Set this to bytes32(0) to remove the peer address.
* @dev Peer is a bytes32 to accommodate non-evm chains.
*/
function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner {
_setPeer(_eid, _peer);
}
/**
* @notice Sets the peer address (OApp instance) for a corresponding endpoint.
* @param _eid The endpoint ID.
* @param _peer The address of the peer to be associated with the corresponding endpoint.
*
* @dev Indicates that the peer is trusted to send LayerZero messages to this OApp.
* @dev Set this to bytes32(0) to remove the peer address.
* @dev Peer is a bytes32 to accommodate non-evm chains.
*/
function _setPeer(uint32 _eid, bytes32 _peer) internal virtual {
peers[_eid] = _peer;
emit PeerSet(_eid, _peer);
}
/**
* @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set.
* ie. the peer is set to bytes32(0).
* @param _eid The endpoint ID.
* @return peer The address of the peer associated with the specified endpoint.
*/
function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) {
bytes32 peer = peers[_eid];
if (peer == bytes32(0)) revert NoPeer(_eid);
return peer;
}
/**
* @notice Sets the delegate address for the OApp.
* @param _delegate The address of the delegate to be set.
*
* @dev Only the owner/admin of the OApp can call this function.
* @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract.
*/
function setDelegate(address _delegate) public onlyOwner {
endpoint.setDelegate(_delegate);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { IOAppReceiver, Origin } from "./interfaces/IOAppReceiver.sol";
import { OAppCore } from "./OAppCore.sol";
/**
* @title OAppReceiver
* @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers.
*/
abstract contract OAppReceiver is IOAppReceiver, OAppCore {
// Custom error message for when the caller is not the registered endpoint/
error OnlyEndpoint(address addr);
// @dev The version of the OAppReceiver implementation.
// @dev Version is bumped when changes are made to this contract.
uint64 internal constant RECEIVER_VERSION = 2;
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*
* @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented.
* ie. this is a RECEIVE only OApp.
* @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions.
*/
function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
return (0, RECEIVER_VERSION);
}
/**
* @notice Indicates whether an address is an approved composeMsg sender to the Endpoint.
* @dev _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @dev _message The lzReceive payload.
* @param _sender The sender address.
* @return isSender Is a valid sender.
*
* @dev Applications can optionally choose to implement separate composeMsg senders that are NOT the bridging layer.
* @dev The default sender IS the OAppReceiver implementer.
*/
function isComposeMsgSender(
Origin calldata /*_origin*/,
bytes calldata /*_message*/,
address _sender
) public view virtual returns (bool) {
return _sender == address(this);
}
/**
* @notice Checks if the path initialization is allowed based on the provided origin.
* @param origin The origin information containing the source endpoint and sender address.
* @return Whether the path has been initialized.
*
* @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received.
* @dev This defaults to assuming if a peer has been set, its initialized.
* Can be overridden by the OApp if there is other logic to determine this.
*/
function allowInitializePath(Origin calldata origin) public view virtual returns (bool) {
return peers[origin.srcEid] == origin.sender;
}
/**
* @notice Retrieves the next nonce for a given source endpoint and sender address.
* @dev _srcEid The source endpoint ID.
* @dev _sender The sender address.
* @return nonce The next nonce.
*
* @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement.
* @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered.
* @dev This is also enforced by the OApp.
* @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0.
*/
function nextNonce(uint32 /*_srcEid*/, bytes32 /*_sender*/) public view virtual returns (uint64 nonce) {
return 0;
}
/**
* @dev Entry point for receiving messages or packets from the endpoint.
* @param _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @param _guid The unique identifier for the received LayerZero message.
* @param _message The payload of the received message.
* @param _executor The address of the executor for the received message.
* @param _extraData Additional arbitrary data provided by the corresponding executor.
*
* @dev Entry point for receiving msg/packet from the LayerZero endpoint.
*/
function lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) public payable virtual {
// Ensures that only the endpoint can attempt to lzReceive() messages to this OApp.
if (address(endpoint) != msg.sender) revert OnlyEndpoint(msg.sender);
// Ensure that the sender matches the expected peer for the source endpoint.
if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender);
// Call the internal OApp implementation of lzReceive.
_lzReceive(_origin, _guid, _message, _executor, _extraData);
}
/**
* @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation.
*/
function _lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) internal virtual;
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { MessagingParams, MessagingFee, MessagingReceipt } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { OAppCore } from "./OAppCore.sol";
/**
* @title OAppSender
* @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint.
*/
abstract contract OAppSender is OAppCore {
using SafeERC20 for IERC20;
// Custom error messages
error NotEnoughNative(uint256 msgValue);
error LzTokenUnavailable();
// @dev The version of the OAppSender implementation.
// @dev Version is bumped when changes are made to this contract.
uint64 internal constant SENDER_VERSION = 1;
/**
* @notice Retrieves the OApp version information.
* @return senderVersion The version of the OAppSender.sol contract.
* @return receiverVersion The version of the OAppReceiver.sol contract.
*
* @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented.
* ie. this is a SEND only OApp.
* @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions
*/
function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) {
return (SENDER_VERSION, 0);
}
/**
* @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation.
* @param _dstEid The destination endpoint ID.
* @param _message The message payload.
* @param _options Additional options for the message.
* @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens.
* @return fee The calculated MessagingFee for the message.
* - nativeFee: The native fee for the message.
* - lzTokenFee: The LZ token fee for the message.
*/
function _quote(
uint32 _dstEid,
bytes memory _message,
bytes memory _options,
bool _payInLzToken
) internal view virtual returns (MessagingFee memory fee) {
return
endpoint.quote(
MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken),
address(this)
);
}
/**
* @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message.
* @param _dstEid The destination endpoint ID.
* @param _message The message payload.
* @param _options Additional options for the message.
* @param _fee The calculated LayerZero fee for the message.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess fee values sent to the endpoint.
* @return receipt The receipt for the sent message.
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function _lzSend(
uint32 _dstEid,
bytes memory _message,
bytes memory _options,
MessagingFee memory _fee,
address _refundAddress
) internal virtual returns (MessagingReceipt memory receipt) {
// @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint.
uint256 messageValue = _payNative(_fee.nativeFee);
if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee);
return
// solhint-disable-next-line check-send-result
endpoint.send{ value: messageValue }(
MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0),
_refundAddress
);
}
/**
* @dev Internal function to pay the native fee associated with the message.
* @param _nativeFee The native fee to be paid.
* @return nativeFee The amount of native currency paid.
*
* @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction,
* this will need to be overridden because msg.value would contain multiple lzFees.
* @dev Should be overridden in the event the LayerZero endpoint requires a different native currency.
* @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees.
* @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time.
*/
function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) {
if (msg.value != _nativeFee) revert NotEnoughNative(msg.value);
return _nativeFee;
}
/**
* @dev Internal function to pay the LZ token fee associated with the message.
* @param _lzTokenFee The LZ token fee to be paid.
*
* @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint.
* @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend().
*/
function _payLzToken(uint256 _lzTokenFee) internal virtual {
// @dev Cannot cache the token because it is not immutable in the endpoint.
address lzToken = endpoint.lzToken();
if (lzToken == address(0)) revert LzTokenUnavailable();
// Pay LZ token fee by sending tokens to the endpoint.
IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee);
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { MessagingReceipt, MessagingFee } from "../../oapp/OAppSender.sol";
/**
* @dev Struct representing token parameters for the OFT send() operation.
*/
struct SendParam {
uint32 dstEid; // Destination endpoint ID.
bytes32 to; // Recipient address.
uint256 amountLD; // Amount to send in local decimals.
uint256 minAmountLD; // Minimum amount to send in local decimals.
bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message.
bytes composeMsg; // The composed message for the send() operation.
bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations.
}
/**
* @dev Struct representing OFT limit information.
* @dev These amounts can change dynamically and are up the the specific oft implementation.
*/
struct OFTLimit {
uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient.
uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient.
}
/**
* @dev Struct representing OFT receipt information.
*/
struct OFTReceipt {
uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals.
// @dev In non-default implementations, the amountReceivedLD COULD differ from this value.
uint256 amountReceivedLD; // Amount of tokens to be received on the remote side.
}
/**
* @dev Struct representing OFT fee details.
* @dev Future proof mechanism to provide a standardized way to communicate fees to things like a UI.
*/
struct OFTFeeDetail {
int256 feeAmountLD; // Amount of the fee in local decimals.
string description; // Description of the fee.
}
/**
* @title IOFT
* @dev Interface for the OftChain (OFT) token.
* @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well.
* @dev This specific interface ID is '0x02e49c2c'.
*/
interface IOFT {
// Custom error messages
error InvalidLocalDecimals();
error SlippageExceeded(uint256 amountLD, uint256 minAmountLD);
// Events
event OFTSent(
bytes32 indexed guid, // GUID of the OFT message.
uint32 dstEid, // Destination Endpoint ID.
address indexed fromAddress, // Address of the sender on the src chain.
uint256 amountSentLD, // Amount of tokens sent in local decimals.
uint256 amountReceivedLD // Amount of tokens received in local decimals.
);
event OFTReceived(
bytes32 indexed guid, // GUID of the OFT message.
uint32 srcEid, // Source Endpoint ID.
address indexed toAddress, // Address of the recipient on the dst chain.
uint256 amountReceivedLD // Amount of tokens received in local decimals.
);
/**
* @notice Retrieves interfaceID and the version of the OFT.
* @return interfaceId The interface ID.
* @return version The version.
*
* @dev interfaceId: This specific interface ID is '0x02e49c2c'.
* @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.
* @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.
* ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)
*/
function oftVersion() external view returns (bytes4 interfaceId, uint64 version);
/**
* @notice Retrieves the address of the token associated with the OFT.
* @return token The address of the ERC20 token implementation.
*/
function token() external view returns (address);
/**
* @notice Indicates whether the OFT contract requires approval of the 'token()' to send.
* @return requiresApproval Needs approval of the underlying token implementation.
*
* @dev Allows things like wallet implementers to determine integration requirements,
* without understanding the underlying token implementation.
*/
function approvalRequired() external view returns (bool);
/**
* @notice Retrieves the shared decimals of the OFT.
* @return sharedDecimals The shared decimals of the OFT.
*/
function sharedDecimals() external view returns (uint8);
/**
* @notice Provides a quote for OFT-related operations.
* @param _sendParam The parameters for the send operation.
* @return limit The OFT limit information.
* @return oftFeeDetails The details of OFT fees.
* @return receipt The OFT receipt information.
*/
function quoteOFT(
SendParam calldata _sendParam
) external view returns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory);
/**
* @notice Provides a quote for the send() operation.
* @param _sendParam The parameters for the send() operation.
* @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
* @return fee The calculated LayerZero messaging fee from the send() operation.
*
* @dev MessagingFee: LayerZero msg fee
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
*/
function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory);
/**
* @notice Executes the send() operation.
* @param _sendParam The parameters for the send operation.
* @param _fee The fee information supplied by the caller.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess funds from fees etc. on the src.
* @return receipt The LayerZero messaging receipt from the send() operation.
* @return oftReceipt The OFT receipt information.
*
* @dev MessagingReceipt: LayerZero msg receipt
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function send(
SendParam calldata _sendParam,
MessagingFee calldata _fee,
address _refundAddress
) external payable returns (MessagingReceipt memory, OFTReceipt memory);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library OFTComposeMsgCodec {
// Offset constants for decoding composed messages
uint8 private constant NONCE_OFFSET = 8;
uint8 private constant SRC_EID_OFFSET = 12;
uint8 private constant AMOUNT_LD_OFFSET = 44;
uint8 private constant COMPOSE_FROM_OFFSET = 76;
/**
* @dev Encodes a OFT composed message.
* @param _nonce The nonce value.
* @param _srcEid The source endpoint ID.
* @param _amountLD The amount in local decimals.
* @param _composeMsg The composed message.
* @return _msg The encoded Composed message.
*/
function encode(
uint64 _nonce,
uint32 _srcEid,
uint256 _amountLD,
bytes memory _composeMsg // 0x[composeFrom][composeMsg]
) internal pure returns (bytes memory _msg) {
_msg = abi.encodePacked(_nonce, _srcEid, _amountLD, _composeMsg);
}
/**
* @dev Retrieves the nonce from the composed message.
* @param _msg The message.
* @return The nonce value.
*/
function nonce(bytes calldata _msg) internal pure returns (uint64) {
return uint64(bytes8(_msg[:NONCE_OFFSET]));
}
/**
* @dev Retrieves the source endpoint ID from the composed message.
* @param _msg The message.
* @return The source endpoint ID.
*/
function srcEid(bytes calldata _msg) internal pure returns (uint32) {
return uint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET]));
}
/**
* @dev Retrieves the amount in local decimals from the composed message.
* @param _msg The message.
* @return The amount in local decimals.
*/
function amountLD(bytes calldata _msg) internal pure returns (uint256) {
return uint256(bytes32(_msg[SRC_EID_OFFSET:AMOUNT_LD_OFFSET]));
}
/**
* @dev Retrieves the composeFrom value from the composed message.
* @param _msg The message.
* @return The composeFrom value.
*/
function composeFrom(bytes calldata _msg) internal pure returns (bytes32) {
return bytes32(_msg[AMOUNT_LD_OFFSET:COMPOSE_FROM_OFFSET]);
}
/**
* @dev Retrieves the composed message.
* @param _msg The message.
* @return The composed message.
*/
function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {
return _msg[COMPOSE_FROM_OFFSET:];
}
/**
* @dev Converts an address to bytes32.
* @param _addr The address to convert.
* @return The bytes32 representation of the address.
*/
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
/**
* @dev Converts bytes32 to an address.
* @param _b The bytes32 value to convert.
* @return The address representation of bytes32.
*/
function bytes32ToAddress(bytes32 _b) internal pure returns (address) {
return address(uint160(uint256(_b)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library OFTMsgCodec {
// Offset constants for encoding and decoding OFT messages
uint8 private constant SEND_TO_OFFSET = 32;
uint8 private constant SEND_AMOUNT_SD_OFFSET = 40;
/**
* @dev Encodes an OFT LayerZero message.
* @param _sendTo The recipient address.
* @param _amountShared The amount in shared decimals.
* @param _composeMsg The composed message.
* @return _msg The encoded message.
* @return hasCompose A boolean indicating whether the message has a composed payload.
*/
function encode(
bytes32 _sendTo,
uint64 _amountShared,
bytes memory _composeMsg
) internal view returns (bytes memory _msg, bool hasCompose) {
hasCompose = _composeMsg.length > 0;
// @dev Remote chains will want to know the composed function caller ie. msg.sender on the src.
_msg = hasCompose
? abi.encodePacked(_sendTo, _amountShared, addressToBytes32(msg.sender), _composeMsg)
: abi.encodePacked(_sendTo, _amountShared);
}
/**
* @dev Checks if the OFT message is composed.
* @param _msg The OFT message.
* @return A boolean indicating whether the message is composed.
*/
function isComposed(bytes calldata _msg) internal pure returns (bool) {
return _msg.length > SEND_AMOUNT_SD_OFFSET;
}
/**
* @dev Retrieves the recipient address from the OFT message.
* @param _msg The OFT message.
* @return The recipient address.
*/
function sendTo(bytes calldata _msg) internal pure returns (bytes32) {
return bytes32(_msg[:SEND_TO_OFFSET]);
}
/**
* @dev Retrieves the amount in shared decimals from the OFT message.
* @param _msg The OFT message.
* @return The amount in shared decimals.
*/
function amountSD(bytes calldata _msg) internal pure returns (uint64) {
return uint64(bytes8(_msg[SEND_TO_OFFSET:SEND_AMOUNT_SD_OFFSET]));
}
/**
* @dev Retrieves the composed message from the OFT message.
* @param _msg The OFT message.
* @return The composed message.
*/
function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) {
return _msg[SEND_AMOUNT_SD_OFFSET:];
}
/**
* @dev Converts an address to bytes32.
* @param _addr The address to convert.
* @return The bytes32 representation of the address.
*/
function addressToBytes32(address _addr) internal pure returns (bytes32) {
return bytes32(uint256(uint160(_addr)));
}
/**
* @dev Converts bytes32 to an address.
* @param _b The bytes32 value to convert.
* @return The address representation of bytes32.
*/
function bytes32ToAddress(bytes32 _b) internal pure returns (address) {
return address(uint160(uint256(_b)));
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IOFT, OFTCore } from "./OFTCore.sol";
/**
* @title OFT Contract
* @dev OFT is an ERC-20 token that extends the functionality of the OFTCore contract.
*/
abstract contract OFT is OFTCore, ERC20 {
/**
* @dev Constructor for the OFT contract.
* @param _name The name of the OFT.
* @param _symbol The symbol of the OFT.
* @param _lzEndpoint The LayerZero endpoint address.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*/
constructor(
string memory _name,
string memory _symbol,
address _lzEndpoint,
address _delegate
) ERC20(_name, _symbol) OFTCore(decimals(), _lzEndpoint, _delegate) {}
/**
* @dev Retrieves the address of the underlying ERC20 implementation.
* @return The address of the OFT token.
*
* @dev In the case of OFT, address(this) and erc20 are the same contract.
*/
function token() public view returns (address) {
return address(this);
}
/**
* @notice Indicates whether the OFT contract requires approval of the 'token()' to send.
* @return requiresApproval Needs approval of the underlying token implementation.
*
* @dev In the case of OFT where the contract IS the token, approval is NOT required.
*/
function approvalRequired() external pure virtual returns (bool) {
return false;
}
/**
* @dev Burns tokens from the sender's specified balance.
* @param _from The address to debit the tokens from.
* @param _amountLD The amount of tokens to send in local decimals.
* @param _minAmountLD The minimum amount to send in local decimals.
* @param _dstEid The destination chain ID.
* @return amountSentLD The amount sent in local decimals.
* @return amountReceivedLD The amount received in local decimals on the remote.
*/
function _debit(
address _from,
uint256 _amountLD,
uint256 _minAmountLD,
uint32 _dstEid
) internal virtual override returns (uint256 amountSentLD, uint256 amountReceivedLD) {
(amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);
// @dev In NON-default OFT, amountSentLD could be 100, with a 10% fee, the amountReceivedLD amount is 90,
// therefore amountSentLD CAN differ from amountReceivedLD.
// @dev Default OFT burns on src.
_burn(_from, amountSentLD);
}
/**
* @dev Credits tokens to the specified address.
* @param _to The address to credit the tokens to.
* @param _amountLD The amount of tokens to credit in local decimals.
* @dev _srcEid The source chain ID.
* @return amountReceivedLD The amount of tokens ACTUALLY received in local decimals.
*/
function _credit(
address _to,
uint256 _amountLD,
uint32 /*_srcEid*/
) internal virtual override returns (uint256 amountReceivedLD) {
// @dev Default OFT mints on dst.
_mint(_to, _amountLD);
// @dev In the case of NON-default OFT, the _amountLD MIGHT not be == amountReceivedLD.
return _amountLD;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { OApp, Origin } from "../oapp/OApp.sol";
import { OAppOptionsType3 } from "../oapp/libs/OAppOptionsType3.sol";
import { IOAppMsgInspector } from "../oapp/interfaces/IOAppMsgInspector.sol";
import { OAppPreCrimeSimulator } from "../precrime/OAppPreCrimeSimulator.sol";
import { IOFT, SendParam, OFTLimit, OFTReceipt, OFTFeeDetail, MessagingReceipt, MessagingFee } from "./interfaces/IOFT.sol";
import { OFTMsgCodec } from "./libs/OFTMsgCodec.sol";
import { OFTComposeMsgCodec } from "./libs/OFTComposeMsgCodec.sol";
/**
* @title OFTCore
* @dev Abstract contract for the OftChain (OFT) token.
*/
abstract contract OFTCore is IOFT, OApp, OAppPreCrimeSimulator, OAppOptionsType3 {
using OFTMsgCodec for bytes;
using OFTMsgCodec for bytes32;
// @notice Provides a conversion rate when swapping between denominations of SD and LD
// - shareDecimals == SD == shared Decimals
// - localDecimals == LD == local decimals
// @dev Considers that tokens have different decimal amounts on various chains.
// @dev eg.
// For a token
// - locally with 4 decimals --> 1.2345 => uint(12345)
// - remotely with 2 decimals --> 1.23 => uint(123)
// - The conversion rate would be 10 ** (4 - 2) = 100
// @dev If you want to send 1.2345 -> (uint 12345), you CANNOT represent that value on the remote,
// you can only display 1.23 -> uint(123).
// @dev To preserve the dust that would otherwise be lost on that conversion,
// we need to unify a denomination that can be represented on ALL chains inside of the OFT mesh
uint256 public immutable decimalConversionRate;
// @notice Msg types that are used to identify the various OFT operations.
// @dev This can be extended in child contracts for non-default oft operations
// @dev These values are used in things like combineOptions() in OAppOptionsType3.sol.
uint16 public constant SEND = 1;
uint16 public constant SEND_AND_CALL = 2;
// Address of an optional contract to inspect both 'message' and 'options'
address public msgInspector;
event MsgInspectorSet(address inspector);
/**
* @dev Constructor.
* @param _localDecimals The decimals of the token on the local chain (this chain).
* @param _endpoint The address of the LayerZero endpoint.
* @param _delegate The delegate capable of making OApp configurations inside of the endpoint.
*/
constructor(uint8 _localDecimals, address _endpoint, address _delegate) OApp(_endpoint, _delegate) {
if (_localDecimals < sharedDecimals()) revert InvalidLocalDecimals();
decimalConversionRate = 10 ** (_localDecimals - sharedDecimals());
}
/**
* @notice Retrieves interfaceID and the version of the OFT.
* @return interfaceId The interface ID.
* @return version The version.
*
* @dev interfaceId: This specific interface ID is '0x02e49c2c'.
* @dev version: Indicates a cross-chain compatible msg encoding with other OFTs.
* @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented.
* ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1)
*/
function oftVersion() external pure virtual returns (bytes4 interfaceId, uint64 version) {
return (type(IOFT).interfaceId, 1);
}
/**
* @dev Retrieves the shared decimals of the OFT.
* @return The shared decimals of the OFT.
*
* @dev Sets an implicit cap on the amount of tokens, over uint64.max() will need some sort of outbound cap / totalSupply cap
* Lowest common decimal denominator between chains.
* Defaults to 6 decimal places to provide up to 18,446,744,073,709.551615 units (max uint64).
* For tokens exceeding this totalSupply(), they will need to override the sharedDecimals function with something smaller.
* ie. 4 sharedDecimals would be 1,844,674,407,370,955.1615
*/
function sharedDecimals() public view virtual returns (uint8) {
return 6;
}
/**
* @dev Sets the message inspector address for the OFT.
* @param _msgInspector The address of the message inspector.
*
* @dev This is an optional contract that can be used to inspect both 'message' and 'options'.
* @dev Set it to address(0) to disable it, or set it to a contract address to enable it.
*/
function setMsgInspector(address _msgInspector) public virtual onlyOwner {
msgInspector = _msgInspector;
emit MsgInspectorSet(_msgInspector);
}
/**
* @notice Provides a quote for OFT-related operations.
* @param _sendParam The parameters for the send operation.
* @return oftLimit The OFT limit information.
* @return oftFeeDetails The details of OFT fees.
* @return oftReceipt The OFT receipt information.
*/
function quoteOFT(
SendParam calldata _sendParam
)
external
view
virtual
returns (OFTLimit memory oftLimit, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory oftReceipt)
{
uint256 minAmountLD = 0; // Unused in the default implementation.
uint256 maxAmountLD = type(uint64).max; // Unused in the default implementation.
oftLimit = OFTLimit(minAmountLD, maxAmountLD);
// Unused in the default implementation; reserved for future complex fee details.
oftFeeDetails = new OFTFeeDetail[](0);
// @dev This is the same as the send() operation, but without the actual send.
// - amountSentLD is the amount in local decimals that would be sent from the sender.
// - amountReceivedLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance.
// @dev The amountSentLD MIGHT not equal the amount the user actually receives. HOWEVER, the default does.
(uint256 amountSentLD, uint256 amountReceivedLD) = _debitView(
_sendParam.amountLD,
_sendParam.minAmountLD,
_sendParam.dstEid
);
oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);
}
/**
* @notice Provides a quote for the send() operation.
* @param _sendParam The parameters for the send() operation.
* @param _payInLzToken Flag indicating whether the caller is paying in the LZ token.
* @return msgFee The calculated LayerZero messaging fee from the send() operation.
*
* @dev MessagingFee: LayerZero msg fee
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
*/
function quoteSend(
SendParam calldata _sendParam,
bool _payInLzToken
) external view virtual returns (MessagingFee memory msgFee) {
// @dev mock the amount to receive, this is the same operation used in the send().
// The quote is as similar as possible to the actual send() operation.
(, uint256 amountReceivedLD) = _debitView(_sendParam.amountLD, _sendParam.minAmountLD, _sendParam.dstEid);
// @dev Builds the options and OFT message to quote in the endpoint.
(bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);
// @dev Calculates the LayerZero fee for the send() operation.
return _quote(_sendParam.dstEid, message, options, _payInLzToken);
}
/**
* @dev Executes the send operation.
* @param _sendParam The parameters for the send operation.
* @param _fee The calculated fee for the send() operation.
* - nativeFee: The native fee.
* - lzTokenFee: The lzToken fee.
* @param _refundAddress The address to receive any excess funds.
* @return msgReceipt The receipt for the send operation.
* @return oftReceipt The OFT receipt information.
*
* @dev MessagingReceipt: LayerZero msg receipt
* - guid: The unique identifier for the sent message.
* - nonce: The nonce of the sent message.
* - fee: The LayerZero fee incurred for the message.
*/
function send(
SendParam calldata _sendParam,
MessagingFee calldata _fee,
address _refundAddress
) external payable virtual returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) {
// @dev Applies the token transfers regarding this send() operation.
// - amountSentLD is the amount in local decimals that was ACTUALLY sent/debited from the sender.
// - amountReceivedLD is the amount in local decimals that will be received/credited to the recipient on the remote OFT instance.
(uint256 amountSentLD, uint256 amountReceivedLD) = _debit(
msg.sender,
_sendParam.amountLD,
_sendParam.minAmountLD,
_sendParam.dstEid
);
// @dev Builds the options and OFT message to quote in the endpoint.
(bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD);
// @dev Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt.
msgReceipt = _lzSend(_sendParam.dstEid, message, options, _fee, _refundAddress);
// @dev Formulate the OFT receipt.
oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD);
emit OFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, amountSentLD, amountReceivedLD);
}
/**
* @dev Internal function to build the message and options.
* @param _sendParam The parameters for the send() operation.
* @param _amountLD The amount in local decimals.
* @return message The encoded message.
* @return options The encoded options.
*/
function _buildMsgAndOptions(
SendParam calldata _sendParam,
uint256 _amountLD
) internal view virtual returns (bytes memory message, bytes memory options) {
bool hasCompose;
// @dev This generated message has the msg.sender encoded into the payload so the remote knows who the caller is.
(message, hasCompose) = OFTMsgCodec.encode(
_sendParam.to,
_toSD(_amountLD),
// @dev Must be include a non empty bytes if you want to compose, EVEN if you dont need it on the remote.
// EVEN if you dont require an arbitrary payload to be sent... eg. '0x01'
_sendParam.composeMsg
);
// @dev Change the msg type depending if its composed or not.
uint16 msgType = hasCompose ? SEND_AND_CALL : SEND;
// @dev Combine the callers _extraOptions with the enforced options via the OAppOptionsType3.
options = combineOptions(_sendParam.dstEid, msgType, _sendParam.extraOptions);
// @dev Optionally inspect the message and options depending if the OApp owner has set a msg inspector.
// @dev If it fails inspection, needs to revert in the implementation. ie. does not rely on return boolean
if (msgInspector != address(0)) IOAppMsgInspector(msgInspector).inspect(message, options);
}
/**
* @dev Internal function to handle the receive on the LayerZero endpoint.
* @param _origin The origin information.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address from the src chain.
* - nonce: The nonce of the LayerZero message.
* @param _guid The unique identifier for the received LayerZero message.
* @param _message The encoded message.
* @dev _executor The address of the executor.
* @dev _extraData Additional data.
*/
function _lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address /*_executor*/, // @dev unused in the default implementation.
bytes calldata /*_extraData*/ // @dev unused in the default implementation.
) internal virtual override {
// @dev The src sending chain doesnt know the address length on this chain (potentially non-evm)
// Thus everything is bytes32() encoded in flight.
address toAddress = _message.sendTo().bytes32ToAddress();
// @dev Credit the amountLD to the recipient and return the ACTUAL amount the recipient received in local decimals
uint256 amountReceivedLD = _credit(toAddress, _toLD(_message.amountSD()), _origin.srcEid);
if (_message.isComposed()) {
// @dev Proprietary composeMsg format for the OFT.
bytes memory composeMsg = OFTComposeMsgCodec.encode(
_origin.nonce,
_origin.srcEid,
amountReceivedLD,
_message.composeMsg()
);
// @dev Stores the lzCompose payload that will be executed in a separate tx.
// Standardizes functionality for executing arbitrary contract invocation on some non-evm chains.
// @dev The off-chain executor will listen and process the msg based on the src-chain-callers compose options passed.
// @dev The index is used when a OApp needs to compose multiple msgs on lzReceive.
// For default OFT implementation there is only 1 compose msg per lzReceive, thus its always 0.
endpoint.sendCompose(toAddress, _guid, 0 /* the index of the composed message*/, composeMsg);
}
emit OFTReceived(_guid, _origin.srcEid, toAddress, amountReceivedLD);
}
/**
* @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.
* @param _origin The origin information.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address from the src chain.
* - nonce: The nonce of the LayerZero message.
* @param _guid The unique identifier for the received LayerZero message.
* @param _message The LayerZero message.
* @param _executor The address of the off-chain executor.
* @param _extraData Arbitrary data passed by the msg executor.
*
* @dev Enables the preCrime simulator to mock sending lzReceive() messages,
* routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.
*/
function _lzReceiveSimulate(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) internal virtual override {
_lzReceive(_origin, _guid, _message, _executor, _extraData);
}
/**
* @dev Check if the peer is considered 'trusted' by the OApp.
* @param _eid The endpoint ID to check.
* @param _peer The peer to check.
* @return Whether the peer passed is considered 'trusted' by the OApp.
*
* @dev Enables OAppPreCrimeSimulator to check whether a potential Inbound Packet is from a trusted source.
*/
function isPeer(uint32 _eid, bytes32 _peer) public view virtual override returns (bool) {
return peers[_eid] == _peer;
}
/**
* @dev Internal function to remove dust from the given local decimal amount.
* @param _amountLD The amount in local decimals.
* @return amountLD The amount after removing dust.
*
* @dev Prevents the loss of dust when moving amounts between chains with different decimals.
* @dev eg. uint(123) with a conversion rate of 100 becomes uint(100).
*/
function _removeDust(uint256 _amountLD) internal view virtual returns (uint256 amountLD) {
return (_amountLD / decimalConversionRate) * decimalConversionRate;
}
/**
* @dev Internal function to convert an amount from shared decimals into local decimals.
* @param _amountSD The amount in shared decimals.
* @return amountLD The amount in local decimals.
*/
function _toLD(uint64 _amountSD) internal view virtual returns (uint256 amountLD) {
return _amountSD * decimalConversionRate;
}
/**
* @dev Internal function to convert an amount from local decimals into shared decimals.
* @param _amountLD The amount in local decimals.
* @return amountSD The amount in shared decimals.
*/
function _toSD(uint256 _amountLD) internal view virtual returns (uint64 amountSD) {
return uint64(_amountLD / decimalConversionRate);
}
/**
* @dev Internal function to mock the amount mutation from a OFT debit() operation.
* @param _amountLD The amount to send in local decimals.
* @param _minAmountLD The minimum amount to send in local decimals.
* @dev _dstEid The destination endpoint ID.
* @return amountSentLD The amount sent, in local decimals.
* @return amountReceivedLD The amount to be received on the remote chain, in local decimals.
*
* @dev This is where things like fees would be calculated and deducted from the amount to be received on the remote.
*/
function _debitView(
uint256 _amountLD,
uint256 _minAmountLD,
uint32 /*_dstEid*/
) internal view virtual returns (uint256 amountSentLD, uint256 amountReceivedLD) {
// @dev Remove the dust so nothing is lost on the conversion between chains with different decimals for the token.
amountSentLD = _removeDust(_amountLD);
// @dev The amount to send is the same as amount received in the default implementation.
amountReceivedLD = amountSentLD;
// @dev Check for slippage.
if (amountReceivedLD < _minAmountLD) {
revert SlippageExceeded(amountReceivedLD, _minAmountLD);
}
}
/**
* @dev Internal function to perform a debit operation.
* @param _from The address to debit.
* @param _amountLD The amount to send in local decimals.
* @param _minAmountLD The minimum amount to send in local decimals.
* @param _dstEid The destination endpoint ID.
* @return amountSentLD The amount sent in local decimals.
* @return amountReceivedLD The amount received in local decimals on the remote.
*
* @dev Defined here but are intended to be overriden depending on the OFT implementation.
* @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.
*/
function _debit(
address _from,
uint256 _amountLD,
uint256 _minAmountLD,
uint32 _dstEid
) internal virtual returns (uint256 amountSentLD, uint256 amountReceivedLD);
/**
* @dev Internal function to perform a credit operation.
* @param _to The address to credit.
* @param _amountLD The amount to credit in local decimals.
* @param _srcEid The source endpoint ID.
* @return amountReceivedLD The amount ACTUALLY received in local decimals.
*
* @dev Defined here but are intended to be overriden depending on the OFT implementation.
* @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD.
*/
function _credit(
address _to,
uint256 _amountLD,
uint32 _srcEid
) internal virtual returns (uint256 amountReceivedLD);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
// @dev Import the Origin so it's exposed to OAppPreCrimeSimulator implementers.
// solhint-disable-next-line no-unused-import
import { InboundPacket, Origin } from "../libs/Packet.sol";
/**
* @title IOAppPreCrimeSimulator Interface
* @dev Interface for the preCrime simulation functionality in an OApp.
*/
interface IOAppPreCrimeSimulator {
// @dev simulation result used in PreCrime implementation
error SimulationResult(bytes result);
error OnlySelf();
/**
* @dev Emitted when the preCrime contract address is set.
* @param preCrimeAddress The address of the preCrime contract.
*/
event PreCrimeSet(address preCrimeAddress);
/**
* @dev Retrieves the address of the preCrime contract implementation.
* @return The address of the preCrime contract.
*/
function preCrime() external view returns (address);
/**
* @dev Retrieves the address of the OApp contract.
* @return The address of the OApp contract.
*/
function oApp() external view returns (address);
/**
* @dev Sets the preCrime contract address.
* @param _preCrime The address of the preCrime contract.
*/
function setPreCrime(address _preCrime) external;
/**
* @dev Mocks receiving a packet, then reverts with a series of data to infer the state/result.
* @param _packets An array of LayerZero InboundPacket objects representing received packets.
*/
function lzReceiveAndRevert(InboundPacket[] calldata _packets) external payable;
/**
* @dev checks if the specified peer is considered 'trusted' by the OApp.
* @param _eid The endpoint Id to check.
* @param _peer The peer to check.
* @return Whether the peer passed is considered 'trusted' by the OApp.
*/
function isPeer(uint32 _eid, bytes32 _peer) external view returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
struct PreCrimePeer {
uint32 eid;
bytes32 preCrime;
bytes32 oApp;
}
// TODO not done yet
interface IPreCrime {
error OnlyOffChain();
// for simulate()
error PacketOversize(uint256 max, uint256 actual);
error PacketUnsorted();
error SimulationFailed(bytes reason);
// for preCrime()
error SimulationResultNotFound(uint32 eid);
error InvalidSimulationResult(uint32 eid, bytes reason);
error CrimeFound(bytes crime);
function getConfig(bytes[] calldata _packets, uint256[] calldata _packetMsgValues) external returns (bytes memory);
function simulate(
bytes[] calldata _packets,
uint256[] calldata _packetMsgValues
) external payable returns (bytes memory);
function buildSimulationResult() external view returns (bytes memory);
function preCrime(
bytes[] calldata _packets,
uint256[] calldata _packetMsgValues,
bytes[] calldata _simulations
) external;
function version() external view returns (uint64 major, uint8 minor);
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol";
import { PacketV1Codec } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol";
/**
* @title InboundPacket
* @dev Structure representing an inbound packet received by the contract.
*/
struct InboundPacket {
Origin origin; // Origin information of the packet.
uint32 dstEid; // Destination endpointId of the packet.
address receiver; // Receiver address for the packet.
bytes32 guid; // Unique identifier of the packet.
uint256 value; // msg.value of the packet.
address executor; // Executor address for the packet.
bytes message; // Message payload of the packet.
bytes extraData; // Additional arbitrary data for the packet.
}
/**
* @title PacketDecoder
* @dev Library for decoding LayerZero packets.
*/
library PacketDecoder {
using PacketV1Codec for bytes;
/**
* @dev Decode an inbound packet from the given packet data.
* @param _packet The packet data to decode.
* @return packet An InboundPacket struct representing the decoded packet.
*/
function decode(bytes calldata _packet) internal pure returns (InboundPacket memory packet) {
packet.origin = Origin(_packet.srcEid(), _packet.sender(), _packet.nonce());
packet.dstEid = _packet.dstEid();
packet.receiver = _packet.receiverB20();
packet.guid = _packet.guid();
packet.message = _packet.message();
}
/**
* @dev Decode multiple inbound packets from the given packet data and associated message values.
* @param _packets An array of packet data to decode.
* @param _packetMsgValues An array of associated message values for each packet.
* @return packets An array of InboundPacket structs representing the decoded packets.
*/
function decode(
bytes[] calldata _packets,
uint256[] memory _packetMsgValues
) internal pure returns (InboundPacket[] memory packets) {
packets = new InboundPacket[](_packets.length);
for (uint256 i = 0; i < _packets.length; i++) {
bytes calldata packet = _packets[i];
packets[i] = PacketDecoder.decode(packet);
// @dev Allows the verifier to specify the msg.value that gets passed in lzReceive.
packets[i].value = _packetMsgValues[i];
}
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IPreCrime } from "./interfaces/IPreCrime.sol";
import { IOAppPreCrimeSimulator, InboundPacket, Origin } from "./interfaces/IOAppPreCrimeSimulator.sol";
/**
* @title OAppPreCrimeSimulator
* @dev Abstract contract serving as the base for preCrime simulation functionality in an OApp.
*/
abstract contract OAppPreCrimeSimulator is IOAppPreCrimeSimulator, Ownable {
// The address of the preCrime implementation.
address public preCrime;
/**
* @dev Retrieves the address of the OApp contract.
* @return The address of the OApp contract.
*
* @dev The simulator contract is the base contract for the OApp by default.
* @dev If the simulator is a separate contract, override this function.
*/
function oApp() external view virtual returns (address) {
return address(this);
}
/**
* @dev Sets the preCrime contract address.
* @param _preCrime The address of the preCrime contract.
*/
function setPreCrime(address _preCrime) public virtual onlyOwner {
preCrime = _preCrime;
emit PreCrimeSet(_preCrime);
}
/**
* @dev Interface for pre-crime simulations. Always reverts at the end with the simulation results.
* @param _packets An array of InboundPacket objects representing received packets to be delivered.
*
* @dev WARNING: MUST revert at the end with the simulation results.
* @dev Gives the preCrime implementation the ability to mock sending packets to the lzReceive function,
* WITHOUT actually executing them.
*/
function lzReceiveAndRevert(InboundPacket[] calldata _packets) public payable virtual {
for (uint256 i = 0; i < _packets.length; i++) {
InboundPacket calldata packet = _packets[i];
// Ignore packets that are not from trusted peers.
if (!isPeer(packet.origin.srcEid, packet.origin.sender)) continue;
// @dev Because a verifier is calling this function, it doesnt have access to executor params:
// - address _executor
// - bytes calldata _extraData
// preCrime will NOT work for OApps that rely on these two parameters inside of their _lzReceive().
// They are instead stubbed to default values, address(0) and bytes("")
// @dev Calling this.lzReceiveSimulate removes ability for assembly return 0 callstack exit,
// which would cause the revert to be ignored.
this.lzReceiveSimulate{ value: packet.value }(
packet.origin,
packet.guid,
packet.message,
packet.executor,
packet.extraData
);
}
// @dev Revert with the simulation results. msg.sender must implement IPreCrime.buildSimulationResult().
revert SimulationResult(IPreCrime(msg.sender).buildSimulationResult());
}
/**
* @dev Is effectively an internal function because msg.sender must be address(this).
* Allows resetting the call stack for 'internal' calls.
* @param _origin The origin information containing the source endpoint and sender address.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address on the src chain.
* - nonce: The nonce of the message.
* @param _guid The unique identifier of the packet.
* @param _message The message payload of the packet.
* @param _executor The executor address for the packet.
* @param _extraData Additional data for the packet.
*/
function lzReceiveSimulate(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) external payable virtual {
// @dev Ensure ONLY can be called 'internally'.
if (msg.sender != address(this)) revert OnlySelf();
_lzReceiveSimulate(_origin, _guid, _message, _executor, _extraData);
}
/**
* @dev Internal function to handle the OAppPreCrimeSimulator simulated receive.
* @param _origin The origin information.
* - srcEid: The source chain endpoint ID.
* - sender: The sender address from the src chain.
* - nonce: The nonce of the LayerZero message.
* @param _guid The GUID of the LayerZero message.
* @param _message The LayerZero message.
* @param _executor The address of the off-chain executor.
* @param _extraData Arbitrary data passed by the msg executor.
*
* @dev Enables the preCrime simulator to mock sending lzReceive() messages,
* routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver.
*/
function _lzReceiveSimulate(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) internal virtual;
/**
* @dev checks if the specified peer is considered 'trusted' by the OApp.
* @param _eid The endpoint Id to check.
* @param _peer The peer to check.
* @return Whether the peer passed is considered 'trusted' by the OApp.
*/
function isPeer(uint32 _eid, bytes32 _peer) public view virtual returns (bool);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { IMessageLibManager } from "./IMessageLibManager.sol";
import { IMessagingComposer } from "./IMessagingComposer.sol";
import { IMessagingChannel } from "./IMessagingChannel.sol";
import { IMessagingContext } from "./IMessagingContext.sol";
struct MessagingParams {
uint32 dstEid;
bytes32 receiver;
bytes message;
bytes options;
bool payInLzToken;
}
struct MessagingReceipt {
bytes32 guid;
uint64 nonce;
MessagingFee fee;
}
struct MessagingFee {
uint256 nativeFee;
uint256 lzTokenFee;
}
struct Origin {
uint32 srcEid;
bytes32 sender;
uint64 nonce;
}
interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext {
event PacketSent(bytes encodedPayload, bytes options, address sendLibrary);
event PacketVerified(Origin origin, address receiver, bytes32 payloadHash);
event PacketDelivered(Origin origin, address receiver);
event LzReceiveAlert(
address indexed receiver,
address indexed executor,
Origin origin,
bytes32 guid,
uint256 gas,
uint256 value,
bytes message,
bytes extraData,
bytes reason
);
event LzTokenSet(address token);
event DelegateSet(address sender, address delegate);
function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory);
function send(
MessagingParams calldata _params,
address _refundAddress
) external payable returns (MessagingReceipt memory);
function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external;
function verifiable(Origin calldata _origin, address _receiver) external view returns (bool);
function initializable(Origin calldata _origin, address _receiver) external view returns (bool);
function lzReceive(
Origin calldata _origin,
address _receiver,
bytes32 _guid,
bytes calldata _message,
bytes calldata _extraData
) external payable;
// oapp can burn messages partially by calling this function with its own business logic if messages are verified in order
function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external;
function setLzToken(address _lzToken) external;
function lzToken() external view returns (address);
function nativeToken() external view returns (address);
function setDelegate(address _delegate) external;
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { Origin } from "./ILayerZeroEndpointV2.sol";
interface ILayerZeroReceiver {
function allowInitializePath(Origin calldata _origin) external view returns (bool);
function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64);
function lzReceive(
Origin calldata _origin,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) external payable;
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import { SetConfigParam } from "./IMessageLibManager.sol";
enum MessageLibType {
Send,
Receive,
SendAndReceive
}
interface IMessageLib is IERC165 {
function setConfig(address _oapp, SetConfigParam[] calldata _config) external;
function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config);
function isSupportedEid(uint32 _eid) external view returns (bool);
// message libs of same major version are compatible
function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion);
function messageLibType() external view returns (MessageLibType);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
struct SetConfigParam {
uint32 eid;
uint32 configType;
bytes config;
}
interface IMessageLibManager {
struct Timeout {
address lib;
uint256 expiry;
}
event LibraryRegistered(address newLib);
event DefaultSendLibrarySet(uint32 eid, address newLib);
event DefaultReceiveLibrarySet(uint32 eid, address newLib);
event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry);
event SendLibrarySet(address sender, uint32 eid, address newLib);
event ReceiveLibrarySet(address receiver, uint32 eid, address newLib);
event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout);
function registerLibrary(address _lib) external;
function isRegisteredLibrary(address _lib) external view returns (bool);
function getRegisteredLibraries() external view returns (address[] memory);
function setDefaultSendLibrary(uint32 _eid, address _newLib) external;
function defaultSendLibrary(uint32 _eid) external view returns (address);
function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _gracePeriod) external;
function defaultReceiveLibrary(uint32 _eid) external view returns (address);
function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external;
function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry);
function isSupportedEid(uint32 _eid) external view returns (bool);
function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool);
/// ------------------- OApp interfaces -------------------
function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external;
function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib);
function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool);
function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external;
function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault);
function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _expiry) external;
function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry);
function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external;
function getConfig(
address _oapp,
address _lib,
uint32 _eid,
uint32 _configType
) external view returns (bytes memory config);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingChannel {
event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce);
event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash);
function eid() external view returns (uint32);
// this is an emergency function if a message cannot be verified for some reasons
// required to provide _nextNonce to avoid race condition
function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external;
function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external;
function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32);
function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64);
function inboundPayloadHash(
address _receiver,
uint32 _srcEid,
bytes32 _sender,
uint64 _nonce
) external view returns (bytes32);
function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingComposer {
event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message);
event ComposeDelivered(address from, address to, bytes32 guid, uint16 index);
event LzComposeAlert(
address indexed from,
address indexed to,
address indexed executor,
bytes32 guid,
uint16 index,
uint256 gas,
uint256 value,
bytes message,
bytes extraData,
bytes reason
);
function composeQueue(
address _from,
address _to,
bytes32 _guid,
uint16 _index
) external view returns (bytes32 messageHash);
function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external;
function lzCompose(
address _from,
address _to,
bytes32 _guid,
uint16 _index,
bytes calldata _message,
bytes calldata _extraData
) external payable;
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
interface IMessagingContext {
function isSendingMessage() external view returns (bool);
function getSendContext() external view returns (uint32 dstEid, address sender);
}// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import { MessagingFee } from "./ILayerZeroEndpointV2.sol";
import { IMessageLib } from "./IMessageLib.sol";
struct Packet {
uint64 nonce;
uint32 srcEid;
address sender;
uint32 dstEid;
bytes32 receiver;
bytes32 guid;
bytes message;
}
interface ISendLib is IMessageLib {
function send(
Packet calldata _packet,
bytes calldata _options,
bool _payInLzToken
) external returns (MessagingFee memory, bytes memory encodedPacket);
function quote(
Packet calldata _packet,
bytes calldata _options,
bool _payInLzToken
) external view returns (MessagingFee memory);
function setTreasury(address _treasury) external;
function withdrawFee(address _to, uint256 _amount) external;
function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external;
}// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
library AddressCast {
error AddressCast_InvalidSizeForAddress();
error AddressCast_InvalidAddress();
function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) {
if (_addressBytes.length > 32) revert AddressCast_InvalidAddress();
result = bytes32(_addressBytes);
unchecked {
uint256 offset = 32 - _addressBytes.length;
result = result >> (offset * 8);
}
}
function toBytes32(address _address) internal pure returns (bytes32 result) {
result = bytes32(uint256(uint160(_address)));
}
function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) {
if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress();
result = new bytes(_size);
unchecked {
uint256 offset = 256 - _size * 8;
assembly {
mstore(add(result, 32), shl(offset, _addressBytes32))
}
}
}
function toAddress(bytes32 _addressBytes32) internal pure returns (address result) {
result = address(uint160(uint256(_addressBytes32)));
}
function toAddress(bytes calldata _addressBytes) internal pure returns (address result) {
if (_addressBytes.length != 20) revert AddressCast_InvalidAddress();
result = address(bytes20(_addressBytes));
}
}// SPDX-License-Identifier: LZBL-1.2
pragma solidity ^0.8.20;
import { Packet } from "../../interfaces/ISendLib.sol";
import { AddressCast } from "../../libs/AddressCast.sol";
library PacketV1Codec {
using AddressCast for address;
using AddressCast for bytes32;
uint8 internal constant PACKET_VERSION = 1;
// header (version + nonce + path)
// version
uint256 private constant PACKET_VERSION_OFFSET = 0;
// nonce
uint256 private constant NONCE_OFFSET = 1;
// path
uint256 private constant SRC_EID_OFFSET = 9;
uint256 private constant SENDER_OFFSET = 13;
uint256 private constant DST_EID_OFFSET = 45;
uint256 private constant RECEIVER_OFFSET = 49;
// payload (guid + message)
uint256 private constant GUID_OFFSET = 81; // keccak256(nonce + path)
uint256 private constant MESSAGE_OFFSET = 113;
function encode(Packet memory _packet) internal pure returns (bytes memory encodedPacket) {
encodedPacket = abi.encodePacked(
PACKET_VERSION,
_packet.nonce,
_packet.srcEid,
_packet.sender.toBytes32(),
_packet.dstEid,
_packet.receiver,
_packet.guid,
_packet.message
);
}
function encodePacketHeader(Packet memory _packet) internal pure returns (bytes memory) {
return
abi.encodePacked(
PACKET_VERSION,
_packet.nonce,
_packet.srcEid,
_packet.sender.toBytes32(),
_packet.dstEid,
_packet.receiver
);
}
function encodePayload(Packet memory _packet) internal pure returns (bytes memory) {
return abi.encodePacked(_packet.guid, _packet.message);
}
function header(bytes calldata _packet) internal pure returns (bytes calldata) {
return _packet[0:GUID_OFFSET];
}
function version(bytes calldata _packet) internal pure returns (uint8) {
return uint8(bytes1(_packet[PACKET_VERSION_OFFSET:NONCE_OFFSET]));
}
function nonce(bytes calldata _packet) internal pure returns (uint64) {
return uint64(bytes8(_packet[NONCE_OFFSET:SRC_EID_OFFSET]));
}
function srcEid(bytes calldata _packet) internal pure returns (uint32) {
return uint32(bytes4(_packet[SRC_EID_OFFSET:SENDER_OFFSET]));
}
function sender(bytes calldata _packet) internal pure returns (bytes32) {
return bytes32(_packet[SENDER_OFFSET:DST_EID_OFFSET]);
}
function senderAddressB20(bytes calldata _packet) internal pure returns (address) {
return sender(_packet).toAddress();
}
function dstEid(bytes calldata _packet) internal pure returns (uint32) {
return uint32(bytes4(_packet[DST_EID_OFFSET:RECEIVER_OFFSET]));
}
function receiver(bytes calldata _packet) internal pure returns (bytes32) {
return bytes32(_packet[RECEIVER_OFFSET:GUID_OFFSET]);
}
function receiverB20(bytes calldata _packet) internal pure returns (address) {
return receiver(_packet).toAddress();
}
function guid(bytes calldata _packet) internal pure returns (bytes32) {
return bytes32(_packet[GUID_OFFSET:MESSAGE_OFFSET]);
}
function message(bytes calldata _packet) internal pure returns (bytes calldata) {
return bytes(_packet[MESSAGE_OFFSET:]);
}
function payload(bytes calldata _packet) internal pure returns (bytes calldata) {
return bytes(_packet[GUID_OFFSET:]);
}
function payloadHash(bytes calldata _packet) internal pure returns (bytes32) {
return keccak256(payload(_packet));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}// 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// 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);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}// 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();
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @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 ReentrancyGuard {
// 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;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_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 {
// 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 {
// 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) {
return _status == ENTERED;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "./AcceptableImplementationClaimableAdminStorage.sol";
/**
* @title SafeUpgradeableClaimableAdmin
* @dev based on Compound's Unitroller
* https://github.com/compound-finance/compound-protocol/blob/a3214f67b73310d547e00fc578e8355911c9d376/contracts/Unitroller.sol
*/
contract AcceptableImplementationClaimableAdmin is
AcceptableImplementationClaimableAdminStorage
{
/**
* @notice Emitted when pendingImplementation is changed
*/
event NewPendingImplementation(
address oldPendingImplementation,
address newPendingImplementation
);
/**
* @notice Emitted when pendingImplementation is accepted, which means delegation implementation is updated
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/*** Admin Functions ***/
function _setPendingImplementation(address newPendingImplementation) public {
require(msg.sender == admin, "not admin");
require(
approvePendingImplementationInternal(newPendingImplementation),
"INVALID_IMPLEMENTATION"
);
address oldPendingImplementation = pendingImplementation;
pendingImplementation = newPendingImplementation;
emit NewPendingImplementation(
oldPendingImplementation,
pendingImplementation
);
}
/**
* @notice Accepts new implementation. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
*/
function _acceptImplementation() public returns (uint) {
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
require(
msg.sender == pendingImplementation &&
pendingImplementation != address(0),
"Not the EXISTING pending implementation"
);
// Save current values for inclusion in log
address oldImplementation = implementation;
address oldPendingImplementation = pendingImplementation;
implementation = pendingImplementation;
pendingImplementation = address(0);
emit NewImplementation(oldImplementation, implementation);
emit NewPendingImplementation(
oldPendingImplementation,
pendingImplementation
);
return 0;
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address newPendingAdmin) public {
// Check caller = admin
require(msg.sender == admin, "Not Admin");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() public {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(
msg.sender == pendingAdmin && pendingAdmin != address(0),
"Not the EXISTING pending admin"
);
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
constructor(address _initialAdmin) {
admin = _initialAdmin;
emit NewAdmin(address(0), _initialAdmin);
}
/**
* @dev Delegates execution to an implementation contract.
* It returns to the external caller whatever the implementation returns
* or forwards reverts.
*/
fallback() external payable {
// delegate all other functions to current implementation
(bool success, ) = implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 {
revert(free_mem_ptr, returndatasize())
}
default {
return(free_mem_ptr, returndatasize())
}
}
}
receive() external payable {}
function approvePendingImplementationInternal(
address // _implementation
) internal virtual returns (bool) {
return true;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
contract ClaimableAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/*** Modifiers ***/
modifier onlyAdmin() {
require(msg.sender == admin, "ONLY_ADMIN");
_;
}
/*** Constructor ***/
constructor() {
// Set admin to caller
admin = msg.sender;
}
}
contract AcceptableImplementationClaimableAdminStorage is
ClaimableAdminStorage
{
/**
* @notice Active logic
*/
address public implementation;
/**
* @notice Pending logic
*/
address public pendingImplementation;
}
contract AcceptableRegistryImplementationClaimableAdminStorage is
AcceptableImplementationClaimableAdminStorage
{
/**
* @notice System Registry
*/
address public registry;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "./AcceptableImplementationClaimableAdminStorage.sol";
/**
* @title Claimable Admin
*/
contract ClaimableAdmin is ClaimableAdminStorage {
/**
* @notice Emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
*/
function _setPendingAdmin(address newPendingAdmin) public {
// Check caller = admin
require(msg.sender == admin, "Not Admin");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
*/
function _acceptAdmin() public {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(
msg.sender == pendingAdmin && pendingAdmin != address(0),
"Not the EXISTING pending admin"
);
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
interface IContractRegistryBase {
function isImplementationValidForProxy(
bytes32 proxyNameHash,
address _implementation
) external view returns (bool);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {ChipEnumsV1} from "../interfaces/ChipEnumsV1.sol";
import "../interfaces/IRegistryV1.sol";
/**
* @title BaseChip
* @notice Base for Chip contracts to inherit from, handles the auto approval mechanism.
*/
contract BaseChip is ChipEnumsV1 {
// ***** Events *****
event AutoApprovedSpenderSet(
string indexed role,
address indexed oldSpender,
address indexed newSpender
);
// ***** Immutable Storage *****
IRegistryV1 public immutable registry;
ChipMode public immutable chipMode;
// ***** Storage *****
// address => is auto approved
mapping(address => bool) public autoApproved;
// role hash => role address
mapping(bytes32 => address) public autoApprovedSpendersByRoles;
// ***** Views *****
function getAutoApprovedSpenderAddressByRole(
string calldata role
) public view returns (address) {
bytes32 roleHash = keccak256(abi.encodePacked(role));
return autoApprovedSpendersByRoles[roleHash];
}
// ***** Constructor *****
constructor(IRegistryV1 _registry, ChipMode _chipMode) {
require(address(_registry) != address(0), "!_registry");
registry = _registry;
chipMode = _chipMode;
}
// ***** Admin Functions *****
function setAutoApprovedSpenderForRoleInternal(
string calldata role,
address spender
) internal {
require(
spender == address(0) ||
registry.getValidSpenderTargetForChipByRole(address(this), role) ==
spender,
"NOT_REGISTRY_APPROVED"
);
address oldSpender = getAutoApprovedSpenderAddressByRole(role);
autoApproved[oldSpender] = false;
autoApproved[spender] = true;
bytes32 roleHash = keccak256(abi.encodePacked(role));
autoApprovedSpendersByRoles[roleHash] = spender;
emit AutoApprovedSpenderSet(role, oldSpender, spender);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../interfaces/IPoolMintControllerV1.sol";
import "../../interfaces/IPoolBurnControllerV1.sol";
import "../../interfaces/IBurnHandlerV1.sol";
import "../../../AdministrationContracts/ClaimableAdmin.sol";
import "../BaseChip.sol";
/**
* @title EngineChip
* @notice EngineChip is a ERC20 token that functions as a chip for ERC20 tokens that exist in the engin chain
*/
contract EngineChip is ClaimableAdmin, ERC20, ReentrancyGuard, BaseChip {
using SafeERC20 for IERC20;
using SafeERC20 for ERC20;
// ***** Events *****
event IsMintingPausedSet(bool indexed value);
event BurnHandlerSet(
address indexed previousHandler,
address indexed handler
);
event MintControllerSet(
address indexed previousController,
address indexed newController
);
event BurnControllerSet(
address indexed previousController,
address indexed newController
);
event TokensSwept(
address indexed token,
address indexed receiver,
uint256 amount
);
event ChipMinted(
address indexed minter,
address indexed to,
uint256 underlyingAmount,
uint256 amount
);
event ChipBurned(
address indexed burner,
address indexed receiver,
uint256 underlyingAmount,
uint256 amount
);
// ***** Constants *****
uint public constant SELF_UNIT_SCALE = 1e18;
// ***** Storage *****
IERC20 public immutable underlyingToken;
uint256 public immutable exchangeRate;
IBurnHandlerV1 public burnHandler;
bool public isMintingPaused;
IPoolMintControllerV1 public mintController;
IPoolBurnControllerV1 public burnController;
// ***** Constructor *****
constructor(
IRegistryV1 _registry,
string memory _name,
string memory _symbol,
IERC20 _underlyingToken,
address _initialAdmin
) ERC20(_name, _symbol) BaseChip(_registry, ChipMode.LOCAL) {
require(address(_underlyingToken) != address(0), "!_underlyingToken");
underlyingToken = _underlyingToken;
uint underlyingDecimals = ERC20(address(_underlyingToken)).decimals();
exchangeRate = 10 ** underlyingDecimals;
admin = _initialAdmin;
emit NewAdmin(address(0), _initialAdmin);
}
// ***** Admin Functions *****
/**
* @notice Set the auto approved spender for a role
* @param role The role to set the spender for
* @param spender The spender to set
*/
function setAutoApprovedSpenderForRole(
string calldata role,
address spender
) external onlyAdmin {
setAutoApprovedSpenderForRoleInternal(role, spender);
}
/**
* @notice Set the burn handler for the pool
* @param _handler The new burn handler
*/
function setBurnHandler(IBurnHandlerV1 _handler) external onlyAdmin {
require(
address(_handler) == address(0) ||
registry.validBurnHandlerForChip(address(this)) == address(_handler),
"NOT_REGISTRY_APPROVED"
);
address previousHandler = address(burnHandler);
require(previousHandler != address(_handler), "ALREADY_SET");
burnHandler = _handler;
emit BurnHandlerSet(previousHandler, address(_handler));
}
/**
* @notice Set the minting pause state
* @param _value The new minting pause state
*/
function setIsMintingPaused(bool _value) external onlyAdmin {
require(isMintingPaused != _value, "ALREADY_SET");
isMintingPaused = _value;
emit IsMintingPausedSet(_value);
}
/**
* @notice Set the mint controller for the pool
* @param _mintController The new mint controller
*/
function setMintController(
IPoolMintControllerV1 _mintController
) external onlyAdmin {
// Sanity
require(
address(_mintController) == address(0) ||
_mintController.isPoolMintController(),
"NOT_POOL_MINT_CONTROLLER"
);
address previousController = address(mintController);
require(previousController != address(_mintController), "ALREADY_SET");
mintController = _mintController;
emit MintControllerSet(previousController, address(_mintController));
}
/**
* @notice Set the burn controller for the pool
* @param _burnController The new burn controller
*/
function setBurnController(
IPoolBurnControllerV1 _burnController
) external onlyAdmin {
// Sanity
require(
address(_burnController) == address(0) ||
_burnController.isPoolBurnController(),
"NOT_POOL_BURN_CONTROLLER"
);
address previousController = address(burnController);
require(previousController != address(_burnController), "ALREADY_SET");
burnController = _burnController;
emit BurnControllerSet(previousController, address(_burnController));
}
/**
* @notice Sweep any non-underlying tokens from the contract
* @dev Owner can sweep any tokens other than the underlying token
* @param _token The token to sweep
* @param _amount The amount to sweep
*/
function sweepTokens(IERC20 _token, uint256 _amount) external onlyAdmin {
require(
address(_token) != address(underlyingToken),
"CANNOT_SWEEP_UNDERLYING_TOKEN"
);
_token.safeTransfer(admin, _amount);
emit TokensSwept(address(_token), admin, _amount);
}
/**
* @notice Sweep native coin from the contract
* @dev Owner can sweep any native coin accidentally sent to the contract
* @param _amount The amount to sweep
*/
function sweepNative(uint256 _amount) external onlyAdmin {
payable(admin).transfer(_amount);
}
// ***** Local Mint/Burn Functions *****
/**
* Mint chips to the given address against underlying tokens taken from the caller
* @param _toAddress The address to mint the chips to
* @param _amount The amount of underlying tokens to mint against
*/
function mintChip(address _toAddress, uint256 _amount) external nonReentrant {
require(!isMintingPaused, "MINT_PAUSED");
require(_amount != 0, "AMOUNT_ZERO");
address minter = msg.sender;
takeUnderlying(minter, _amount);
uint ownAmountToMint = underlyingAmountToOwnAmountInternal(_amount);
IPoolMintControllerV1 _mintController = mintController;
if (address(_mintController) != address(0)) {
bool isPermitted = _mintController.informMintRequest(
minter,
_toAddress,
_amount,
ownAmountToMint
);
require(isPermitted, "MINT_CONTROLLER_REFUSAL");
}
_mint(_toAddress, ownAmountToMint);
emit ChipMinted(minter, _toAddress, _amount, ownAmountToMint);
}
/**
* Burn chips from the caller and transfer the underlying tokens to the 'toAddress'
* @param _receiver The address to receive the underlying tokens
* @param _amount The amount of chips to burn
*/
function burnChip(address _receiver, uint256 _amount) external nonReentrant {
address burner = msg.sender;
safeBurnInternal(burner, _receiver, _amount);
}
/**
* Burn chips from the caller and transfer the underlying tokens to the 'burnHandler' and calls it's 'handleBurn' function
* @param _amount The amount of chips to burn
* @param _payload The payload to pass to the burn handler
*/
function burnChipAndCall(
uint256 _amount,
bytes calldata _payload
) external payable nonReentrant {
require(burnHandler != IBurnHandlerV1(address(0)), "NO_BURN_HANDLER");
// burn the chips
address burner = msg.sender;
uint256 underlyingAmount = safeBurnInternal(
burner,
address(burnHandler),
_amount
);
// call the burn handler
burnHandler.handleBurn{value: msg.value}(
burner,
_amount,
underlyingAmount,
_payload
);
}
// ***** burn internal Functions *****
/**
* Safely burns the chips and transfers the underlying tokens to the receiver
* @param burner The address of the burner
* @param receiver The address to receive the underlying tokens
* @param chipAmount The amount of chips to burn
* @return underlyingAmount The amount of underlying tokens transferred
*/
function safeBurnInternal(
address burner,
address receiver,
uint256 chipAmount
) internal returns (uint256 underlyingAmount) {
// sanity
require(chipAmount != 0, "AMOUNT_ZERO");
// Convert the chip amount to underlying amount
underlyingAmount = ownAmountToUnderlyingAmountInternal(chipAmount);
// sanity
require(underlyingAmount != 0, "UNDERLYING_AMOUNT_ZERO");
// Inform the burn controller
IPoolBurnControllerV1 _burnController = burnController;
if (address(_burnController) != address(0)) {
bool isPermitted = _burnController.informBurnRequest(
burner,
receiver,
underlyingAmount,
chipAmount
);
require(isPermitted, "BURN_CONTROLLER_REFUSAL");
}
// Burn the chips
_burn(burner, chipAmount);
// Transfer the underlying tokens to the receiver
underlyingToken.safeTransfer(receiver, underlyingAmount);
// emit event
emit ChipBurned(burner, receiver, underlyingAmount, chipAmount);
}
// ***** ERC20 internal override Functions *****
/**
* @notice Uses the base ERC20 logic unless 'spender' is marked as 'autoApproved'
*/
function allowance(
address owner,
address spender
) public view virtual override returns (uint256) {
if (autoApproved[spender]) {
return type(uint).max;
} else {
return ERC20.allowance(owner, spender);
}
}
// ***** Underlying utils *****
/**
* Utility function to safely take underlying tokens (ERC20) from a pre-approved account
* @dev Will revert if the contract will not get the exact 'amount' value
*/
function takeUnderlying(address from, uint amount) internal {
uint balanceBefore = underlyingToken.balanceOf(address(this));
underlyingToken.safeTransferFrom(from, address(this), amount);
uint balanceAfter = underlyingToken.balanceOf(address(this));
require(balanceAfter - balanceBefore == amount, "DID_NOT_RECEIVE_EXACT");
}
/**
* Converts the underlying amount to the amount of self tokens by the current exchange rate
*/
function underlyingAmountToOwnAmountInternal(
uint256 underlyingAmount
) internal view returns (uint256 ownAmount) {
ownAmount = (underlyingAmount * SELF_UNIT_SCALE) / exchangeRate;
}
/**
* Converts the (self) LP amount to the equal underlying amount by the current exchange rate
*/
function ownAmountToUnderlyingAmountInternal(
uint256 ownAmount
) internal view returns (uint256 underlyingAmount) {
underlyingAmount = (ownAmount * exchangeRate) / SELF_UNIT_SCALE;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "@layerzerolabs/lz-evm-oapp-v2/contracts/oft/OFT.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import "../../interfaces/IRegistryV1.sol";
import "../../interfaces/ILzCreditControllerV1.sol";
import "../../interfaces/ILzDebitControllerV1.sol";
import "../BaseChip.sol";
/**
* @title OFTChip
* @notice The OFTChip is a remote chip that extends the LayerZero OFT token.
*/
contract OFTChip is OFT, BaseChip {
// ***** Events *****
event IsSendPausedSet(bool isPaused);
event CreditControllerSet(
address indexed previousController,
address indexed newController
);
event DebitControllerSet(
address indexed previousController,
address indexed newController
);
event TokensSwept(
address indexed token,
address indexed receiver,
uint256 amount
);
// ***** Storage *****
bool public isSendPaused;
ILzCreditControllerV1 public creditController;
ILzDebitControllerV1 public debitController;
// ***** Constructor *****
constructor(
IRegistryV1 _registry,
string memory _name,
string memory _symbol,
address _lzEndpoint,
address _delegate,
address _initialOwner
)
OFT(_name, _symbol, _lzEndpoint, _delegate)
BaseChip(_registry, ChipMode.REMOTE)
Ownable(_initialOwner)
{
require(address(_lzEndpoint) != address(0), "!_lzEndpoint");
}
// ***** Admin Functions *****
/**
* @notice Set the auto approved spender for a role
* @param role The role to set the spender for
* @param spender The spender to set
*/
function setAutoApprovedSpenderForRole(
string calldata role,
address spender
) external onlyOwner {
setAutoApprovedSpenderForRoleInternal(role, spender);
}
/**
* @notice Set the send pause state
* @param _isPaused The new send pause state
*/
function setIsSendPaused(bool _isPaused) external onlyOwner {
bool currentState = isSendPaused;
require(_isPaused != currentState, "ALREADY_SET");
isSendPaused = _isPaused;
emit IsSendPausedSet(_isPaused);
}
/**
* @notice Set the credit controller
* @param _creditController The new credit controller
*/
function setCreditController(
ILzCreditControllerV1 _creditController
) external onlyOwner {
// Sanity
require(
address(_creditController) == address(0) ||
_creditController.isCreditController(),
"NOT_CREDIT_CONTROLLER"
);
address previousController = address(creditController);
require(previousController != address(_creditController), "ALREADY_SET");
creditController = _creditController;
emit CreditControllerSet(previousController, address(_creditController));
}
/**
* @notice Set the debit controller
* @param _debitController The new debit controller
*/
function setDebitController(
ILzDebitControllerV1 _debitController
) external onlyOwner {
// Sanity
require(
address(_debitController) == address(0) ||
_debitController.isDebitController(),
"NOT_DEBIT_CONTROLLER"
);
address previousController = address(debitController);
require(previousController != address(_debitController), "ALREADY_SET");
debitController = _debitController;
emit DebitControllerSet(previousController, address(_debitController));
}
/**
* @notice Sweep any non-underlying tokens from the contract
* @dev Owner can sweep any tokens other than the underlying token
* @param _token The token to sweep
* @param _amount The amount to sweep
*/
function sweepTokens(ERC20 _token, uint256 _amount) external onlyOwner {
require(address(_token) != address(this), "CANNOT_SWEEP_SELF");
_token.transfer(owner(), _amount);
emit TokensSwept(address(_token), owner(), _amount);
}
// ***** Lz Functions *****
/**
* @dev Credits tokens to the specified address.
* @param _to The address to credit the tokens to.
* @param _amountLD The amount of tokens to credit in local decimals.
* @dev _srcEid The source chain ID.
* @return amountReceivedLD The amount of tokens ACTUALLY received in local decimals.
*/
function _credit(
address _to,
uint256 _amountLD,
uint32 _srcEid
) internal virtual override returns (uint256 amountReceivedLD) {
ILzCreditControllerV1 creditController_ = creditController;
if (address(creditController_) != address(0)) {
try
creditController_.informLzCreditRequest(_to, _amountLD, _srcEid)
{} catch {}
}
return super._credit(_to, _amountLD, _srcEid);
}
/**
* @dev Burns tokens from the sender's specified balance.
* @param _from The address to debit the tokens from.
* @param _amountLD The amount of tokens to send in local decimals.
* @param _minAmountLD The minimum amount to send in local decimals.
* @param _dstEid The destination chain ID.
* @return amountSentLD The amount sent in local decimals.
* @return amountReceivedLD The amount received in local decimals on the remote.
*/
function _debit(
address _from,
uint256 _amountLD,
uint256 _minAmountLD,
uint32 _dstEid
)
internal
virtual
override
returns (uint256 amountSentLD, uint256 amountReceivedLD)
{
require(!isSendPaused, "SEND_PAUSED");
ILzDebitControllerV1 debitController_ = debitController;
if (address(debitController_) != address(0)) {
require(
debitController_.informLzDebitRequestWithSource(
_from,
_amountLD,
_minAmountLD,
_dstEid
),
"DEBIT_NOT_APPROVED"
);
}
return super._debit(_from, _amountLD, _minAmountLD, _dstEid);
}
// ***** ERC20 internal override Functions *****
/**
* @notice Uses the base ERC20 logic unless 'spender' is marked as 'autoApproved'
*/
function allowance(
address owner,
address spender
) public view virtual override returns (uint256) {
if (autoApproved[spender]) {
return type(uint).max;
} else {
return ERC20.allowance(owner, spender);
}
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
contract ChipEnumsV1 {
enum ChipMode {
NONE,
LOCAL,
REMOTE,
HYBRID
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
interface IBurnHandlerV1 {
function handleBurn(
address burner,
uint256 chipAmount,
uint256 underlyingAmount,
bytes calldata payload
) external payable;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
interface IFundingRateModel {
// return value is the "funding paid by heavier side" in PRECISION per OI (heavier side) per second
// e.g : (0.01 * PRECISION) = Paying (heavier) side (as a whole) pays 1% of funding per second for each OI unit
function getFundingRate(
uint256 pairId,
uint256 openInterestLong,
uint256 openInterestShort,
uint256 pairMaxOpenInterest
) external view returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
interface IGlobalLock {
function lock() external;
function freeLock() external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
interface IInterestRateModel {
// Returns asset/second of interest per borrowed unit
// e.g : (0.01 * PRECISION) = 1% of interest per second
function getBorrowRate(uint256 utilization) external view returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "./LexErrors.sol";
import "./LexPoolAdminEnums.sol";
import "./IPoolAccountantV1.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface LexPoolStructs {
struct PendingDeposit {
uint256 amount;
uint256 minAmountOut;
}
struct PendingRedeem {
uint256 amount;
uint256 minAmountOut;
uint256 maxAmountOut;
}
}
interface LexPoolEvents is LexPoolAdminEnums {
event NewEpoch(
uint256 epochId,
int256 reportedUnrealizedPricePnL,
uint256 exchangeRate,
uint256 virtualUnderlyingBalance,
uint256 totalSupply
);
event AddressUpdated(LexPoolAddressesEnum indexed enumCode, address a);
event NumberUpdated(LexPoolNumbersEnum indexed enumCode, uint value);
event DepositRequest(
address indexed user,
uint256 amount,
uint256 minAmountOut,
uint256 processingEpoch
);
event RedeemRequest(
address indexed user,
uint256 amount,
uint256 minAmountOut,
uint256 processingEpoch
);
event ProcessedDeposit(
address indexed user,
bool deposited,
uint256 depositedAmount
);
event ProcessedRedeem(
address indexed user,
bool redeemed,
uint256 withdrawnAmount // Underlying amount
);
event CanceledDeposit(
address indexed user,
uint256 epoch,
uint256 cancelledAmount
);
event CanceledRedeem(
address indexed user,
uint256 epoch,
uint256 cancelledAmount
);
event ImmediateDepositAllowedToggled(bool indexed value);
event ImmediateDeposit(
address indexed depositor,
uint256 depositAmount,
uint256 mintAmount
);
event ReservesWithdrawn(
address _to,
uint256 interestShare,
uint256 totalFundingShare
);
}
interface ILexPoolFunctionality is
IERC20,
LexPoolStructs,
LexPoolEvents,
LexErrors
{
function setPoolAccountant(
IPoolAccountantFunctionality _poolAccountant
) external;
function setPnlRole(address pnl) external;
function setMaxExtraWithdrawalAmountF(uint256 maxExtra) external;
function setEpochsDelayDeposit(uint256 delay) external;
function setEpochsDelayRedeem(uint256 delay) external;
function setEpochDuration(uint256 duration) external;
function setMinDepositAmount(uint256 amount) external;
function toggleImmediateDepositAllowed() external;
function reduceReserves(
address _to
) external returns (uint256 interestShare, uint256 totalFundingShare);
function requestDeposit(
uint256 amount,
uint256 minAmountOut,
bytes32 domain,
bytes32 referralCode
) external;
function requestDepositViaIntent(
address user,
uint256 amount,
uint256 minAmountOut,
bytes32 domain,
bytes32 referralCode
) external;
function requestRedeem(uint256 amount, uint256 minAmountOut) external;
function requestRedeemViaIntent(
address user,
uint256 amount,
uint256 minAmountOut
) external;
function processDeposit(
address[] memory users
)
external
returns (
uint256 amountDeposited,
uint256 amountCancelled,
uint256 counterDeposited,
uint256 counterCancelled
);
function cancelDeposits(
address[] memory users,
uint256[] memory epochs
) external;
function processRedeems(
address[] memory users
)
external
returns (
uint256 amountRedeemed,
uint256 amountCancelled,
uint256 counterDeposited,
uint256 counterCancelled
);
function cancelRedeems(
address[] memory users,
uint256[] memory epochs
) external;
function nextEpoch(
int256 totalUnrealizedPricePnL
) external returns (uint256 newExchangeRate);
function currentVirtualUtilization() external view returns (uint256);
function currentVirtualUtilization(
uint256 totalBorrows,
uint256 totalReserves,
int256 unrealizedFunding
) external view returns (uint256);
function virtualBalanceForUtilization() external view returns (uint256);
function virtualBalanceForUtilization(
uint256 extraAmount,
int256 unrealizedFunding
) external view returns (uint256);
function underlyingBalanceForExchangeRate() external view returns (uint256);
function sendAssetToTrader(address to, uint256 amount) external;
function isUtilizationForLPsValid() external view returns (bool);
}
interface ILexPoolV1 is ILexPoolFunctionality {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function SELF_UNIT_SCALE() external view returns (uint);
function underlyingDecimals() external view returns (uint256);
function poolAccountant() external view returns (address);
function underlying() external view returns (IERC20);
function tradingFloor() external view returns (address);
function currentEpoch() external view returns (uint256);
function currentExchangeRate() external view returns (uint256);
function nextEpochStartMin() external view returns (uint256);
function epochDuration() external view returns (uint256);
function minDepositAmount() external view returns (uint256);
function epochsDelayDeposit() external view returns (uint256);
function epochsDelayRedeem() external view returns (uint256);
function immediateDepositAllowed() external view returns (bool);
function pendingDeposits(
uint epoch,
address account
) external view returns (PendingDeposit memory);
function pendingRedeems(
uint epoch,
address account
) external view returns (PendingRedeem memory);
function pendingDepositAmount() external view returns (uint256);
function pendingWithdrawalAmount() external view returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
interface ILynxVersionedContract {
/**
* @notice Returns the name of the contract
*/
function getContractName() external view returns (string memory);
/**
* @notice Returns the version of the contract
* @dev units are scaled by 1000 (1,000 = 1.00, 1,120 = 1.12)
*/
function getContractVersion() external view returns (string memory);
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
interface ILzCreditControllerV1 {
function isCreditController() external view returns (bool);
function informLzCreditRequest(
address _to,
uint256 _amountToCreditLD,
uint32 /*_srcEid*/
) external returns (bool isPermitted);
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
interface ILzDebitControllerV1 {
function isDebitController() external view returns (bool);
function informLzDebitRequest(
uint256 _amountToSendLD, // amount to send in local decimals()
uint256 _minAmountToCreditLD, // minimum ammount to credit on the destination
uint32 _dstEid // destination endpoint id
) external returns (bool isPermitted);
function informLzDebitRequestWithSource(
address _debitFrom, // address to debit from
uint256 _amountToSendLD, // amount to send in local decimals()
uint256 _minAmountToCreditLD, // minimum ammount to credit on the destination
uint32 _dstEid // destination endpoint id
) external returns (bool isPermitted);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "./LexErrors.sol";
import "./ILexPoolV1.sol";
import "./IInterestRateModel.sol";
import "./IFundingRateModel.sol";
import "./TradingEnumsV1.sol";
interface PoolAccountantStructs {
// @note To be used for passing information in function calls
struct PositionRegistrationParams {
uint256 collateral;
uint32 leverage;
bool long;
uint64 openPrice;
uint64 tp;
}
struct PairFunding {
// Slot 0
int256 accPerOiLong; // 32 bytes -- Underlying Decimals
// Slot 1
int256 accPerOiShort; // 32 bytes -- Underlying Decimals
// Slot 2
uint256 lastUpdateTimestamp; // 32 bytes
}
struct TradeInitialAccFees {
// Slot 0
uint256 borrowIndex; // 32 bytes
// Slot 1
int256 funding; // 32 bytes -- underlying units -- Underlying Decimals
}
struct PairOpenInterest {
// Slot 0
uint256 long; // 32 bytes -- underlying units -- Dynamic open interest for long positions
// Slot 1
uint256 short; // 32 bytes -- underlying units -- Dynamic open interest for short positions
}
// This struct is not kept in storage
struct PairFromTo {
string from;
string to;
}
struct Pair {
// Slot 0
uint16 id; // 02 bytes
uint16 groupId; // 02 bytes
uint16 feeId; // 02 bytes
uint32 minLeverage; // 04 bytes
uint32 maxLeverage; // 04 bytes
uint32 maxBorrowF; // 04 bytes -- FRACTION_SCALE (5)
// Slot 1
uint256 maxPositionSize; // 32 bytes -- underlying units
// Slot 2
uint256 maxGain; // 32 bytes -- underlying units
// Slot 3
uint256 maxOpenInterest; // 32 bytes -- Underlying units
// Slot 4
uint256 maxSkew; // 32 bytes -- underlying units
// Slot 5
uint256 minOpenFee; // 32 bytes -- underlying units. MAX_UINT means use the default group level value
// Slot 6
uint256 minPerformanceFee; // 32 bytes -- underlying units
}
struct Group {
// Slot 0
uint16 id; // 02 bytes
uint32 minLeverage; // 04 bytes
uint32 maxLeverage; // 04 bytes
uint32 maxBorrowF; // 04 bytes -- FRACTION_SCALE (5)
// Slot 1
uint256 maxPositionSize; // 32 bytes (Underlying units)
// Slot 2
uint256 minOpenFee; // 32 bytes (Underlying uints). MAX_UINT means use the default global level value
}
struct Fee {
// Slot 0
uint16 id; // 02 bytes
uint32 openFeeF; // 04 bytes -- FRACTION_SCALE (5) (Fraction of leveraged pos)
uint32 closeFeeF; // 04 bytes -- FRACTION_SCALE (5) (Fraction of leveraged pos)
uint32 performanceFeeF; // 04 bytes -- FRACTION_SCALE (5) (Fraction of performance)
}
}
interface PoolAccountantEvents is PoolAccountantStructs {
event PairAdded(
uint256 indexed id,
string indexed from,
string indexed to,
Pair pair
);
event PairUpdated(uint256 indexed id, Pair pair);
event GroupAdded(uint256 indexed id, string indexed groupName, Group group);
event GroupUpdated(uint256 indexed id, Group group);
event FeeAdded(uint256 indexed id, string indexed name, Fee fee);
event FeeUpdated(uint256 indexed id, Fee fee);
event TradeInitialAccFeesStored(
bytes32 indexed positionId,
uint256 borrowIndex,
// uint256 rollover,
int256 funding
);
event AccrueFunding(
uint256 indexed pairId,
int256 valueLong,
int256 valueShort
);
event ProtocolFundingShareAccrued(
uint16 indexed pairId,
uint256 protocolFundingShare
);
// event AccRolloverFeesStored(uint256 pairIndex, uint256 value);
event FeesCharged(
bytes32 indexed positionId,
address indexed trader,
uint16 indexed pairId,
PositionRegistrationParams positionRegistrationParams,
// bool long,
// uint256 collateral, // Underlying Decimals
// uint256 leverage,
int256 profitPrecision, // PRECISION
uint256 interest,
int256 funding, // Underlying Decimals
uint256 closingFee,
uint256 tradeValue
);
event PerformanceFeeCharging(
bytes32 indexed positionId,
uint256 performanceFee
);
event MaxOpenInterestUpdated(uint256 pairIndex, uint256 maxOpenInterest);
event AccrueInterest(
uint256 cash,
uint256 totalInterestNew,
uint256 borrowIndexNew,
uint256 interestShareNew
);
event Borrow(
uint256 indexed pairId,
uint256 borrowAmount,
uint256 newTotalBorrows
);
event Repay(
uint256 indexed pairId,
uint256 repayAmount,
uint256 newTotalBorrows
);
}
interface IPoolAccountantFunctionality is
PoolAccountantStructs,
PoolAccountantEvents,
LexErrors,
TradingEnumsV1
{
function setTradeIncentivizer(address _tradeIncentivizer) external;
function setMaxGainF(uint256 _maxGainF) external;
function setFrm(IFundingRateModel _frm) external;
function setMinOpenFee(uint256 min) external;
function setLexPartF(uint256 partF) external;
function setFundingRateMax(uint256 maxValue) external;
function setLiquidationThresholdF(uint256 threshold) external;
function setLiquidationFeeF(uint256 fee) external;
function setIrm(IInterestRateModel _irm) external;
function setIrmHard(IInterestRateModel _irm) external;
function setInterestShareFactor(uint256 factor) external;
function setFundingShareFactor(uint256 factor) external;
function setBorrowRateMax(uint256 rate) external;
function setMaxTotalBorrows(uint256 maxBorrows) external;
function setMaxVirtualUtilization(uint256 _maxVirtualUtilization) external;
function resetTradersPairGains(uint256 pairId) external;
function addGroup(Group calldata _group) external;
function updateGroup(Group calldata _group) external;
function addFee(Fee calldata _fee) external;
function updateFee(Fee calldata _fee) external;
function addPair(Pair calldata _pair) external;
function addPairs(Pair[] calldata _pairs) external;
function updatePair(Pair calldata _pair) external;
function readAndZeroReserves()
external
returns (uint256 accumulatedInterestShare,
uint256 accFundingShare);
function registerOpenTrade(
bytes32 positionId,
address trader,
uint16 pairId,
uint256 collateral,
uint32 leverage,
bool long,
uint256 tp,
uint256 openPrice
) external returns (uint256 fee, uint256 lexPartFee);
function registerCloseTrade(
bytes32 positionId,
address trader,
uint16 pairId,
PositionRegistrationParams calldata positionRegistrationParams,
uint256 closePrice,
PositionCloseType positionCloseType
)
external
returns (
uint256 closingFee,
uint256 tradeValue,
int256 profitPrecision,
uint finalClosePrice
);
function registerUpdateTp(
bytes32 positionId,
address trader,
uint16 pairId,
uint256 collateral,
uint32 leverage,
bool long,
uint256 openPrice,
uint256 oldTriggerPrice,
uint256 triggerPrice
) external;
// function registerUpdateSl(
// address trader,
// uint256 pairIndex,
// uint256 index,
// uint256 collateral,
// uint256 leverage,
// bool long,
// uint256 openPrice,
// uint256 triggerPrice
// ) external returns (uint256 fee);
function accrueInterest()
external
returns (
uint256 totalInterestNew,
uint256 interestShareNew,
uint256 borrowIndexNew
);
// Limited only for the LexPool
function accrueInterest(
uint256 availableCash
)
external
returns (
uint256 totalInterestNew,
uint256 interestShareNew,
uint256 borrowIndexNew
);
function getTradeClosingValues(
bytes32 positionId,
uint16 pairId,
PositionRegistrationParams calldata positionRegistrationParams,
uint256 closePrice,
bool isLiquidation
)
external
returns (
uint256 tradeValue, // Underlying Decimals
uint256 safeClosingFee,
int256 profitPrecision,
uint256 interest,
int256 funding
);
function getTradeLiquidationPrice(
bytes32 positionId,
uint16 pairId,
uint256 openPrice, // PRICE_SCALE (8)
uint256 tp,
bool long,
uint256 collateral, // Underlying Decimals
uint32 leverage
)
external
returns (
uint256 // PRICE_SCALE (8)
);
function calcTradeDynamicFees(
bytes32 positionId,
uint16 pairId,
bool long,
uint256 collateral,
uint32 leverage,
uint256 openPrice,
uint256 tp
) external returns (uint256 interest, int256 funding);
function unrealizedFunding() external view returns (int256);
function totalBorrows() external view returns (uint256);
function interestShare() external view returns (uint256);
function fundingShare() external view returns (uint256);
function totalReservesView() external view returns (uint256);
function borrowsAndInterestShare()
external
view
returns (uint256 totalBorrows, uint256 totalInterestShare);
function pairTotalOpenInterest(
uint256 pairIndex
) external view returns (int256);
function pricePnL(
uint256 pairId,
uint256 price
) external view returns (int256);
function getAllSupportedPairIds() external view returns (uint16[] memory);
function getAllSupportedGroupsIds() external view returns (uint16[] memory);
function getAllSupportedFeeIds() external view returns (uint16[] memory);
}
interface IPoolAccountantV1 is IPoolAccountantFunctionality {
function totalBorrows() external view returns (uint256);
function maxTotalBorrows() external view returns (uint256);
function pairBorrows(uint256 pairId) external view returns (uint256);
function groupBorrows(uint256 groupId) external view returns (uint256);
function pairMaxBorrow(uint16 pairId) external view returns (uint256);
function groupMaxBorrow(uint16 groupId) external view returns (uint256);
function lexPool() external view returns (ILexPoolV1);
function maxGainF() external view returns (uint256);
function interestShareFactor() external view returns (uint256);
function fundingShareFactor() external view returns (uint256);
function frm() external view returns (IFundingRateModel);
function irm() external view returns (IInterestRateModel);
function pairs(uint16 pairId) external view returns (Pair memory);
function groups(uint16 groupId) external view returns (Group memory);
function fees(uint16 feeId) external view returns (Fee memory);
function openInterestInPair(
uint pairId
) external view returns (PairOpenInterest memory);
function minOpenFee() external view returns (uint256);
function liquidationThresholdF() external view returns (uint256);
function liquidationFeeF() external view returns (uint256);
function lexPartF() external view returns (uint256);
function tradersPairGains(uint256 pairId) external view returns (int256);
function calcBorrowAmount(
uint256 collateral,
uint256 leverage,
bool long,
uint256 openPrice,
uint256 tp
) external pure returns (uint256);
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
interface IPoolBurnControllerV1 {
/**
* @notice Check if the contract is a PoolBurnController
*/
function isPoolBurnController() external view returns (bool);
/**
* @notice Inform the PoolBurnController of a burn request
* param _burner The address of the account that is burning the tokens
* param _receiver The address of the account that will receive the underlying tokens
* param _underlyingAmount The amount of underlying tokens that will be given for burning
* param _burnAmount The amount of tokens that will be burned
*/
function informBurnRequest(
address _burner,
address _receiver,
uint256 _underlyingAmount,
uint256 _burnAmount
) external returns (bool isPermitted);
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
interface IPoolMintControllerV1 {
/**
* @notice Check if the contract is a PoolMintController
*/
function isPoolMintController() external view returns (bool);
/**
* @notice Inform the PoolMintController of a mint request
* param _minter The address of the account that is minting the tokens
* param _to The address of the account that is minting the tokens
* param _underlyingAmount The amount of underlying tokens that were taken for minting
* param _mintAmount The amount of tokens that will be minted
*/
function informMintRequest(
address _minter,
address _to,
uint256 _underlyingAmount,
uint256 _mintAmount
) external returns (bool isPermitted);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "../../AdministrationContracts/IContractRegistryBase.sol";
import "./IGlobalLock.sol";
interface IRegistryV1Functionality is IContractRegistryBase, IGlobalLock {
// **** Locking mechanism ****
function isTradersPortalAndLocker(
address _address
) external view returns (bool);
function isTriggersAndLocker(address _address) external view returns (bool);
function isTradersPortalOrTriggersAndLocker(
address _address
) external view returns (bool);
}
interface IRegistryV1 is IRegistryV1Functionality {
// **** Public Storage params ****
function feesManagers(address asset) external view returns (address);
function orderBook() external view returns (address);
function tradersPortal() external view returns (address);
function triggers() external view returns (address);
function tradeIntentsVerifier() external view returns (address);
function liquidityIntentsVerifier() external view returns (address);
function chipsIntentsVerifier() external view returns (address);
function lexProxiesFactory() external view returns (address);
function chipsFactory() external view returns (address);
/**
* @return An array of all supported trading floors
*/
function getAllSupportedTradingFloors()
external
view
returns (address[] memory);
/**
* @return An array of all supported settlement assets
*/
function getSettlementAssetsForTradingFloor(
address _tradingFloor
) external view returns (address[] memory);
/**
* @return The spender role address that is set for this chip
*/
function getValidSpenderTargetForChipByRole(
address chip,
string calldata role
) external view returns (address);
/**
* @return the address of the valid 'burnHandler' for the chip
*/
function validBurnHandlerForChip(
address chip
) external view returns (address);
/**
* @return The address matching for the given role
*/
function getDynamicRoleAddress(
string calldata _role
) external view returns (address);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "./TradingFloorStructsV1.sol";
import "./IPoolAccountantV1.sol";
import "./ILexPoolV1.sol";
interface ITradingFloorV1Functionality is TradingFloorStructsV1 {
function supportNewSettlementAsset(
address _asset,
address _lexPool,
address _poolAccountant
) external;
function getPositionTriggerInfo(
bytes32 _positionId
)
external
view
returns (
PositionPhase positionPhase,
uint64 timestamp,
uint16 pairId,
bool long,
uint32 spreadReductionF
);
function getPositionPortalInfo(
bytes32 _positionId
)
external
view
returns (
PositionPhase positionPhase,
uint64 inPhaseSince,
address positionTrader
);
function storePendingPosition(
OpenOrderType _orderType,
PositionRequestIdentifiers memory _requestIdentifiers,
PositionRequestParams memory _requestParams,
uint32 _spreadReductionF
) external returns (bytes32 positionId);
function setOpenedPositionToMarketClose(
bytes32 _positionId,
uint64 _minPrice,
uint64 _maxPrice
) external;
function cancelPendingPosition(
bytes32 _positionId,
OpenOrderType _orderType,
uint feeFraction
) external;
function cancelMarketCloseForPosition(
bytes32 _positionId,
CloseOrderType _orderType,
uint feeFraction
) external;
function updatePendingPosition_openLimit(
bytes32 _positionId,
uint64 _minPrice,
uint64 _maxPrice,
uint64 _tp,
uint64 _sl
) external;
function openNewPosition_market(
bytes32 _positionId,
uint64 assetEffectivePrice,
uint256 feeForCancellation
) external;
function openNewPosition_limit(
bytes32 _positionId,
uint64 assetEffectivePrice,
uint256 feeForCancellation
) external;
function closeExistingPosition_Market(
bytes32 _positionId,
uint64 assetPrice,
uint64 effectivePrice
) external;
function closeExistingPosition_Limit(
bytes32 _positionId,
LimitTrigger limitTrigger,
uint64 assetPrice,
uint64 effectivePrice
) external;
// Manage open trade
function updateOpenedPosition(
bytes32 _positionId,
PositionField updateField,
uint64 fieldValue,
uint64 effectivePrice
) external;
// Fees
function collectFee(address _asset, FeeType _feeType, address _to) external;
}
interface ITradingFloorV1 is ITradingFloorV1Functionality {
function PRECISION() external pure returns (uint);
// *** Views ***
function pairTradersArray(
address _asset,
uint _pairIndex
) external view returns (address[] memory);
function generatePositionHashId(
address settlementAsset,
address trader,
uint16 pairId,
uint32 index
) external pure returns (bytes32 hashId);
// *** Public Storage addresses ***
function lexPoolForAsset(address asset) external view returns (ILexPoolV1);
function poolAccountantForAsset(
address asset
) external view returns (IPoolAccountantV1);
function registry() external view returns (address);
// *** Public Storage params ***
function positionsById(bytes32 id) external view returns (Position memory);
function positionIdentifiersById(
bytes32 id
) external view returns (PositionIdentifiers memory);
function positionLimitsInfoById(
bytes32 id
) external view returns (PositionLimitsInfo memory);
function triggerPricesById(
bytes32 id
) external view returns (PositionTriggerPrices memory);
function pairTradersInfo(
address settlementAsset,
address trader,
uint pairId
) external view returns (PairTraderInfo memory);
function spreadReductionsP(uint) external view returns (uint);
function maxSlF() external view returns (uint);
function maxTradesPerPair() external view returns (uint);
function maxSanityProfitF() external view returns (uint);
function feesMap(
address settlementAsset,
FeeType feeType
) external view returns (uint256);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
interface LexErrors {
enum CapType {
NONE, // 0
MIN_OPEN_FEE, // 1
MAX_POS_SIZE_PAIR, // 2
MAX_POS_SIZE_GROUP, // 3
MAX_LEVERAGE, // 4
MIN_LEVERAGE, // 5
MAX_VIRTUAL_UTILIZATION, // 6
MAX_OPEN_INTEREST, // 7
MAX_ABS_SKEW, // 8
MAX_BORROW_PAIR, // 9
MAX_BORROW_GROUP, // 10
MIN_DEPOSIT_AMOUNT, // 11
MAX_ACCUMULATED_GAINS, // 12
BORROW_RATE_MAX, // 13
FUNDING_RATE_MAX, // 14
MAX_POTENTIAL_GAIN, // 15
MAX_TOTAL_BORROW, // 16
MIN_PERFORMANCE_FEE // 17
//...
}
error CapError(CapType, uint256 value);
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
interface LexPoolAdminEnums {
enum LexPoolAddressesEnum {
none,
poolAccountant,
pnlRole
}
enum LexPoolNumbersEnum {
none,
maxExtraWithdrawalAmountF,
epochsDelayDeposit,
epochsDelayRedeem,
epochDuration,
minDepositAmount
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
interface TradingEnumsV1 {
enum PositionPhase {
NONE,
OPEN_MARKET,
OPEN_LIMIT,
OPENED,
CLOSE_MARKET,
CLOSED
}
enum OpenOrderType {
NONE,
MARKET,
LIMIT
}
enum CloseOrderType {
NONE,
MARKET
}
enum FeeType {
NONE,
OPEN_FEE,
CLOSE_FEE,
TRIGGER_FEE
}
enum LimitTrigger {
NONE,
TP,
SL,
LIQ
}
enum PositionField {
NONE,
TP,
SL
}
enum PositionCloseType {
NONE,
TP,
SL,
LIQ,
MARKET
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "./TradingEnumsV1.sol";
interface TradingFloorStructsV1 is TradingEnumsV1 {
enum AdminNumericParam {
NONE,
MAX_TRADES_PER_PAIR,
MAX_SL_F,
MAX_SANITY_PROFIT_F
}
/**
* @dev Memory struct for identifiers
*/
struct PositionRequestIdentifiers {
address trader;
uint16 pairId;
address settlementAsset;
uint32 positionIndex;
}
struct PositionRequestParams {
bool long;
uint256 collateral; // Settlement Asset Decimals
uint32 leverage;
uint64 minPrice; // PRICE_SCALE
uint64 maxPrice; // PRICE_SCALE
uint64 tp; // PRICE_SCALE
uint64 sl; // PRICE_SCALE
uint64 tpByFraction; // FRACTION_SCALE
uint64 slByFraction; // FRACTION_SCALE
}
/**
* @dev Storage struct for identifiers
*/
struct PositionIdentifiers {
// Slot 0
address settlementAsset; // 20 bytes
uint16 pairId; // 02 bytes
uint32 index; // 04 bytes
// Slot 1
address trader; // 20 bytes
}
struct Position {
// Slot 0
uint collateral; // 32 bytes -- Settlement Asset Decimals
// Slot 1
PositionPhase phase; // 01 bytes
uint64 inPhaseSince; // 08 bytes
uint32 leverage; // 04 bytes
bool long; // 01 bytes
uint64 openPrice; // 08 bytes -- PRICE_SCALE (8)
uint32 spreadReductionF; // 04 bytes -- FRACTION_SCALE (5)
}
/**
* Holds the non liquidation limits for the position
*/
struct PositionLimitsInfo {
uint64 tpLastUpdated; // 08 bytes -- timestamp
uint64 slLastUpdated; // 08 bytes -- timestamp
uint64 tp; // 08 bytes -- PRICE_SCALE (8)
uint64 sl; // 08 bytes -- PRICE_SCALE (8)
}
/**
* Holds the prices for opening (and market closing) of a position
*/
struct PositionTriggerPrices {
uint64 minPrice; // 08 bytes -- PRICE_SCALE
uint64 maxPrice; // 08 bytes -- PRICE_SCALE
uint64 tpByFraction; // 04 bytes -- FRACTION_SCALE
uint64 slByFraction; // 04 bytes -- FRACTION_SCALE
}
/**
* @dev administration struct, used to keep tracks on the 'PairTraders' list and
* to limit the amount of positions a trader can have
*/
struct PairTraderInfo {
uint32 positionsCounter; // 04 bytes
uint32 positionInArray; // 04 bytes (the index + 1)
// Note : Can add more fields here
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "../../AdministrationContracts/AcceptableImplementationClaimableAdmin.sol";
/**
* @title RegistryProxy
* @dev Used as the contracts registry brain of the Lynx platform
*/
contract RegistryProxy is AcceptableImplementationClaimableAdmin {
constructor() AcceptableImplementationClaimableAdmin(msg.sender) {}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "../../AdministrationContracts/AcceptableImplementationClaimableAdminStorage.sol";
/**
* @title RegistryStorage
* @dev Storage contract for the Registry
*/
contract RegistryStorage is AcceptableImplementationClaimableAdminStorage {
uint256 public constant VERSION_SCALE = 1000; // 1,000 = 1.00, 1,120 = 1.12
// ***** Locking mechanism *****
// System lock
address public systemLockOwner;
// Address => is allowed to lock the system
mapping(address => bool) public validSystemLockOwners;
// ***** Versioning mechanism *****
// contract name hash => latest version number
mapping(bytes32 => uint256) public latestVersions;
// version => (contract name hash => implementation)
mapping(uint256 => mapping(bytes32 => address)) public implementations;
// ***** Trading Floors *****
// trading floor => is supported
mapping(address => bool) public isTradingFloorSupported;
// all supported trading floors
address[] public supportedTradingFloors;
// trading floor => supported settlement assets lists
mapping(address => address[]) public settlementAssetsForTradingFloor;
// ***** Roles mechanism *****
// asset => feesManager
mapping(address => address) public feesManagers;
// role hash => address
mapping(bytes32 => address) public dynamicRoleAddresses;
address public orderBook;
address public tradersPortal;
address public triggers;
address public tradeIntentsVerifier;
address public liquidityIntentsVerifier;
address public chipsIntentsVerifier;
// ***** Chips *****
// chip => role (hash) => spender
mapping(address => mapping(bytes32 => address))
public validSpenderTargetForChipByRole;
// chip => valid burn handler
mapping(address => address) public validBurnHandlerForChip;
// ***** Factories *****
address public lexProxiesFactory;
address public chipsFactory;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {ILynxVersionedContract} from "../../../interfaces/ILynxVersionedContract.sol";
abstract contract SingleContractDeployerBase is ILynxVersionedContract {
// ***** Events *****
event FactoryRoleSet(
address indexed previousFactoryRole,
address indexed newFactoryRole
);
event ContractDeployed(address indexed newContract);
// ***** Immutable *****
// For readability only, should not use this value for on-chain logic
string public DEPLOYED_CONTRACT_NAME;
string public DEPLOYED_CONTRACT_VERSION;
// ***** Storage *****
address[] public allDeployedContracts;
// contract address => was deployed by this contract
mapping(address => bool) public wasDeployedFromHere;
// ***** Modifiers *****
modifier onlyFactoryRole() {
require(msg.sender == getFactoryRole(), "NOT_FACTORY_ROLE");
_;
}
// ***** Views *****
function getDeployedContractName() external view returns (string memory) {
return DEPLOYED_CONTRACT_NAME;
}
function getAllDeployedContractsAddresses()
external
view
returns (address[] memory)
{
return allDeployedContracts;
}
// ***** Public Virtual Views *****
function getFactoryRole() public virtual returns (address);
// ***** Constructor *****
constructor(
string memory _deployedContractName,
string memory _deployedContractVersion
) {
DEPLOYED_CONTRACT_NAME = _deployedContractName;
DEPLOYED_CONTRACT_VERSION = _deployedContractVersion;
}
// ***** Deployer Functions *****
function deploySingleContract(
bytes calldata payload
) public onlyFactoryRole returns (address) {
address deployedContract = deploySingleContractInternal(payload);
onContractDeployed(deployedContract);
return deployedContract;
}
// ***** Internal Functions *****
function onContractDeployed(address _deployedContract) internal {
// Sanity
require(!wasDeployedFromHere[_deployedContract], "HANDLER_ALREADY_CALLED");
// State
allDeployedContracts.push(_deployedContract);
wasDeployedFromHere[_deployedContract] = true;
// Events
emit ContractDeployed(_deployedContract);
}
// ***** Internal Virtual Functions *****
function deploySingleContractInternal(
bytes calldata payload
) internal virtual returns (address);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {SingleContractDeployerBase} from "../baseContracts/SingleContractDeployerBase.sol";
import {IRegistryV1} from "../../../interfaces/IRegistryV1.sol";
import {EngineChip, IERC20} from "../../../Chips/EngineChip/EngineChip.sol";
contract EngineChipDeployer is SingleContractDeployerBase {
// ***** Constants (ILynxVersionedContract interface) *****
string public constant CONTRACT_NAME = "EngineChipDeployer";
string public constant CONTRACT_VERSION = "1000"; // 1.0
// ***** Views (ILynxVersionedContract interface) *****
function getContractName() external pure override returns (string memory) {
return CONTRACT_NAME;
}
function getContractVersion() external pure override returns (string memory) {
return CONTRACT_VERSION;
}
// ***** Storage *****
/**
* @notice System Registry
*/
address public immutable registry;
// ***** Public Override Views *****
function getFactoryRole() public override returns (address) {
return IRegistryV1(registry).chipsFactory();
}
// ***** Constructor *****
constructor(
address _registry
)
SingleContractDeployerBase(
"EngineChip",
// 1.0
"1000"
)
{
registry = _registry;
}
// ***** Deployment Functions *****
function deployEngineChip(
string memory _name,
string memory _symbol,
address _underlyingToken,
address _initialAdmin
) external onlyFactoryRole returns (address) {
address freshEngineChip = deployEngineChipInternal(
_name,
_symbol,
_underlyingToken,
_initialAdmin
);
// Call base hook
onContractDeployed(freshEngineChip);
return freshEngineChip;
}
// ***** Internal Override Functions *****
/**
* @notice Implements the 'SingleContractDeployerBase' generic deploy function
*/
function deploySingleContractInternal(
bytes calldata payload
) internal override returns (address) {
(
string memory name,
string memory symbol,
address underlyingToken,
address initialAdmin
) = abi.decode(payload, (string, string, address, address));
// Continue in the deployment
return
deployEngineChipInternal(name, symbol, underlyingToken, initialAdmin);
}
// ***** Internal Deployment Functions *****
function deployEngineChipInternal(
string memory _name,
string memory _symbol,
address _underlyingToken,
address _initialAdmin
) internal returns (address) {
// Sanity checks
require(bytes(_name).length > 0, "NO_NAME");
require(bytes(_symbol).length > 0, "NO_SYMBOL");
require(_underlyingToken != address(0), "NO_UNDERLYING_TOKEN");
require(_initialAdmin != address(0), "NO_INITIAL_ADMIN");
address freshEngineChip = address(
new EngineChip(
IRegistryV1(registry),
_name,
_symbol,
IERC20(_underlyingToken),
_initialAdmin
)
);
return freshEngineChip;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {SingleContractDeployerBase} from "../baseContracts/SingleContractDeployerBase.sol";
import {IRegistryV1} from "../../../interfaces/IRegistryV1.sol";
import {OFTChip} from "../../../Chips/OFTChip/OFTChip.sol";
contract OFTChipDeployer is SingleContractDeployerBase {
// ***** Constants (ILynxVersionedContract interface) *****
string public constant CONTRACT_NAME = "OFTChipDeployer";
string public constant CONTRACT_VERSION = "1000"; // 1.0
// ***** Views (ILynxVersionedContract interface) *****
function getContractName() external pure override returns (string memory) {
return CONTRACT_NAME;
}
function getContractVersion() external pure override returns (string memory) {
return CONTRACT_VERSION;
}
// ***** Storage *****
/**
* @notice System Registry
*/
address public immutable registry;
// ***** Public Override Views *****
function getFactoryRole() public view override returns (address) {
return IRegistryV1(registry).chipsFactory();
}
// ***** Constructor *****
constructor(
address _registry
)
SingleContractDeployerBase(
"OFTChip",
// 1.0
"1000"
)
{
registry = _registry;
}
// ***** Deployment Functions *****
function deployOFTChip(
string memory _name,
string memory _symbol,
address _lzEndpoint,
address _delegate,
address _initialOwner
) external onlyFactoryRole returns (address) {
address freshOFTChip = deployOFTChipInternal(
_name,
_symbol,
_lzEndpoint,
_delegate,
_initialOwner
);
// Call base hook
onContractDeployed(freshOFTChip);
return freshOFTChip;
}
// ***** Internal Override Functions *****
/**
* @notice Implements the 'SingleContractDeployerBase' generic deploy function
*/
function deploySingleContractInternal(
bytes calldata payload
) internal override returns (address) {
(
string memory name,
string memory symbol,
address lzEndpoint,
address delegate,
address initialOwner
) = abi.decode(payload, (string, string, address, address, address));
// Continue in the deployment
return
deployOFTChipInternal(name, symbol, lzEndpoint, delegate, initialOwner);
}
// ***** Internal Deployment Functions *****
function deployOFTChipInternal(
string memory _name,
string memory _symbol,
address _lzEndpoint,
address _delegate,
address _initialOwner
) internal returns (address) {
// Sanity checks
require(bytes(_name).length > 0, "NO_NAME");
require(bytes(_symbol).length > 0, "NO_SYMBOL");
require(_lzEndpoint != address(0), "NO_LZ_ENDPOINT");
require(_delegate != address(0), "NO_DELEGATE");
require(_initialOwner != address(0), "NO_INITIAL_OWNER");
address freshOFTChip = address(
new OFTChip(
IRegistryV1(registry),
_name,
_symbol,
_lzEndpoint,
_delegate,
_initialOwner
)
);
return freshOFTChip;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {SingleContractDeployerBase} from "../baseContracts/SingleContractDeployerBase.sol";
abstract contract RegistryBasedProxySingleContractDeployer is
SingleContractDeployerBase
{
// ***** Storage *****
/**
* @notice System Registry
*/
address public immutable registry;
// ***** Constructor *****
constructor(
address _registry,
string memory _deployedContractName,
string memory _deployedContractVersion
)
SingleContractDeployerBase(_deployedContractName, _deployedContractVersion)
{
registry = _registry;
}
// ***** Deployment functions *****
/**
* @notice Specific deploy function
*/
function deployRegistryProxy(
address _initialAdmin
) external onlyFactoryRole returns (address) {
address deployedContract = deployRegistryProxyInternal(_initialAdmin);
// Call base hook
onContractDeployed(deployedContract);
return deployedContract;
}
// ***** Internal override functions *****
/**
* @notice Implements the 'SingleContractDeployerBase' generic deploy function
*/
function deploySingleContractInternal(
bytes calldata payload
) internal override returns (address) {
// Check payload length - address is exactly 32 bytes with encodePacked
require(payload.length == 32, "INVALID_PAYLOAD_LENGTH");
// Convert bytes to address
address initialAdminParam = abi.decode(payload, (address));
require(initialAdminParam != address(0), "INVALID_INITIAL_ADMIN");
// Continue in the specific deployment function
return deployRegistryProxyInternal(initialAdminParam);
}
// ***** Internal virtual functions *****
/**
* @notice Virtual function to allow deployment of a specific Registry Proxy
*/
function deployRegistryProxyInternal(
address _initialAdmin
) internal virtual returns (address);
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IRegistryV1} from "../../interfaces/IRegistryV1.sol";
import {ILynxVersionedContract} from "../../interfaces/ILynxVersionedContract.sol";
import {SingleContractDeployerBase} from "../deployers/baseContracts/SingleContractDeployerBase.sol";
import {EngineChipDeployer} from "../deployers/chips/EngineChipDeployer.sol";
import {OFTChipDeployer} from "../deployers/chips/OFTChipDeployer.sol";
contract ChipsFactory is ILynxVersionedContract {
// ***** Events *****
event ApprovedCallerSet(address indexed caller, bool indexed isApproved);
event EngineChipDeployed(
address indexed asset,
address indexed caller,
address indexed engineChip,
string symbol
);
event OFTChipDeployed(
string indexed symbol,
address indexed caller,
address indexed oftChip
);
event ImportedEngineChipForAsset(
address indexed asset,
address indexed caller,
address indexed engineChip
);
event ImportedOFTChipForSymbol(
string indexed symbol,
address indexed caller,
address indexed oftChip
);
// ***** Constants (ILynxVersionedContract interface) *****
string public constant CONTRACT_NAME = "ChipsFactory";
string public constant CONTRACT_VERSION = "100"; // 0.10
// ***** Immutable *****
string public constant CHIPS_DEPLOYER_ROLE_KEY = "CHIPS_DEPLOYER_ROLE";
/**
* @notice System Registry
*/
address public immutable registry;
address public immutable engineChipDeployer;
address public immutable oftChipDeployer;
// ***** Storage *****
mapping(address => address) public engineChipForAsset;
mapping(address => bool) public deployedEngineChips;
mapping(string => address) public oftChipForSymbol;
mapping(address => bool) public deployedOFTChips;
address[] public allAssetsWithEngineChip;
string[] public allSymbolsWithOFTChip;
// ***** Views (ILynxVersionedContract interface) *****
function getContractName() external pure override returns (string memory) {
return CONTRACT_NAME;
}
function getContractVersion() external pure override returns (string memory) {
return CONTRACT_VERSION;
}
// ***** Views *****
function getAllAssetsWithEngineChip() public view returns (address[] memory) {
return allAssetsWithEngineChip;
}
function getAllSymbolsWithOFTChip() public view returns (string[] memory) {
return allSymbolsWithOFTChip;
}
function isChipDeployedByFactory(address _chip) public view returns (bool) {
return
isOFTChipDeployedByFactory(_chip) || isEngineChipDeployedByFactory(_chip);
}
function isEngineChipDeployedByFactory(
address _engineChip
) public view returns (bool) {
return deployedEngineChips[_engineChip];
}
function isOFTChipDeployedByFactory(
address _oftChip
) public view returns (bool) {
return deployedOFTChips[_oftChip];
}
// ***** Constructor *****
constructor(
address _registry,
address _engineChipDeployer,
address _oftChipDeployer
) {
// Sanity -- Ensure the deployer is connected to the same registry
require(
_registry == EngineChipDeployer(_engineChipDeployer).registry(),
"REGISTRY_MISMATCH"
);
// Sanity -- Ensure the deployer deploys what we expect
validateProxyDeployerContract(_engineChipDeployer, "EngineChip");
// Sanity -- Ensure the deployer is connected to the same registry
require(
_registry == OFTChipDeployer(_oftChipDeployer).registry(),
"REGISTRY_MISMATCH"
);
// Sanity -- Ensure the deployer deploys what we expect
validateProxyDeployerContract(_oftChipDeployer, "OFTChip");
// Immutables
registry = _registry;
engineChipDeployer = _engineChipDeployer;
oftChipDeployer = _oftChipDeployer;
}
// ***** Import/Set Ledger *****
function importEngineChipsFromChipsFactory(
ChipsFactory _factoryToImportFrom
) public {
address chipsDeployerRole = IRegistryV1(registry).getDynamicRoleAddress(
CHIPS_DEPLOYER_ROLE_KEY
);
require(msg.sender == chipsDeployerRole, "NOT_AUTHORIZED_DEPLOYER");
// Sanity
require(address(_factoryToImportFrom) != address(this), "INVALID_FACTORY");
require(
_factoryToImportFrom.registry() == registry,
"INVALID_FACTORY_REGISTRY"
);
address[] memory assetsToImport = _factoryToImportFrom
.getAllAssetsWithEngineChip();
for (uint256 i = 0; i < assetsToImport.length; i++) {
address asset = assetsToImport[i];
address engineChip = _factoryToImportFrom.engineChipForAsset(asset);
require(
engineChipForAsset[asset] == address(0),
"ALREADY_DEPLOYED_FOR_TOKEN"
);
require(
deployedEngineChips[engineChip] == false,
"ALREADY_DEPLOYED_FOR_TOKEN"
);
engineChipForAsset[asset] = engineChip;
deployedEngineChips[engineChip] = true;
allAssetsWithEngineChip.push(asset);
emit ImportedEngineChipForAsset(asset, msg.sender, engineChip);
}
}
function importOFTChipsFromChipsFactory(
ChipsFactory _factoryToImportFrom
) public {
address chipsDeployerRole = IRegistryV1(registry).getDynamicRoleAddress(
CHIPS_DEPLOYER_ROLE_KEY
);
require(msg.sender == chipsDeployerRole, "NOT_AUTHORIZED_DEPLOYER");
// Sanity
require(address(_factoryToImportFrom) != address(this), "INVALID_FACTORY");
require(
_factoryToImportFrom.registry() == registry,
"INVALID_FACTORY_REGISTRY"
);
string[] memory symbolsToImport = _factoryToImportFrom
.getAllSymbolsWithOFTChip();
for (uint256 i = 0; i < symbolsToImport.length; i++) {
string memory symbol = symbolsToImport[i];
address oftChip = _factoryToImportFrom.oftChipForSymbol(symbol);
require(
oftChipForSymbol[symbol] == address(0),
"ALREADY_DEPLOYED_FOR_TOKEN"
);
require(deployedOFTChips[oftChip] == false, "ALREADY_DEPLOYED_FOR_TOKEN");
oftChipForSymbol[symbol] = oftChip;
deployedOFTChips[oftChip] = true;
allSymbolsWithOFTChip.push(symbol);
emit ImportedOFTChipForSymbol(symbol, msg.sender, oftChip);
}
}
function setEngineChipForAsset(address _asset, address _engineChip) public {
address chipsDeployerRole = IRegistryV1(registry).getDynamicRoleAddress(
CHIPS_DEPLOYER_ROLE_KEY
);
require(msg.sender == chipsDeployerRole, "NOT_AUTHORIZED_DEPLOYER");
// Sanity
require(
engineChipForAsset[_asset] == address(0),
"ALREADY_DEPLOYED_FOR_TOKEN"
);
require(
deployedEngineChips[_engineChip] == false,
"ALREADY_DEPLOYED_FOR_TOKEN"
);
// Store contract
engineChipForAsset[_asset] = _engineChip;
deployedEngineChips[_engineChip] = true;
// Add to all assets array
allAssetsWithEngineChip.push(_asset);
emit ImportedEngineChipForAsset(_asset, msg.sender, _engineChip);
}
function setOFTChipForSymbol(
string calldata _symbol,
address _oftChip
) public {
address chipsDeployerRole = IRegistryV1(registry).getDynamicRoleAddress(
CHIPS_DEPLOYER_ROLE_KEY
);
require(msg.sender == chipsDeployerRole, "NOT_AUTHORIZED_DEPLOYER");
// Sanity
require(
oftChipForSymbol[_symbol] == address(0),
"ALREADY_DEPLOYED_FOR_TOKEN"
);
require(deployedOFTChips[_oftChip] == false, "ALREADY_DEPLOYED_FOR_TOKEN");
// Store contract
oftChipForSymbol[_symbol] = _oftChip;
deployedOFTChips[_oftChip] = true;
// Add to all symbols array
allSymbolsWithOFTChip.push(_symbol);
emit ImportedOFTChipForSymbol(_symbol, msg.sender, _oftChip);
}
// ***** Deployment functions *****
function deployEngineChipForAsset(
string memory _name,
string memory _symbol,
address _asset,
address _initialAdmin
) public returns (address) {
address chipsDeployerRole = IRegistryV1(registry).getDynamicRoleAddress(
CHIPS_DEPLOYER_ROLE_KEY
);
require(msg.sender == chipsDeployerRole, "NOT_AUTHORIZED_DEPLOYER");
// Sanity
require(
engineChipForAsset[_asset] == address(0),
"ALREADY_DEPLOYED_FOR_ASSET"
);
// Deploy the Engine Chip
address freshEngineChip = EngineChipDeployer(engineChipDeployer)
.deployEngineChip(_name, _symbol, _asset, _initialAdmin);
// Store contract
engineChipForAsset[_asset] = freshEngineChip;
deployedEngineChips[freshEngineChip] = true;
// Add to all assets array
allAssetsWithEngineChip.push(_asset);
// Emit event
emit EngineChipDeployed(_asset, msg.sender, freshEngineChip, _symbol);
return freshEngineChip;
}
function deployOFTChipForSymbol(
string memory _name,
string memory _symbol,
address _lzEndpoint,
address _delegate,
address _initialOwner
) public returns (address) {
address chipsDeployerRole = IRegistryV1(registry).getDynamicRoleAddress(
CHIPS_DEPLOYER_ROLE_KEY
);
require(msg.sender == chipsDeployerRole, "NOT_AUTHORIZED_DEPLOYER");
// Sanity
require(
oftChipForSymbol[_symbol] == address(0),
"ALREADY_DEPLOYED_FOR_ASSET"
);
// Deploy the OFT Chip
address freshOFTChip = OFTChipDeployer(oftChipDeployer).deployOFTChip(
_name,
_symbol,
_lzEndpoint,
_delegate,
_initialOwner
);
// Store contract
oftChipForSymbol[_symbol] = freshOFTChip;
deployedOFTChips[freshOFTChip] = true;
// Add to all symbols array
allSymbolsWithOFTChip.push(_symbol);
// Emit event
emit OFTChipDeployed(_symbol, msg.sender, freshOFTChip);
return freshOFTChip;
}
// ***** Utils *****
/**
* @notice validates the deployer contract is the one we expect
*/
function validateProxyDeployerContract(
address _deployerContract,
string memory expectedName
) internal view {
// Sanity -- Ensure the deployer deploys what we expect
string memory deployedContractName = SingleContractDeployerBase(
_deployerContract
).DEPLOYED_CONTRACT_NAME();
require(
compareStrings(deployedContractName, expectedName),
"WRONG_DEPLOYER_CONTRACT"
);
}
/**
* @notice Util function for string comparison
*/
function compareStrings(
string memory a,
string memory b
) public pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import {IRegistryV1} from "../../interfaces/IRegistryV1.sol";
import {ILynxVersionedContract} from "../../interfaces/ILynxVersionedContract.sol";
import {RegistryBasedProxySingleContractDeployer} from "../deployers/registryBasedProxies/RegistryBasedProxySingleContractDeployer.sol";
contract LexProxiesFactory is ILynxVersionedContract {
// ***** Events *****
event ApprovedCallerSet(address indexed caller, bool indexed isApproved);
event LexProxyContractsDeployed(
address indexed asset,
address indexed caller,
address lexPoolProxy,
address poolAccountantProxy
);
// ***** Structs *****
struct LexProxyContractsStruct {
address lexPoolProxy;
address poolAccountantProxy;
}
// ***** Constants (ILynxVersionedContract interface) *****
string public constant CONTRACT_NAME = "LexProxiesFactory";
string public constant CONTRACT_VERSION = "100"; // 0.10
// ***** Immutable *****
string public constant LEX_PROXIES_DEPLOYER_ROLE_KEY =
"LEX_PROXIES_DEPLOYER_ROLE";
/**
* @notice System Registry
*/
address public immutable registry;
address public immutable lexPoolProxyDeployer;
address public immutable poolAccountantProxyDeployer;
// ***** Storage *****
mapping(address => LexProxyContractsStruct) public lexContractsForAsset;
address[] public allAssetsDeployedFor;
// ***** Views (ILynxVersionedContract interface) *****
function getContractName() external pure override returns (string memory) {
return CONTRACT_NAME;
}
function getContractVersion() external pure override returns (string memory) {
return CONTRACT_VERSION;
}
// ***** Views *****
function getLexProxyContractsForChip(
address _asset
) public view returns (LexProxyContractsStruct memory) {
return lexContractsForAsset[_asset];
}
function getAllAssetsDeployedFor() public view returns (address[] memory) {
return allAssetsDeployedFor;
}
// ***** Constructor *****
constructor(
address _registry,
address _lexPoolProxyDeployer,
address _poolAccountantProxyDeployer
) {
// Sanity
validateProxyDeployerContract(
_registry,
_lexPoolProxyDeployer,
"LexPoolProxy"
);
validateProxyDeployerContract(
_registry,
_poolAccountantProxyDeployer,
"PoolAccountantProxy"
);
// Immutables
registry = _registry;
lexPoolProxyDeployer = _lexPoolProxyDeployer;
poolAccountantProxyDeployer = _poolAccountantProxyDeployer;
}
// ***** Deployment functions *****
function deployLexProxiesForAsset(
address _asset,
address _initialAdmin
) public returns (LexProxyContractsStruct memory) {
address lexProxiedDeployerRole = IRegistryV1(registry)
.getDynamicRoleAddress(LEX_PROXIES_DEPLOYER_ROLE_KEY);
require(msg.sender == lexProxiedDeployerRole, "NOT_AUTHORIZED_DEPLOYER");
// Sanity
require(
lexContractsForAsset[_asset].lexPoolProxy == address(0),
"ALREADY_DEPLOYED_FOR_ASSET"
);
// Deploy the Lex Proxies
address freshLexPoolProxy = RegistryBasedProxySingleContractDeployer(
lexPoolProxyDeployer
).deployRegistryProxy(_initialAdmin);
address freshPoolAccountantProxy = RegistryBasedProxySingleContractDeployer(
poolAccountantProxyDeployer
).deployRegistryProxy(_initialAdmin);
// Store the Lex Proxies
LexProxyContractsStruct memory lexProxies = LexProxyContractsStruct(
freshLexPoolProxy,
freshPoolAccountantProxy
);
lexContractsForAsset[_asset] = lexProxies;
// Add to all assets array
allAssetsDeployedFor.push(_asset);
// Emit event
emit LexProxyContractsDeployed(
_asset,
msg.sender,
freshLexPoolProxy,
freshPoolAccountantProxy
);
return lexProxies;
}
// ***** Utils *****
/**
* @notice validates the deployer contract is the one we expect
*/
function validateProxyDeployerContract(
address _ownRegistry,
address _deployerContract,
string memory expectedName
) internal {
// Sanity -- Ensure the deployer is connected to the same registry
require(
_ownRegistry ==
RegistryBasedProxySingleContractDeployer(_deployerContract).registry(),
"REGISTRY_MISMATCH"
);
// Sanity -- Ensure the deployer deploys what we expect
string
memory deployedContractName = RegistryBasedProxySingleContractDeployer(
_deployerContract
).DEPLOYED_CONTRACT_NAME();
require(
compareStrings(deployedContractName, expectedName),
"WRONG_DEPLOYER_CONTRACT"
);
}
/**
* @notice Util function for string comparison
*/
function compareStrings(
string memory a,
string memory b
) public pure returns (bool) {
return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b));
}
}{
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"evmVersion": "paris",
"metadata": {
"useLiteralContent": true
},
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"anonymous":false,"inputs":[{"indexed":true,"internalType":"string","name":"name","type":"string"},{"indexed":false,"internalType":"address","name":"a","type":"address"}],"name":"AddressUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"asset","type":"address"},{"indexed":true,"internalType":"address","name":"feesManager","type":"address"}],"name":"FeesManagerSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"version","type":"uint256"},{"indexed":true,"internalType":"bytes32","name":"contractNameHash","type":"bytes32"},{"indexed":false,"internalType":"address","name":"contractImplementation","type":"address"}],"name":"NewVersionPublished","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tradingFloor","type":"address"},{"indexed":true,"internalType":"address","name":"settlementAsset","type":"address"},{"indexed":true,"internalType":"address","name":"lexPool","type":"address"},{"indexed":false,"internalType":"address","name":"poolAccountant","type":"address"}],"name":"SettlementAssetForTradingFloorAdded","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"tradingFloor","type":"address"}],"name":"TradingFloorSupported","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"chip","type":"address"},{"indexed":true,"internalType":"address","name":"burnHandler","type":"address"}],"name":"ValidChipBurnHandlerSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"chip","type":"address"},{"indexed":true,"internalType":"string","name":"role","type":"string"},{"indexed":true,"internalType":"address","name":"spender","type":"address"}],"name":"ValidChipSpenderTargetByRoleSet","type":"event"},{"inputs":[],"name":"CONTRACT_NAME","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"CONTRACT_VERSION","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"VERSION_SCALE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"contract RegistryProxy","name":"registryProxy","type":"address"}],"name":"_become","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tradingFloor","type":"address"},{"internalType":"address","name":"_lexPool","type":"address"}],"name":"addNewSettlementAssetInTradingFloor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"admin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"chipsFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"chipsIntentsVerifier","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"dynamicRoleAddresses","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"feesManagers","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"freeLock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getAllSupportedTradingFloors","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getContractName","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"getContractVersion","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"pure","type":"function"},{"inputs":[{"internalType":"string","name":"_role","type":"string"}],"name":"getDynamicRoleAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"proxyNameHash","type":"bytes32"}],"name":"getLatestImplementationForProxyByHash","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"string","name":"proxyName","type":"string"}],"name":"getLatestImplementationForProxyByName","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tradingFloor","type":"address"}],"name":"getSettlementAssetsForTradingFloor","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"chip","type":"address"},{"internalType":"string","name":"role","type":"string"}],"name":"getValidSpenderTargetForChipByRole","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"implementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"},{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"implementations","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"proxyNameHash","type":"bytes32"},{"internalType":"address","name":"_implementation","type":"address"}],"name":"isImplementationValidForProxy","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"}],"name":"isTradersPortalAndLocker","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"}],"name":"isTradersPortalOrTriggersAndLocker","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isTradingFloorSupported","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_address","type":"address"}],"name":"isTriggersAndLocker","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"latestVersions","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lexProxiesFactory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"liquidityIntentsVerifier","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"orderBook","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingImplementation","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"versionToPublish","type":"uint256"},{"internalType":"bytes32[]","name":"contractNameHashes","type":"bytes32[]"},{"internalType":"address[]","name":"contractImplementations","type":"address[]"}],"name":"publishNewSystemVersionBatch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"versionToPublish","type":"uint256"},{"internalType":"bytes32","name":"contractNameHash","type":"bytes32"},{"internalType":"address","name":"contractImplementation","type":"address"}],"name":"publishNewSystemVersionSingle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_chipsFactory","type":"address"}],"name":"setChipsFactory","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_chipsIntentsVerifier","type":"address"}],"name":"setChipsIntentsVerifier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_role","type":"string"},{"internalType":"address","name":"_address","type":"address"}],"name":"setDynamicRoleAddress","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"asset","type":"address"},{"internalType":"address","name":"feesManager","type":"address"}],"name":"setFeesManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_lexProxiesFactory","type":"address"}],"name":"setLexProxiesFactory","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_liquidityIntentsVerifier","type":"address"}],"name":"setLiquidityIntentsVerifier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_orderBook","type":"address"}],"name":"setOrderBook","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tradeIntentsVerifier","type":"address"}],"name":"setTradeIntentsVerifier","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_tradersPortal","type":"address"}],"name":"setTradersPortal","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_triggers","type":"address"}],"name":"setTriggers","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"chip","type":"address"},{"internalType":"address","name":"burnHandler","type":"address"}],"name":"setValidChipBurnHandler","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"chip","type":"address"},{"internalType":"string","name":"role","type":"string"},{"internalType":"address","name":"spender","type":"address"}],"name":"setValidChipSpenderTargetByRole","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"settlementAssetsForTradingFloor","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"_tradingFloor","type":"address"}],"name":"supportTradingFloor","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"supportedTradingFloors","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"systemLockOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tradeIntentsVerifier","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"tradersPortal","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"triggers","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"validBurnHandlerForChip","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"validSpenderTargetForChipByRole","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"validSystemLockOwners","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"}]Contract Creation Code
608060405234801561001057600080fd5b50600080546001600160a01b03191633179055612597806100326000396000f3fe608060405234801561001057600080fd5b50600436106103835760003560e01c80636fad7860116101de578063aa3e63591161010f578063d466a021116100ad578063f5f5ba721161007c578063f5f5ba7214610894578063f83d08ba146108b8578063f851a440146108c0578063fab33704146108d357600080fd5b8063d466a02114610828578063e1f234511461083b578063f4865dd51461084e578063f5adc4fd1461087157600080fd5b8063b49198b3116100e9578063b49198b3146107e6578063c0e636b2146107ef578063c62777c514610802578063c73704dc1461081557600080fd5b8063aa3e63591461078c578063ad0a930d146107c0578063adb22590146107d357600080fd5b806393a5dd1b1161017c578063a2b9cedd11610156578063a2b9cedd1461072a578063a5a2ed371461073d578063a8487bcf14610750578063a8e36e5b1461076357600080fd5b806393a5dd1b146106db5780639a1598c8146106ee5780639c9f88651461070157600080fd5b8063776af5ba116101b8578063776af5ba146106825780637896f649146106955780637bbb19dc146106a85780638aa10435146106bb57600080fd5b80636fad786014610649578063731aa5f91461065c578063760ef0721461066f57600080fd5b806338b90333116102b857806358ca59ce11610256578063614d08f811610230578063614d08f8146105ce578063631e6d38146105f557806367e6508114610608578063695660aa1461063657600080fd5b806358ca59ce146105955780635c60da1b146105a85780635cecd5ff146105bb57600080fd5b8063419a519311610292578063419a51931461053e5780634971e256146105515780634e24b565146105645780635029a8e61461056c57600080fd5b806338b90333146104f3578063396f7b231461052357806340da020f1461053657600080fd5b8063267822471161032557806333829b66116102ff57806333829b66146104a75780633397432b146104ba57806333e1354d146104cd578063372e2470146104e057600080fd5b8063267822471461046e57806327c7ff291461048157806330fbdfe11461049457600080fd5b80631d504dc6116103615780631d504dc6146104125780631e586943146104255780631eb405781461044857806323cb030e1461045b57600080fd5b80630764ca6a14610388578063166b97541461039d5780631a254268146103c6575b600080fd5b61039b610396366004612054565b6108e6565b005b6103b06103ab3660046120e3565b6109cd565b6040516103bd9190612107565b60405180910390f35b6103fa6103d4366004612154565b60136020908152600092835260408084209091529082529020546001600160a01b031681565b6040516001600160a01b0390911681526020016103bd565b61039b6104203660046120e3565b610a43565b610438610433366004612180565b610b91565b60405190151581526020016103bd565b61039b6104563660046120e3565b610bfb565b6103fa610469366004612154565b610c7e565b6001546103fa906001600160a01b031681565b61039b61048f3660046121b0565b610cb6565b61039b6104a23660046120e3565b611290565b61039b6104b53660046121b0565b611318565b6016546103fa906001600160a01b031681565b6103fa6104db3660046121de565b611350565b6010546103fa906001600160a01b031681565b610516604051806040016040528060048152602001630313031360e41b81525081565b6040516103bd919061221b565b6003546103fa906001600160a01b031681565b61039b611361565b61043861054c3660046120e3565b6113ba565b6103fa61055f366004612290565b611401565b6103b0611459565b6103fa61057a3660046120e3565b6014602052600090815260409020546001600160a01b031681565b6103fa6105a33660046122e5565b6114bb565b6002546103fa906001600160a01b031681565b6011546103fa906001600160a01b031681565b61051660405180604001604052806008815260200167526567697374727960c01b81525081565b61039b610603366004612327565b611507565b6106286106163660046121de565b60066020526000908152604090205481565b6040519081526020016103bd565b6015546103fa906001600160a01b031681565b61039b6106573660046120e3565b611541565b61043861066a3660046120e3565b6115e5565b61039b61067d366004612360565b611615565b600d546103fa906001600160a01b031681565b6103fa6106a33660046122e5565b611687565b600f546103fa906001600160a01b031681565b6040805180820190915260048152630313031360e41b6020820152610516565b61039b6106e93660046120e3565b6116c6565b61039b6106fc3660046120e3565b611730565b6103fa61070f3660046121de565b600c602052600090815260409020546001600160a01b031681565b61039b6107383660046120e3565b6117b4565b61043861074b3660046120e3565b611827565b6004546103fa906001600160a01b031681565b6103fa6107713660046120e3565b600b602052600090815260409020546001600160a01b031681565b6103fa61079a3660046123c8565b60076020908152600092835260408084209091529082529020546001600160a01b031681565b61039b6107ce3660046123ea565b611857565b61039b6107e13660046120e3565b61192c565b6106286103e881565b6103fa6107fd3660046121de565b6119e2565b6012546103fa906001600160a01b031681565b61039b6108233660046120e3565b611a0c565b61039b6108363660046120e3565b611a73565b61039b6108493660046121b0565b611add565b61043861085c3660046120e3565b60056020526000908152604090205460ff1681565b61043861087f3660046120e3565b60086020526000908152604090205460ff1681565b604080518082019091526008815267526567697374727960c01b6020820152610516565b61039b611b5e565b6000546103fa906001600160a01b031681565b600e546103fa906001600160a01b031681565b6000546001600160a01b031633146109195760405162461bcd60e51b815260040161091090612436565b60405180910390fd5b82811461095d5760405162461bcd60e51b8152602060048201526012602482015271417272617973206d75737420626520313a3160701b6044820152606401610910565b60005b838110156109c557600085858381811061097c5761097c61245a565b90506020020135905060008484848181106109995761099961245a565b90506020020160208101906109ae91906120e3565b90506109bb888383611c09565b5050600101610960565b505050505050565b6001600160a01b0381166000908152600a6020908152604091829020805483518184028101840190945280845260609392830182828015610a3757602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610a19575b50505050509050919050565b806001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a81573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aa59190612470565b6001600160a01b0316336001600160a01b031614610af45760405162461bcd60e51b815260206004820152600c60248201526b10b83937bc3c9730b236b4b760a11b6044820152606401610910565b806001600160a01b031663c1e803346040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610b34573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b58919061248d565b15610b8e5760405162461bcd60e51b81526004016109109060208082526004908201526319985a5b60e21b604082015260600190565b50565b60006001600160a01b038216610bd85760405162461bcd60e51b815260206004820152600c60248201526b5a45524f5f4144445245535360a01b6044820152606401610910565b6000610be384611d30565b6001600160a01b039081169084161491505092915050565b6000546001600160a01b03163314610c255760405162461bcd60e51b815260040161091090612436565b600f54604080518082019091526008815267747269676765727360c01b6020820152610c5c916001600160a01b0316908390611d5f565b600f80546001600160a01b0319166001600160a01b0392909216919091179055565b600a6020528160005260406000208181548110610c9a57600080fd5b6000918252602090912001546001600160a01b03169150829050565b6001600160a01b03821615801590610cd657506001600160a01b03811615155b610d1b5760405162461bcd60e51b815260206004820152601660248201527543414e4e4f545f42455f5a45524f5f4144445245535360501b6044820152606401610910565b6001600160a01b03821660009081526008602052604090205460ff16610d835760405162461bcd60e51b815260206004820152601960248201527f554e535550504f525445445f54524144494e475f464c4f4f52000000000000006044820152606401610910565b6000816001600160a01b031663c12d636b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610dc3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610de79190612470565b90506000826001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e29573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e4d9190612470565b9050826001600160a01b0316826001600160a01b031663fb56c48f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e97573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ebb9190612470565b6001600160a01b031614610f055760405162461bcd60e51b81526020600482015260116024820152700988ab0bea09e9e98be9a92a69a82a8869607b1b6044820152606401610910565b60155460405162dd699960e71b81526001600160a01b0383811660048301526000921690636eb4cc80906024016040805180830381865afa158015610f4e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f7291906124a6565b9050836001600160a01b031681600001516001600160a01b031614610fd15760405162461bcd60e51b815260206004820152601560248201527415539055551213d49256915117d3115617d413d3d3605a1b6044820152606401610910565b826001600160a01b031681602001516001600160a01b0316146110365760405162461bcd60e51b815260206004820152601c60248201527f554e415554484f52495a45445f504f4f4c5f4143434f554e54414e54000000006044820152606401610910565b60165460405163581a7f5760e11b81526001600160a01b0384811660048301529091169063b034feae90602401602060405180830381865afa158015611080573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110a49190612513565b6110e45760405162461bcd60e51b81526020600482015260116024820152700554e415554484f52495a45445f4348495607c1b6044820152606401610910565b6001600160a01b0384811660008181526005602090815260408083208054600160ff1990911681179091558a8616808552600a84528285208054928301815585529290932090920180546001600160a01b03191687861690811790915591516351512f5360e11b81526004810192909252602482019290925291851660448301529063a2a25ea690606401600060405180830381600087803b15801561118957600080fd5b505af115801561119d573d6000803e3d6000fd5b505060408051808201909152600c81526b2a3930b234b733a33637b7b960a11b602082015291506111d19050838288611e3b565b60408051808201909152600781526613195e141bdbdb60ca1b60208201526111fa848288611e3b565b60408051808201909152601481527321b434b839a4b73a32b73a39ab32b934b334b2b960611b602082015260125461123e90869083906001600160a01b0316611e3b565b6040516001600160a01b03878116825280891691878216918b16907f581507277f7df160915f5a3857d9fdc98501391a22f7ae91519dadce96ea67199060200160405180910390a45050505050505050565b6000546001600160a01b031633146112ba5760405162461bcd60e51b815260040161091090612436565b600e5460408051808201909152600d81526c1d1c9859195c9cd41bdc9d185b609a1b60208201526112f6916001600160a01b0316908390611d5f565b600e80546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b031633146113425760405162461bcd60e51b815260040161091090612436565b61134c8282611f55565b5050565b600061135b82611d30565b92915050565b6004546001600160a01b031633146113a85760405162461bcd60e51b815260206004820152600a60248201526910a637b1b5a7bbb732b960b11b6044820152606401610910565b600480546001600160a01b0319169055565b6004546000906001600160a01b03838116911614801561135b5750600e546001600160a01b038381169116148061135b575050600f546001600160a01b0390811691161490565b6000808383604051602001611417929190612535565b60408051808303601f1901815291815281516020928301206001600160a01b039788166000908152601384528281209181529252902054909416949350505050565b606060098054806020026020016040519081016040528092919081815260200182805480156114b157602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311611493575b5050505050905090565b60008083836040516020016114d1929190612535565b60408051808303601f1901815291815281516020928301206000908152600c9092529020546001600160a01b0316949350505050565b6000546001600160a01b031633146115315760405162461bcd60e51b815260040161091090612436565b61153c838383611c09565b505050565b6000546001600160a01b0316331461156b5760405162461bcd60e51b815260040161091090612436565b601680546001600160a01b0319166001600160a01b0383161790556040516b6368697073466163746f727960a01b8152600c015b6040519081900381206001600160a01b0383168252907f943e9d45a11aaae5d87503e3bc248665d9807856e5cf2bdb4a988bee444227819060200160405180910390a250565b6004546000906001600160a01b03838116911614801561135b575050600e546001600160a01b0390811691161490565b6000546001600160a01b0316331461163f5760405162461bcd60e51b815260040161091090612436565b6116818484848080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250869250611e3b915050565b50505050565b600080838360405160200161169d929190612535565b6040516020818303038152906040528051906020012090506116be81611d30565b949350505050565b6000546001600160a01b031633146116f05760405162461bcd60e51b815260040161091090612436565b601080546001600160a01b0319166001600160a01b038316179055604051733a3930b232a4b73a32b73a39ab32b934b334b2b960611b815260140161159f565b6000546001600160a01b0316331461175a5760405162461bcd60e51b815260040161091090612436565b600d546040805180820190915260098152686f72646572426f6f6b60b81b6020820152611792916001600160a01b0316908390611d5f565b600d80546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b031633146117de5760405162461bcd60e51b815260040161091090612436565b601180546001600160a01b0319166001600160a01b0383161790556040517f6c6971756964697479496e74656e747356657269666965720000000000000000815260180161159f565b6004546000906001600160a01b03838116911614801561135b575050600f546001600160a01b0390811691161490565b6000546001600160a01b031633146118815760405162461bcd60e51b815260040161091090612436565b60008383604051602001611896929190612535565b60408051808303601f1901815282825280516020918201206000818152600c90925291902080546001600160a01b0319166001600160a01b03861617905591506118e39085908590612535565b6040519081900381206001600160a01b0384168252907f943e9d45a11aaae5d87503e3bc248665d9807856e5cf2bdb4a988bee444227819060200160405180910390a250505050565b6000546001600160a01b031633146119565760405162461bcd60e51b815260040161091090612436565b6001600160a01b038116600081815260086020526040808220805460ff1916600190811790915560098054918201815583527f6e1540171b6c0c960b71a7020d9f60077f6af931a8bbf590da0223dacf75c7af0180546001600160a01b03191684179055517fc3b56cad40fff5fd7c2e07c16488355f4e10397fbd438c5125a005c40f4e29f19190a250565b600981815481106119f257600080fd5b6000918252602090912001546001600160a01b0316905081565b6000546001600160a01b03163314611a365760405162461bcd60e51b815260040161091090612436565b601580546001600160a01b0319166001600160a01b038316179055604051706c657850726f78696573466163746f727960781b815260110161159f565b6000546001600160a01b03163314611a9d5760405162461bcd60e51b815260040161091090612436565b601280546001600160a01b0319166001600160a01b0383161790556040517331b434b839a4b73a32b73a39ab32b934b334b2b960611b815260140161159f565b6000546001600160a01b03163314611b075760405162461bcd60e51b815260040161091090612436565b6001600160a01b038281166000818152600b602052604080822080546001600160a01b0319169486169485179055517f3c294129903f90afbea58693e1e9c725db2f87ba64e5bed851716d1f3dc610139190a35050565b3360009081526005602052604090205460ff16611bac5760405162461bcd60e51b815260206004820152600c60248201526b10ab30b634b22637b1b5b2b960a11b6044820152606401610910565b6004546001600160a01b031615611bf55760405162461bcd60e51b815260206004820152600d60248201526c105b1c9958591e531bd8dad959609a1b6044820152606401610910565b600480546001600160a01b03191633179055565b600082815260066020526040902054808411611c675760405162461bcd60e51b815260206004820152601a60248201527f4d5553545f5055424c4953485f4e455745525f56455253494f4e0000000000006044820152606401610910565b6001600160a01b038216611cb35760405162461bcd60e51b8152602060048201526013602482015272494d504c454d454e544154494f4e5f5a45524f60681b6044820152606401610910565b60008381526006602090815260408083208790558683526007825280832086845282529182902080546001600160a01b0319166001600160a01b0386169081179091559151918252849186917fe6552da0d01ff56e28f4d0984a3ea0abcaec0a419b7d3057aa687ed889887b13910160405180910390a350505050565b60008181526006602090815260408083205483526007825280832093835292905220546001600160a01b031690565b6001600160a01b038216611dae5760405162461bcd60e51b815260206004820152601660248201527543414e4e4f545f42455f5a45524f5f4144445245535360501b6044820152606401610910565b6001600160a01b03808416600090815260056020526040808220805460ff19908116909155928516825290819020805490921660011790915551611df3908290612545565b6040519081900381206001600160a01b0384168252907f943e9d45a11aaae5d87503e3bc248665d9807856e5cf2bdb4a988bee444227819060200160405180910390a2505050565b600082604051602001611e4e9190612545565b60408051601f1981840301815291815281516020928301206001600160a01b0380881660009081526013855283812083825290945291909220549192509081169083168103611ecd5760405162461bcd60e51b815260206004820152600b60248201526a1053149150511657d4d15560aa1b6044820152606401610910565b6001600160a01b0385811660009081526013602090815260408083208684529091529081902080546001600160a01b031916928616928317905551611f13908690612545565b604051908190038120906001600160a01b038816907fa1d0356cb207c7aad424409734a64fbf1dc258e464dca16730dea8b3f41ce0e790600090a45050505050565b6001600160a01b0380831660009081526014602052604090205481169082168103611fb05760405162461bcd60e51b815260206004820152600b60248201526a1053149150511657d4d15560aa1b6044820152606401610910565b6001600160a01b0383811660008181526014602052604080822080546001600160a01b0319169487169485179055517f8772fee7946b5f02fdba3ae14b5fda258b239f97d8c7cf8a53689519fa2f5ef49190a3505050565b60008083601f84011261201a57600080fd5b50813567ffffffffffffffff81111561203257600080fd5b6020830191508360208260051b850101111561204d57600080fd5b9250929050565b60008060008060006060868803121561206c57600080fd5b85359450602086013567ffffffffffffffff8082111561208b57600080fd5b61209789838a01612008565b909650945060408801359150808211156120b057600080fd5b506120bd88828901612008565b969995985093965092949392505050565b6001600160a01b0381168114610b8e57600080fd5b6000602082840312156120f557600080fd5b8135612100816120ce565b9392505050565b6020808252825182820181905260009190848201906040850190845b818110156121485783516001600160a01b031683529284019291840191600101612123565b50909695505050505050565b6000806040838503121561216757600080fd5b8235612172816120ce565b946020939093013593505050565b6000806040838503121561219357600080fd5b8235915060208301356121a5816120ce565b809150509250929050565b600080604083850312156121c357600080fd5b82356121ce816120ce565b915060208301356121a5816120ce565b6000602082840312156121f057600080fd5b5035919050565b60005b838110156122125781810151838201526020016121fa565b50506000910152565b602081526000825180602084015261223a8160408501602087016121f7565b601f01601f19169190910160400192915050565b60008083601f84011261226057600080fd5b50813567ffffffffffffffff81111561227857600080fd5b60208301915083602082850101111561204d57600080fd5b6000806000604084860312156122a557600080fd5b83356122b0816120ce565b9250602084013567ffffffffffffffff8111156122cc57600080fd5b6122d88682870161224e565b9497909650939450505050565b600080602083850312156122f857600080fd5b823567ffffffffffffffff81111561230f57600080fd5b61231b8582860161224e565b90969095509350505050565b60008060006060848603121561233c57600080fd5b83359250602084013591506040840135612355816120ce565b809150509250925092565b6000806000806060858703121561237657600080fd5b8435612381816120ce565b9350602085013567ffffffffffffffff81111561239d57600080fd5b6123a98782880161224e565b90945092505060408501356123bd816120ce565b939692955090935050565b600080604083850312156123db57600080fd5b50508035926020909101359150565b6000806000604084860312156123ff57600080fd5b833567ffffffffffffffff81111561241657600080fd5b6124228682870161224e565b9094509250506020840135612355816120ce565b6020808252600a908201526927a7262cafa0a226a4a760b11b604082015260600190565b634e487b7160e01b600052603260045260246000fd5b60006020828403121561248257600080fd5b8151612100816120ce565b60006020828403121561249f57600080fd5b5051919050565b6000604082840312156124b857600080fd5b6040516040810181811067ffffffffffffffff821117156124e957634e487b7160e01b600052604160045260246000fd5b60405282516124f7816120ce565b81526020830151612507816120ce565b60208201529392505050565b60006020828403121561252557600080fd5b8151801515811461210057600080fd5b8183823760009101908152919050565b600082516125578184602087016121f7565b919091019291505056fea2646970667358221220ef505f82e2f4620a1a7ed129ed59e5131fb4d7550b41ee13b0f29817acef5e8364736f6c63430008180033
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106103835760003560e01c80636fad7860116101de578063aa3e63591161010f578063d466a021116100ad578063f5f5ba721161007c578063f5f5ba7214610894578063f83d08ba146108b8578063f851a440146108c0578063fab33704146108d357600080fd5b8063d466a02114610828578063e1f234511461083b578063f4865dd51461084e578063f5adc4fd1461087157600080fd5b8063b49198b3116100e9578063b49198b3146107e6578063c0e636b2146107ef578063c62777c514610802578063c73704dc1461081557600080fd5b8063aa3e63591461078c578063ad0a930d146107c0578063adb22590146107d357600080fd5b806393a5dd1b1161017c578063a2b9cedd11610156578063a2b9cedd1461072a578063a5a2ed371461073d578063a8487bcf14610750578063a8e36e5b1461076357600080fd5b806393a5dd1b146106db5780639a1598c8146106ee5780639c9f88651461070157600080fd5b8063776af5ba116101b8578063776af5ba146106825780637896f649146106955780637bbb19dc146106a85780638aa10435146106bb57600080fd5b80636fad786014610649578063731aa5f91461065c578063760ef0721461066f57600080fd5b806338b90333116102b857806358ca59ce11610256578063614d08f811610230578063614d08f8146105ce578063631e6d38146105f557806367e6508114610608578063695660aa1461063657600080fd5b806358ca59ce146105955780635c60da1b146105a85780635cecd5ff146105bb57600080fd5b8063419a519311610292578063419a51931461053e5780634971e256146105515780634e24b565146105645780635029a8e61461056c57600080fd5b806338b90333146104f3578063396f7b231461052357806340da020f1461053657600080fd5b8063267822471161032557806333829b66116102ff57806333829b66146104a75780633397432b146104ba57806333e1354d146104cd578063372e2470146104e057600080fd5b8063267822471461046e57806327c7ff291461048157806330fbdfe11461049457600080fd5b80631d504dc6116103615780631d504dc6146104125780631e586943146104255780631eb405781461044857806323cb030e1461045b57600080fd5b80630764ca6a14610388578063166b97541461039d5780631a254268146103c6575b600080fd5b61039b610396366004612054565b6108e6565b005b6103b06103ab3660046120e3565b6109cd565b6040516103bd9190612107565b60405180910390f35b6103fa6103d4366004612154565b60136020908152600092835260408084209091529082529020546001600160a01b031681565b6040516001600160a01b0390911681526020016103bd565b61039b6104203660046120e3565b610a43565b610438610433366004612180565b610b91565b60405190151581526020016103bd565b61039b6104563660046120e3565b610bfb565b6103fa610469366004612154565b610c7e565b6001546103fa906001600160a01b031681565b61039b61048f3660046121b0565b610cb6565b61039b6104a23660046120e3565b611290565b61039b6104b53660046121b0565b611318565b6016546103fa906001600160a01b031681565b6103fa6104db3660046121de565b611350565b6010546103fa906001600160a01b031681565b610516604051806040016040528060048152602001630313031360e41b81525081565b6040516103bd919061221b565b6003546103fa906001600160a01b031681565b61039b611361565b61043861054c3660046120e3565b6113ba565b6103fa61055f366004612290565b611401565b6103b0611459565b6103fa61057a3660046120e3565b6014602052600090815260409020546001600160a01b031681565b6103fa6105a33660046122e5565b6114bb565b6002546103fa906001600160a01b031681565b6011546103fa906001600160a01b031681565b61051660405180604001604052806008815260200167526567697374727960c01b81525081565b61039b610603366004612327565b611507565b6106286106163660046121de565b60066020526000908152604090205481565b6040519081526020016103bd565b6015546103fa906001600160a01b031681565b61039b6106573660046120e3565b611541565b61043861066a3660046120e3565b6115e5565b61039b61067d366004612360565b611615565b600d546103fa906001600160a01b031681565b6103fa6106a33660046122e5565b611687565b600f546103fa906001600160a01b031681565b6040805180820190915260048152630313031360e41b6020820152610516565b61039b6106e93660046120e3565b6116c6565b61039b6106fc3660046120e3565b611730565b6103fa61070f3660046121de565b600c602052600090815260409020546001600160a01b031681565b61039b6107383660046120e3565b6117b4565b61043861074b3660046120e3565b611827565b6004546103fa906001600160a01b031681565b6103fa6107713660046120e3565b600b602052600090815260409020546001600160a01b031681565b6103fa61079a3660046123c8565b60076020908152600092835260408084209091529082529020546001600160a01b031681565b61039b6107ce3660046123ea565b611857565b61039b6107e13660046120e3565b61192c565b6106286103e881565b6103fa6107fd3660046121de565b6119e2565b6012546103fa906001600160a01b031681565b61039b6108233660046120e3565b611a0c565b61039b6108363660046120e3565b611a73565b61039b6108493660046121b0565b611add565b61043861085c3660046120e3565b60056020526000908152604090205460ff1681565b61043861087f3660046120e3565b60086020526000908152604090205460ff1681565b604080518082019091526008815267526567697374727960c01b6020820152610516565b61039b611b5e565b6000546103fa906001600160a01b031681565b600e546103fa906001600160a01b031681565b6000546001600160a01b031633146109195760405162461bcd60e51b815260040161091090612436565b60405180910390fd5b82811461095d5760405162461bcd60e51b8152602060048201526012602482015271417272617973206d75737420626520313a3160701b6044820152606401610910565b60005b838110156109c557600085858381811061097c5761097c61245a565b90506020020135905060008484848181106109995761099961245a565b90506020020160208101906109ae91906120e3565b90506109bb888383611c09565b5050600101610960565b505050505050565b6001600160a01b0381166000908152600a6020908152604091829020805483518184028101840190945280845260609392830182828015610a3757602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311610a19575b50505050509050919050565b806001600160a01b031663f851a4406040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a81573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610aa59190612470565b6001600160a01b0316336001600160a01b031614610af45760405162461bcd60e51b815260206004820152600c60248201526b10b83937bc3c9730b236b4b760a11b6044820152606401610910565b806001600160a01b031663c1e803346040518163ffffffff1660e01b81526004016020604051808303816000875af1158015610b34573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b58919061248d565b15610b8e5760405162461bcd60e51b81526004016109109060208082526004908201526319985a5b60e21b604082015260600190565b50565b60006001600160a01b038216610bd85760405162461bcd60e51b815260206004820152600c60248201526b5a45524f5f4144445245535360a01b6044820152606401610910565b6000610be384611d30565b6001600160a01b039081169084161491505092915050565b6000546001600160a01b03163314610c255760405162461bcd60e51b815260040161091090612436565b600f54604080518082019091526008815267747269676765727360c01b6020820152610c5c916001600160a01b0316908390611d5f565b600f80546001600160a01b0319166001600160a01b0392909216919091179055565b600a6020528160005260406000208181548110610c9a57600080fd5b6000918252602090912001546001600160a01b03169150829050565b6001600160a01b03821615801590610cd657506001600160a01b03811615155b610d1b5760405162461bcd60e51b815260206004820152601660248201527543414e4e4f545f42455f5a45524f5f4144445245535360501b6044820152606401610910565b6001600160a01b03821660009081526008602052604090205460ff16610d835760405162461bcd60e51b815260206004820152601960248201527f554e535550504f525445445f54524144494e475f464c4f4f52000000000000006044820152606401610910565b6000816001600160a01b031663c12d636b6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610dc3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610de79190612470565b90506000826001600160a01b0316636f307dc36040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e29573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e4d9190612470565b9050826001600160a01b0316826001600160a01b031663fb56c48f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e97573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ebb9190612470565b6001600160a01b031614610f055760405162461bcd60e51b81526020600482015260116024820152700988ab0bea09e9e98be9a92a69a82a8869607b1b6044820152606401610910565b60155460405162dd699960e71b81526001600160a01b0383811660048301526000921690636eb4cc80906024016040805180830381865afa158015610f4e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f7291906124a6565b9050836001600160a01b031681600001516001600160a01b031614610fd15760405162461bcd60e51b815260206004820152601560248201527415539055551213d49256915117d3115617d413d3d3605a1b6044820152606401610910565b826001600160a01b031681602001516001600160a01b0316146110365760405162461bcd60e51b815260206004820152601c60248201527f554e415554484f52495a45445f504f4f4c5f4143434f554e54414e54000000006044820152606401610910565b60165460405163581a7f5760e11b81526001600160a01b0384811660048301529091169063b034feae90602401602060405180830381865afa158015611080573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110a49190612513565b6110e45760405162461bcd60e51b81526020600482015260116024820152700554e415554484f52495a45445f4348495607c1b6044820152606401610910565b6001600160a01b0384811660008181526005602090815260408083208054600160ff1990911681179091558a8616808552600a84528285208054928301815585529290932090920180546001600160a01b03191687861690811790915591516351512f5360e11b81526004810192909252602482019290925291851660448301529063a2a25ea690606401600060405180830381600087803b15801561118957600080fd5b505af115801561119d573d6000803e3d6000fd5b505060408051808201909152600c81526b2a3930b234b733a33637b7b960a11b602082015291506111d19050838288611e3b565b60408051808201909152600781526613195e141bdbdb60ca1b60208201526111fa848288611e3b565b60408051808201909152601481527321b434b839a4b73a32b73a39ab32b934b334b2b960611b602082015260125461123e90869083906001600160a01b0316611e3b565b6040516001600160a01b03878116825280891691878216918b16907f581507277f7df160915f5a3857d9fdc98501391a22f7ae91519dadce96ea67199060200160405180910390a45050505050505050565b6000546001600160a01b031633146112ba5760405162461bcd60e51b815260040161091090612436565b600e5460408051808201909152600d81526c1d1c9859195c9cd41bdc9d185b609a1b60208201526112f6916001600160a01b0316908390611d5f565b600e80546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b031633146113425760405162461bcd60e51b815260040161091090612436565b61134c8282611f55565b5050565b600061135b82611d30565b92915050565b6004546001600160a01b031633146113a85760405162461bcd60e51b815260206004820152600a60248201526910a637b1b5a7bbb732b960b11b6044820152606401610910565b600480546001600160a01b0319169055565b6004546000906001600160a01b03838116911614801561135b5750600e546001600160a01b038381169116148061135b575050600f546001600160a01b0390811691161490565b6000808383604051602001611417929190612535565b60408051808303601f1901815291815281516020928301206001600160a01b039788166000908152601384528281209181529252902054909416949350505050565b606060098054806020026020016040519081016040528092919081815260200182805480156114b157602002820191906000526020600020905b81546001600160a01b03168152600190910190602001808311611493575b5050505050905090565b60008083836040516020016114d1929190612535565b60408051808303601f1901815291815281516020928301206000908152600c9092529020546001600160a01b0316949350505050565b6000546001600160a01b031633146115315760405162461bcd60e51b815260040161091090612436565b61153c838383611c09565b505050565b6000546001600160a01b0316331461156b5760405162461bcd60e51b815260040161091090612436565b601680546001600160a01b0319166001600160a01b0383161790556040516b6368697073466163746f727960a01b8152600c015b6040519081900381206001600160a01b0383168252907f943e9d45a11aaae5d87503e3bc248665d9807856e5cf2bdb4a988bee444227819060200160405180910390a250565b6004546000906001600160a01b03838116911614801561135b575050600e546001600160a01b0390811691161490565b6000546001600160a01b0316331461163f5760405162461bcd60e51b815260040161091090612436565b6116818484848080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250869250611e3b915050565b50505050565b600080838360405160200161169d929190612535565b6040516020818303038152906040528051906020012090506116be81611d30565b949350505050565b6000546001600160a01b031633146116f05760405162461bcd60e51b815260040161091090612436565b601080546001600160a01b0319166001600160a01b038316179055604051733a3930b232a4b73a32b73a39ab32b934b334b2b960611b815260140161159f565b6000546001600160a01b0316331461175a5760405162461bcd60e51b815260040161091090612436565b600d546040805180820190915260098152686f72646572426f6f6b60b81b6020820152611792916001600160a01b0316908390611d5f565b600d80546001600160a01b0319166001600160a01b0392909216919091179055565b6000546001600160a01b031633146117de5760405162461bcd60e51b815260040161091090612436565b601180546001600160a01b0319166001600160a01b0383161790556040517f6c6971756964697479496e74656e747356657269666965720000000000000000815260180161159f565b6004546000906001600160a01b03838116911614801561135b575050600f546001600160a01b0390811691161490565b6000546001600160a01b031633146118815760405162461bcd60e51b815260040161091090612436565b60008383604051602001611896929190612535565b60408051808303601f1901815282825280516020918201206000818152600c90925291902080546001600160a01b0319166001600160a01b03861617905591506118e39085908590612535565b6040519081900381206001600160a01b0384168252907f943e9d45a11aaae5d87503e3bc248665d9807856e5cf2bdb4a988bee444227819060200160405180910390a250505050565b6000546001600160a01b031633146119565760405162461bcd60e51b815260040161091090612436565b6001600160a01b038116600081815260086020526040808220805460ff1916600190811790915560098054918201815583527f6e1540171b6c0c960b71a7020d9f60077f6af931a8bbf590da0223dacf75c7af0180546001600160a01b03191684179055517fc3b56cad40fff5fd7c2e07c16488355f4e10397fbd438c5125a005c40f4e29f19190a250565b600981815481106119f257600080fd5b6000918252602090912001546001600160a01b0316905081565b6000546001600160a01b03163314611a365760405162461bcd60e51b815260040161091090612436565b601580546001600160a01b0319166001600160a01b038316179055604051706c657850726f78696573466163746f727960781b815260110161159f565b6000546001600160a01b03163314611a9d5760405162461bcd60e51b815260040161091090612436565b601280546001600160a01b0319166001600160a01b0383161790556040517331b434b839a4b73a32b73a39ab32b934b334b2b960611b815260140161159f565b6000546001600160a01b03163314611b075760405162461bcd60e51b815260040161091090612436565b6001600160a01b038281166000818152600b602052604080822080546001600160a01b0319169486169485179055517f3c294129903f90afbea58693e1e9c725db2f87ba64e5bed851716d1f3dc610139190a35050565b3360009081526005602052604090205460ff16611bac5760405162461bcd60e51b815260206004820152600c60248201526b10ab30b634b22637b1b5b2b960a11b6044820152606401610910565b6004546001600160a01b031615611bf55760405162461bcd60e51b815260206004820152600d60248201526c105b1c9958591e531bd8dad959609a1b6044820152606401610910565b600480546001600160a01b03191633179055565b600082815260066020526040902054808411611c675760405162461bcd60e51b815260206004820152601a60248201527f4d5553545f5055424c4953485f4e455745525f56455253494f4e0000000000006044820152606401610910565b6001600160a01b038216611cb35760405162461bcd60e51b8152602060048201526013602482015272494d504c454d454e544154494f4e5f5a45524f60681b6044820152606401610910565b60008381526006602090815260408083208790558683526007825280832086845282529182902080546001600160a01b0319166001600160a01b0386169081179091559151918252849186917fe6552da0d01ff56e28f4d0984a3ea0abcaec0a419b7d3057aa687ed889887b13910160405180910390a350505050565b60008181526006602090815260408083205483526007825280832093835292905220546001600160a01b031690565b6001600160a01b038216611dae5760405162461bcd60e51b815260206004820152601660248201527543414e4e4f545f42455f5a45524f5f4144445245535360501b6044820152606401610910565b6001600160a01b03808416600090815260056020526040808220805460ff19908116909155928516825290819020805490921660011790915551611df3908290612545565b6040519081900381206001600160a01b0384168252907f943e9d45a11aaae5d87503e3bc248665d9807856e5cf2bdb4a988bee444227819060200160405180910390a2505050565b600082604051602001611e4e9190612545565b60408051601f1981840301815291815281516020928301206001600160a01b0380881660009081526013855283812083825290945291909220549192509081169083168103611ecd5760405162461bcd60e51b815260206004820152600b60248201526a1053149150511657d4d15560aa1b6044820152606401610910565b6001600160a01b0385811660009081526013602090815260408083208684529091529081902080546001600160a01b031916928616928317905551611f13908690612545565b604051908190038120906001600160a01b038816907fa1d0356cb207c7aad424409734a64fbf1dc258e464dca16730dea8b3f41ce0e790600090a45050505050565b6001600160a01b0380831660009081526014602052604090205481169082168103611fb05760405162461bcd60e51b815260206004820152600b60248201526a1053149150511657d4d15560aa1b6044820152606401610910565b6001600160a01b0383811660008181526014602052604080822080546001600160a01b0319169487169485179055517f8772fee7946b5f02fdba3ae14b5fda258b239f97d8c7cf8a53689519fa2f5ef49190a3505050565b60008083601f84011261201a57600080fd5b50813567ffffffffffffffff81111561203257600080fd5b6020830191508360208260051b850101111561204d57600080fd5b9250929050565b60008060008060006060868803121561206c57600080fd5b85359450602086013567ffffffffffffffff8082111561208b57600080fd5b61209789838a01612008565b909650945060408801359150808211156120b057600080fd5b506120bd88828901612008565b969995985093965092949392505050565b6001600160a01b0381168114610b8e57600080fd5b6000602082840312156120f557600080fd5b8135612100816120ce565b9392505050565b6020808252825182820181905260009190848201906040850190845b818110156121485783516001600160a01b031683529284019291840191600101612123565b50909695505050505050565b6000806040838503121561216757600080fd5b8235612172816120ce565b946020939093013593505050565b6000806040838503121561219357600080fd5b8235915060208301356121a5816120ce565b809150509250929050565b600080604083850312156121c357600080fd5b82356121ce816120ce565b915060208301356121a5816120ce565b6000602082840312156121f057600080fd5b5035919050565b60005b838110156122125781810151838201526020016121fa565b50506000910152565b602081526000825180602084015261223a8160408501602087016121f7565b601f01601f19169190910160400192915050565b60008083601f84011261226057600080fd5b50813567ffffffffffffffff81111561227857600080fd5b60208301915083602082850101111561204d57600080fd5b6000806000604084860312156122a557600080fd5b83356122b0816120ce565b9250602084013567ffffffffffffffff8111156122cc57600080fd5b6122d88682870161224e565b9497909650939450505050565b600080602083850312156122f857600080fd5b823567ffffffffffffffff81111561230f57600080fd5b61231b8582860161224e565b90969095509350505050565b60008060006060848603121561233c57600080fd5b83359250602084013591506040840135612355816120ce565b809150509250925092565b6000806000806060858703121561237657600080fd5b8435612381816120ce565b9350602085013567ffffffffffffffff81111561239d57600080fd5b6123a98782880161224e565b90945092505060408501356123bd816120ce565b939692955090935050565b600080604083850312156123db57600080fd5b50508035926020909101359150565b6000806000604084860312156123ff57600080fd5b833567ffffffffffffffff81111561241657600080fd5b6124228682870161224e565b9094509250506020840135612355816120ce565b6020808252600a908201526927a7262cafa0a226a4a760b11b604082015260600190565b634e487b7160e01b600052603260045260246000fd5b60006020828403121561248257600080fd5b8151612100816120ce565b60006020828403121561249f57600080fd5b5051919050565b6000604082840312156124b857600080fd5b6040516040810181811067ffffffffffffffff821117156124e957634e487b7160e01b600052604160045260246000fd5b60405282516124f7816120ce565b81526020830151612507816120ce565b60208201529392505050565b60006020828403121561252557600080fd5b8151801515811461210057600080fd5b8183823760009101908152919050565b600082516125578184602087016121f7565b919091019291505056fea2646970667358221220ef505f82e2f4620a1a7ed129ed59e5131fb4d7550b41ee13b0f29817acef5e8364736f6c63430008180033
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in S
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.