Source Code
Overview
S Balance
S Value
Less Than $0.01 (@ $0.07/S)Latest 25 from a total of 14,350 transactions
| Transaction Hash |
|
Block
|
From
|
To
|
|||||
|---|---|---|---|---|---|---|---|---|---|
| Trader Request_o... | 44628156 | 153 days ago | IN | 1 wei | 0.01825343 | ||||
| Trader Request_m... | 44627268 | 153 days ago | IN | 1 wei | 0.00472975 | ||||
| Trader Request_u... | 44627184 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_o... | 44627161 | 153 days ago | IN | 1 wei | 0.01608643 | ||||
| Trader Request_m... | 44626952 | 153 days ago | IN | 1 wei | 0.00472975 | ||||
| Trader Request_u... | 44626879 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_u... | 44626852 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_u... | 44626818 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_u... | 44626761 | 153 days ago | IN | 1 wei | 0.00534536 | ||||
| Trader Request_u... | 44626759 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_o... | 44626725 | 153 days ago | IN | 1 wei | 0.01694658 | ||||
| Trader Request_u... | 44626520 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_u... | 44626482 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_u... | 44626453 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_o... | 44626431 | 153 days ago | IN | 1 wei | 0.01608703 | ||||
| Trader Request_m... | 44626153 | 153 days ago | IN | 1 wei | 0.00472975 | ||||
| Trader Request_u... | 44626011 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_u... | 44625942 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_o... | 44625928 | 153 days ago | IN | 1 wei | 0.01694203 | ||||
| Trader Request_u... | 44625789 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_u... | 44625763 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_o... | 44625746 | 153 days ago | IN | 1 wei | 0.01694658 | ||||
| Trader Request_u... | 44625668 | 153 days ago | IN | 1 wei | 0.00874421 | ||||
| Trader Request_u... | 44625623 | 153 days ago | IN | 1 wei | 0.00874056 | ||||
| Trader Request_o... | 44625600 | 153 days ago | IN | 1 wei | 0.01694658 |
Cross-Chain Transactions
Loading...
Loading
Contract Name:
TradersPortalV1
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/TradingFloorStructsV1.sol";
import "../interfaces/OrderBookStructsV1.sol";
import "../interfaces/IAffiliationV1.sol";
import "../interfaces/ITradersPortalV1.sol";
import "../IntentsVerifier/TradeIntentsVerifierV1.sol";
import "../Locks/SystemLocker.sol";
import "../../AdministrationContracts/ClaimableAdmin.sol";
import "../../Lynx/Triggers/TriggersV1.sol";
import "../../CryptographyContracts/EIP712Utils.sol";
import {ILynxVersionedContract} from "../interfaces/ILynxVersionedContract.sol";
import {IOnBehalfTradingV1 as IOnBehalfTrading} from "../interfaces/IOnBehalfTradingV1.sol";
/**
* @title TradersPortalV1
* @notice This contract is the main entry point for traders to interact with the trading system.
* It allows traders to submit requests to open new trades, update existing trades, and close trades.
* It also enforces fees and time locks for certain actions.
*
* @dev Version History:
* - v1.00 (100): Initial version with core trading functionality
* - v1.01 (1010): Integrated sub-account trading support via OnBehalfTrading contract
* - Added onBehalfActivated mapping for traders to opt-in to sub-account trading
* - Added validatePermissions() internal function to centralize permission checks
* - Modified all position management functions to support sub-account trading:
* - openNewPositionInternal: Charges permission when sub-account opens for owner
* - all other functions : Validates sub-account permissions
*/
contract TradersPortalV1 is
ClaimableAdmin,
SystemLocker,
ITradersPortalV1Functionality,
IAffiliationV1,
ILynxVersionedContract,
CommonScales
{
address public NATIVE_UNDERLYING_ADDRESS =
address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
enum TradersPortalActions {
NONE,
REQUEST_POSITION_OPEN,
REQUEST_POSITION_MARKET_CLOSE,
REQUEST_POSITION_SINGLE_FIELD_UPDATE,
REQUEST_POSITION_DOUBLE_FIELD_UPDATE
}
string public constant DYN_ROLE_ON_BEHALF_TRADING = "ON_BEHALF_TRADING";
// ***** Contracts (Immutable) *****
ITradingFloorV1 public immutable tradingFloor;
IRegistryV1 public immutable registry;
// ***** Constants (ILynxVersionedContract interface) *****
string public constant CONTRACT_NAME = "TradersPortalV1";
string public constant CONTRACT_VERSION = "1010"; // 1.01
// ***** Timeouts Params *****
uint256 public limitOrdersTimelock; // seconds (eg. 30)
uint256 public marketOrdersTimeout; // seconds (eg. 30)
uint256 public minLiveTimeForMarketClose; // seconds (eg. 30)
mapping(TradersPortalActions => uint256) public actionFees;
// ***** Done/Pause State *****
bool public isPaused; // Prevent opening new trades
bool public isDone; // Prevent any interaction with the contract
// ***** State *****
bool public isLimitingMarketClosePriceRange;
// Mapping to track which traders have enabled on-behalf trading
mapping(address => bool) public onBehalfActivated;
// ***** Events *****
event DoneToggled(bool done);
event PausedToggled(bool paused);
event NumberUpdated(string name, uint value);
event IsLimitingMarketClosePriceRangeToggled(bool done);
event ActionFeeSet(TradersPortalActions indexed action, uint256 requiredFee);
event PendingOpenLimitPositionCancelled(bytes32 indexed positionId);
event PendingMarketOpenOrderTimeoutCancelled(
bytes32 indexed positionId,
address indexed caller
);
event PendingMarketCloseOrderTimeoutCancelled(
bytes32 indexed positionId,
address indexed caller
);
event OnBehalfActivatedToggled(address indexed trader, bool enabled);
// ***** Modifiers *****
modifier notContract() {
require(
tx.origin == msg.sender || msg.sender == registry.tradeIntentsVerifier(),
"NOT_CONTRACT"
);
_;
}
modifier notDone() {
require(!isDone, "DONE");
_;
}
modifier notDoneOrPaused() {
require(!isDone, "DONE");
require(!isPaused, "PAUSED");
_;
}
modifier onlyFeesManager() {
require(
msg.sender ==
IRegistryV1(tradingFloor.registry()).feesManagers(
NATIVE_UNDERLYING_ADDRESS
),
"NOT_FEES_MANAGER"
);
_;
}
modifier sentEnoughNativeFee(TradersPortalActions action) {
require(msg.value >= actionFees[action], "NOT_ENOUGH_NATIVE");
_;
}
// ***** 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 getOrderBook() public view returns (IOrderBookV1 orderBook) {
orderBook = IOrderBookV1(TriggersV1(registry.triggers()).orderBook());
}
function getTradeIntentsVerifier()
public
view
returns (address tradeIntentsVerifier)
{
tradeIntentsVerifier = registry.tradeIntentsVerifier();
}
function getOnBehalfTrading() public view returns (address onBehalfTrading) {
onBehalfTrading = registry.getDynamicRoleAddress(
DYN_ROLE_ON_BEHALF_TRADING
);
}
// ***** Constructor *****
constructor(
ITradingFloorV1 _tradingFloor
) SystemLocker(_tradingFloor.registry()) {
require(address(_tradingFloor) != address(0), "WRONG_PARAMS");
tradingFloor = _tradingFloor;
registry = IRegistryV1(_tradingFloor.registry());
}
// ***** Pause/Done (Admin) Toggles *****
function togglePause() external onlyAdmin {
isPaused = !isPaused;
emit PausedToggled(isPaused);
}
function toggleDone() external onlyAdmin {
isDone = !isDone;
emit DoneToggled(isDone);
}
// ***** Admin functions *****
function setLimitOrdersTimelock(uint value) external onlyAdmin {
require(value > 0, "CANNOT_BE_ZERO");
limitOrdersTimelock = value;
emit NumberUpdated("limitOrdersTimelock", value);
}
function setMarketOrdersTimeout(uint value) external onlyAdmin {
require(value > 0, "CANNOT_BE_ZERO");
marketOrdersTimeout = value;
emit NumberUpdated("marketOrdersTimeout", value);
}
function setMinLiveTimeForMarketClose(uint value) external onlyAdmin {
require(value > 0, "CANNOT_BE_ZERO");
minLiveTimeForMarketClose = value;
emit NumberUpdated("minLiveTimeForMarketClose", value);
}
function toggleLimitCloseOrdersRange() external onlyAdmin {
isLimitingMarketClosePriceRange = !isLimitingMarketClosePriceRange;
emit IsLimitingMarketClosePriceRangeToggled(
isLimitingMarketClosePriceRange
);
}
function setNativeFeeForAction(
TradersPortalActions action,
uint256 requiredFee
) external onlyAdmin {
actionFees[action] = requiredFee;
emit ActionFeeSet(action, requiredFee);
}
// ***** Fees Interactions *****
function collectNativeFees(address payable _to) external onlyFeesManager {
uint256 selfNativeBalance = address(this).balance;
require(_to.send(selfNativeBalance), "SEND_FAILED");
}
// ***** On-Behalf Trading Management *****
/**
* @notice Enable or disable on-behalf trading for the caller
* @dev When enabled, allows sub-accounts with valid permissions to trade on behalf of the caller
* @param enabled Whether to enable or disable on-behalf trading
*/
function setOnBehalfActivated(bool enabled) external notDoneOrPaused {
onBehalfActivated[msg.sender] = enabled;
emit OnBehalfActivatedToggled(msg.sender, enabled);
}
// ***** Traders Interactions -- Requests *****
/**
* Submits a request to open a new position
* @param positionRequestIdentifiers The identifiers for the position
* @param positionRequestParams The parameters for the position
* @param orderType The type of order to open
* @param domain The domain of the request
* @param referralCode The referral code for the request
* @param runCapTests Whether to run capital tests
* @return The position ID
*/
function traderRequest_openNewPosition(
ITradingFloorV1.PositionRequestIdentifiers
calldata positionRequestIdentifiers,
ITradingFloorV1.PositionRequestParams calldata positionRequestParams,
ITradingFloorV1.OpenOrderType orderType,
bytes32 domain,
bytes32 referralCode,
bool runCapTests
)
external
payable
override
notContract
notDoneOrPaused
nonReentrant
sentEnoughNativeFee(TradersPortalActions.REQUEST_POSITION_OPEN)
returns (bytes32)
{
address caller = _msgSender();
return
openNewPositionInternal(
caller,
positionRequestIdentifiers,
positionRequestParams,
orderType,
domain,
referralCode,
runCapTests
);
}
/**
* Submits a Market Close position request
* @param _positionId The position ID
* @param _minPrice The minimum price to close in
* @param _maxPrice The maximum price to close in
*/
function traderRequest_marketClosePosition(
bytes32 _positionId,
uint64 _minPrice,
uint64 _maxPrice
)
external
payable
override
notContract
notDoneOrPaused
nonReentrant
sentEnoughNativeFee(TradersPortalActions.REQUEST_POSITION_MARKET_CLOSE)
{
address caller = _msgSender();
setExistingPositionToMarketCloseInternal(
caller,
_positionId,
_minPrice,
_maxPrice
);
}
/**
* Submits a request to update a single field of a position
* @param _positionId The position ID
* @param orderType The type of order to open
* @param fieldValue The value to update
*/
function traderRequest_updatePositionSingleField(
bytes32 _positionId,
OrderBookStructsV1.UpdatePositionFieldOrderType orderType,
uint64 fieldValue
)
external
payable
override
notContract
notDoneOrPaused
nonReentrant
sentEnoughNativeFee(
TradersPortalActions.REQUEST_POSITION_SINGLE_FIELD_UPDATE
)
{
address caller = _msgSender();
updatePositionSingleFieldInternal(
caller,
_positionId,
orderType,
fieldValue
);
}
/**
* Submits a request to update a double field of a position
* @param _positionId The position ID
* @param orderType The type of order to open
* @param fieldValueA The first value to update
* @param fieldValueB The second value to update
*/
function traderRequest_updatePositionDoubleField(
bytes32 _positionId,
OrderBookStructsV1.UpdatePositionFieldOrderType orderType,
uint64 fieldValueA,
uint64 fieldValueB
)
external
payable
override
notContract
notDoneOrPaused
nonReentrant
sentEnoughNativeFee(
TradersPortalActions.REQUEST_POSITION_DOUBLE_FIELD_UPDATE
)
{
address caller = _msgSender();
updatePositionDoubleFieldInternal(
caller,
_positionId,
orderType,
fieldValueA,
fieldValueB
);
}
// ***** Traders Interactions -- Direct Actions *****
/**
* Update a pending position's limit
* @notice This function is only callable by the trader who opened the position and will have immediate effect
* @param positionId The position ID
* @param minPrice The minimum price
* @param maxPrice The maximum price
* @param tp The take profit price
* @param sl The stop loss price
*/
function directAction_updatePendingPosition_limit(
bytes32 positionId,
uint64 minPrice,
uint64 maxPrice,
uint64 tp,
uint64 sl
) external notContract notDoneOrPaused nonReentrant {
address caller = _msgSender();
(
TradingEnumsV1.PositionPhase positionPhase,
uint64 inPhaseSince,
address positionTrader
) = tradingFloor.getPositionPortalInfo(positionId);
require(inPhaseSince > 0, "NO_SUCH_POSITION");
validatePermissions(caller, positionTrader, positionId);
require(
positionPhase == TradingEnumsV1.PositionPhase.OPEN_LIMIT,
"NOT_OPEN_LIMIT"
);
require(
block.timestamp - inPhaseSince >= limitOrdersTimelock,
"LIMIT_TIMELOCK"
);
tradingFloor.updatePendingPosition_openLimit(
positionId,
minPrice,
maxPrice,
tp,
sl
);
}
/**
* Cancel a pending Open-Limit order
* @notice This function is only callable by the trader who opened the position and will have immediate effect
* @param _positionId The position ID
*/
function directAction_cancelPendingPosition_limit(
bytes32 _positionId
) external notContract notDoneOrPaused nonReentrant {
TradingEnumsV1.OpenOrderType limitOpenOrderType = TradingEnumsV1
.OpenOrderType
.LIMIT;
address caller = _msgSender();
(
TradingEnumsV1.PositionPhase positionPhase,
uint64 inPhaseSince,
address positionTrader
) = tradingFloor.getPositionPortalInfo(_positionId);
require(inPhaseSince > 0, "NO_SUCH_POSITION");
validatePermissions(caller, positionTrader, _positionId);
require(
positionPhase == TradingEnumsV1.PositionPhase.OPEN_LIMIT,
"NOT_OPEN_LIMIT"
);
require(
block.timestamp - inPhaseSince >= limitOrdersTimelock,
"LIMIT_TIMELOCK"
);
uint noFee = 0;
tradingFloor.cancelPendingPosition(_positionId, limitOpenOrderType, noFee);
emit PendingOpenLimitPositionCancelled(_positionId);
}
/**
* Deletes a pending position update order that has passed its timeout
* @notice This function is callable by anyone and will have immediate effect
* @param _positionId The position ID
*/
function directAction_timeout_updateTradeField(
bytes32 _positionId
) external notContract notDone nonReentrant {
IOrderBookV1 orderBook = getOrderBook();
OrderBookStructsV1.UpdatePositionFieldOrder
memory updatePositionFieldOrder = orderBook
.readAndDeleteUpdatePositionOrder(_positionId);
// Ensure trade exists
require(updatePositionFieldOrder.timestamp > 0, "NO_SUCH_UPDATE_ORDER");
// Ensure market order timeout passed
require(
block.timestamp >=
updatePositionFieldOrder.timestamp + marketOrdersTimeout,
"WAIT_TIMEOUT"
);
}
/**
* Deletes a pending position Market-Open order that has passed its timeout
* @notice This function is callable by anyone and will have immediate effect
* @param _positionId The position ID
*/
function directAction_timeout_openMarket(
bytes32 _positionId
) external notContract notDone nonReentrant {
address caller = _msgSender();
(
TradingEnumsV1.PositionPhase positionPhase,
uint64 inPhaseSince, // address positionTrader
) = tradingFloor.getPositionPortalInfo(_positionId);
require(inPhaseSince > 0, "NO_SUCH_POSITION");
// require(positionTrader == trader, "NOT_YOUR_POSITION");
require(
positionPhase == TradingEnumsV1.PositionPhase.OPEN_MARKET,
"NOT_OPEN_MARKET"
);
require(
block.timestamp >= inPhaseSince + marketOrdersTimeout,
"WAIT_TIMEOUT"
);
uint noFee = 0;
tradingFloor.cancelPendingPosition(
_positionId,
TradingEnumsV1.OpenOrderType.MARKET,
noFee
);
emit PendingMarketOpenOrderTimeoutCancelled(_positionId, caller);
}
/**
* Deletes a pending position Market-Close order that has passed its timeout
* @notice This function is callable by anyone and will have immediate effect
* @param _positionId The position ID
*/
function directAction_timeout_closeMarket(
bytes32 _positionId
) external notContract notDone nonReentrant {
address caller = _msgSender();
(
TradingEnumsV1.PositionPhase positionPhase,
uint64 inPhaseSince, // address positionTrader
) = tradingFloor.getPositionPortalInfo(_positionId);
require(inPhaseSince > 0, "NO_SUCH_POSITION");
// require(positionTrader == trader, "NOT_YOUR_POSITION");
require(
positionPhase == TradingEnumsV1.PositionPhase.CLOSE_MARKET,
"NOT_CLOSE_MARKET"
);
require(
block.timestamp >= inPhaseSince + marketOrdersTimeout,
"WAIT_TIMEOUT"
);
uint noFee = 0;
tradingFloor.cancelMarketCloseForPosition(
_positionId,
TradingEnumsV1.CloseOrderType.MARKET,
noFee
);
emit PendingMarketCloseOrderTimeoutCancelled(_positionId, caller);
}
// ***** Trader Requests Internal *****
/**
* Submits a request to open a new position
* @param positionRequestIdentifiers The identifiers for the position
* @param positionRequestParams The parameters for the position
* @param orderType The type of order to open
* @param domain The domain of the request
* @param referralCode The referral code for the request
* @param runCapTests Whether to run capital tests
* @return The position ID
*/
function openNewPositionInternal(
address caller,
ITradingFloorV1.PositionRequestIdentifiers
calldata positionRequestIdentifiers,
ITradingFloorV1.PositionRequestParams calldata positionRequestParams,
ITradingFloorV1.OpenOrderType orderType,
bytes32 domain,
bytes32 referralCode,
bool runCapTests
) internal returns (bytes32) {
// If caller is different from position owner, check sub-account permissions
if (
caller != positionRequestIdentifiers.trader &&
caller != getTradeIntentsVerifier()
) {
// First check if the position owner has enabled on-behalf trading
require(
onBehalfActivated[positionRequestIdentifiers.trader],
"CALLER_NOT_TRADER"
);
address onBehalfTrading = getOnBehalfTrading();
require(onBehalfTrading != address(0), "ON_BEHALF_TRADING_NOT_SET");
// Charge permission for the collateral amount
IOnBehalfTrading(onBehalfTrading).chargePermission(
positionRequestIdentifiers.trader, // owner (main account)
caller, // spender (sub-account)
positionRequestIdentifiers.settlementAsset, // token (chip)
positionRequestParams.collateral // amount
);
}
require(
positionRequestParams.minPrice <= positionRequestParams.maxPrice,
"MIN_MAX_REVERSE"
);
// Enforce only specific prices or by fraction, not both
require(
positionRequestParams.tp == 0 || positionRequestParams.tpByFraction == 0,
"MULTIPLE_TP_DEFINITIONS"
);
require(
positionRequestParams.sl == 0 || positionRequestParams.slByFraction == 0,
"MULTIPLE_SL_DEFINITIONS"
);
require(
positionRequestParams.slByFraction < FRACTION_SCALE,
"SL_OF_MORE_THAN_100_PERCENT"
);
require(
positionRequestParams.tp == 0 ||
(
positionRequestParams.long
? positionRequestParams.tp > positionRequestParams.maxPrice
: positionRequestParams.tp < positionRequestParams.minPrice
),
"WRONG_TP"
);
require(
positionRequestParams.sl == 0 ||
(
positionRequestParams.long
? positionRequestParams.sl < positionRequestParams.minPrice
: positionRequestParams.sl > positionRequestParams.maxPrice
),
"WRONG_SL"
);
// Validate the trade if requested
if (runCapTests) {
validateTradeCanBeOpenedInternal(
positionRequestIdentifiers,
positionRequestParams
);
}
uint32 spreadReductionF = 0;
bytes32 positionId;
// Limit Order
if (orderType == TradingEnumsV1.OpenOrderType.LIMIT) {
positionId = tradingFloor.storePendingPosition(
orderType,
positionRequestIdentifiers,
positionRequestParams,
spreadReductionF
);
} else if (orderType == TradingEnumsV1.OpenOrderType.MARKET) {
positionId = tradingFloor.storePendingPosition(
orderType,
positionRequestIdentifiers,
positionRequestParams,
spreadReductionF
);
} else {
revert("UNSUPPORTED");
}
emit PositionRequested(domain, referralCode, positionId);
return positionId;
}
/**
* Sets an existing position to Market-Close
* @param caller The caller address
* @param _positionId The position ID
* @param _minPrice The minimum price
* @param _maxPrice The maximum price
*/
function setExistingPositionToMarketCloseInternal(
address caller,
bytes32 _positionId,
uint64 _minPrice,
uint64 _maxPrice
) internal {
(
TradingEnumsV1.PositionPhase positionPhase,
uint64 inPhaseSince,
address positionTrader
) = tradingFloor.getPositionPortalInfo(_positionId);
require(inPhaseSince > 0, "NO_SUCH_POSITION");
validatePermissions(caller, positionTrader, _positionId);
require(
positionPhase != TradingEnumsV1.PositionPhase.CLOSE_MARKET,
"ALREADY_BEING_CLOSED"
);
require(
block.timestamp - inPhaseSince >= minLiveTimeForMarketClose,
"MIN_LIVE_TIME_FOR_MARKET_CLOSE"
);
bool limitingRange = isLimitingMarketClosePriceRange;
tradingFloor.setOpenedPositionToMarketClose(
_positionId,
limitingRange ? 0 : _minPrice,
limitingRange ? type(uint64).max : _maxPrice
);
}
/**
* Submits a request to update a single field of a position
* @param caller The caller address
* @param _positionId The position ID
* @param orderType The type of order to open
* @param fieldValue The value to update
*/
function updatePositionSingleFieldInternal(
address caller,
bytes32 _positionId,
OrderBookStructsV1.UpdatePositionFieldOrderType orderType,
uint64 fieldValue
) internal {
(
TradingEnumsV1.PositionPhase positionPhase,
uint64 inPhaseSince,
address positionTrader
) = tradingFloor.getPositionPortalInfo(_positionId);
// Ensure position exists
require(inPhaseSince > 0, "NO_SUCH_POSITION");
// Can only update own trades
validatePermissions(caller, positionTrader, _positionId);
require(
positionPhase == TradingEnumsV1.PositionPhase.OPENED,
"ONLY_OPENED"
);
IOrderBookV1 orderBook = getOrderBook();
orderBook.storeUpdatePositionSingleFieldOrder(
_positionId,
orderType,
fieldValue
);
}
/**
* Submits a request to update a double field of a position
* @param caller The caller address
* @param _positionId The position ID
* @param orderType The type of order to open
* @param fieldValueA The first value to update
* @param fieldValueB The second value to update
*/
function updatePositionDoubleFieldInternal(
address caller,
bytes32 _positionId,
OrderBookStructsV1.UpdatePositionFieldOrderType orderType,
uint64 fieldValueA,
uint64 fieldValueB
) internal {
(
TradingEnumsV1.PositionPhase positionPhase,
uint64 inPhaseSince,
address positionTrader
) = tradingFloor.getPositionPortalInfo(_positionId);
// Ensure position exists
require(inPhaseSince > 0, "NO_SUCH_POSITION");
// Can only update own trades
validatePermissions(caller, positionTrader, _positionId);
require(
positionPhase == TradingEnumsV1.PositionPhase.OPENED,
"ONLY_OPENED"
);
IOrderBookV1 orderBook = getOrderBook();
orderBook.storeUpdatePositionDoubleFieldOrder(
_positionId,
orderType,
fieldValueA,
fieldValueB
);
}
// ***** Internal validation *****
/**
* Ths function holds the trade-opening validation logic that is shared between market and limit orders
* @dev Will revert if validation fails
*/
function validateTradeCanBeOpenedInternal(
TradingFloorStructsV1.PositionRequestIdentifiers
calldata requestIdentifiers,
TradingFloorStructsV1.PositionRequestParams calldata params
) internal view {
IPoolAccountantV1 poolAccountant = tradingFloor.poolAccountantForAsset(
requestIdentifiers.settlementAsset
);
require(address(poolAccountant) != address(0), "NO_ACCOUNTANT");
validateMaxBorrowCap(poolAccountant, requestIdentifiers, params);
require(
tradingFloor
.pairTradersInfo(
requestIdentifiers.settlementAsset,
requestIdentifiers.trader,
requestIdentifiers.pairId
)
.positionsCounter < tradingFloor.maxTradesPerPair(),
"MAX_TRADES_PER_PAIR"
);
PoolAccountantStructs.Pair memory pair = poolAccountant.pairs(
requestIdentifiers.pairId
);
PoolAccountantStructs.Group memory group = poolAccountant.groups(
pair.groupId
);
PoolAccountantStructs.Fee memory fee = poolAccountant.fees(pair.feeId);
require(
params.leverage > 0 && params.leverage >= pair.minLeverage,
"LEVERAGE_TOO_LOW_FOR_PAIR"
);
require(params.leverage <= pair.maxLeverage, "LEVERAGE_TOO_HIGH_FOR_PAIR");
require(
params.leverage > 0 && params.leverage >= group.minLeverage,
"LEVERAGE_TOO_LOW_FOR_GROUP"
);
require(
params.leverage <= group.maxLeverage,
"LEVERAGE_TOO_HIGH_FOR_GROUP"
);
uint leveragedPosition = calculateLeveragedPosition(
params.collateral,
params.leverage
);
require(leveragedPosition <= pair.maxPositionSize, "POSITION_TOO_BIG");
uint minOpenFee = poolAccountant.minOpenFee();
uint openFeeF = fee.openFeeF;
uint positionOpenFee = (leveragedPosition * openFeeF) / FRACTION_SCALE;
require(positionOpenFee >= minOpenFee, "DOES_NOT_REACH_MIN_OPEN_FEE");
}
// ***** Internal Functions *****
function validatePermissions(
address caller,
address positionTrader,
bytes32 _positionId
) internal view {
// Check if caller owns the position or has permission to manage it
if (caller != positionTrader && caller != getTradeIntentsVerifier()) {
// First check if the position owner has enabled on-behalf trading
require(onBehalfActivated[positionTrader], "CALLER_NOT_TRADER");
// Sub-account trying to manage main account's position
address onBehalfTrading = getOnBehalfTrading();
require(onBehalfTrading != address(0), "ON_BEHALF_TRADING_NOT_SET");
// Get the chip from the position
address settlementAsset = tradingFloor
.positionIdentifiersById(_positionId)
.settlementAsset;
// Verify permission (without charging)
IOnBehalfTrading(onBehalfTrading).requirePermission(
positionTrader, // owner (main account)
caller, // spender (sub-account)
settlementAsset // token (chip)
);
}
}
function validateMaxBorrowCap(
IPoolAccountantV1 poolAccountant,
ITradingFloorV1.PositionRequestIdentifiers
calldata positionRequestIdentifiers,
ITradingFloorV1.PositionRequestParams calldata positionRequestParams
) internal view {
uint64 openPrice = positionRequestParams.long
? positionRequestParams.minPrice
: positionRequestParams.maxPrice;
uint64 tp = calculateTp(
openPrice,
positionRequestParams,
poolAccountant.maxGainF()
);
uint256 amount = poolAccountant.calcBorrowAmount(
positionRequestParams.collateral,
positionRequestParams.leverage,
positionRequestParams.long,
openPrice,
tp
);
uint256 oldPairBorrows = poolAccountant.pairBorrows(
positionRequestIdentifiers.pairId
);
uint256 newPairBorrows = oldPairBorrows + amount;
require(
newPairBorrows <=
poolAccountant.pairMaxBorrow(positionRequestIdentifiers.pairId),
"MAX_BORROW_PAIR"
);
uint16 groupId = poolAccountant
.pairs(positionRequestIdentifiers.pairId)
.groupId;
uint256 oldGroupBorrows = poolAccountant.groupBorrows(groupId);
uint256 newGroupBorrows = oldGroupBorrows + amount;
require(
newGroupBorrows <= poolAccountant.groupMaxBorrow(groupId),
"MAX_BORROW_GROUP"
);
uint256 oldTotalBorrows = poolAccountant.totalBorrows();
uint256 newTotalBorrows = oldTotalBorrows + amount;
require(
newTotalBorrows <= poolAccountant.maxTotalBorrows(),
"MAX_TOTAL_BORROW"
);
}
function calculateTp(
uint64 openPrice,
ITradingFloorV1.PositionRequestParams calldata positionRequestParams,
uint256 maxGainF
) internal pure returns (uint64 tp) {
tp = positionRequestParams.tp;
if (positionRequestParams.tpByFraction > 0) {
uint64 priceDiff = calculatePriceDiffFromFractionAndLeverage(
openPrice,
positionRequestParams.tpByFraction,
positionRequestParams.leverage
);
tp = positionRequestParams.long
? openPrice + priceDiff
: priceDiff < openPrice
? openPrice - priceDiff
: 0;
}
tp = correctTp(
uint64(maxGainF),
openPrice,
positionRequestParams.leverage,
tp,
positionRequestParams.long
);
}
function calculatePriceDiffFromFractionAndLeverage(
uint64 originPrice,
uint64 fractionDiff,
uint64 leverage
) internal pure returns (uint64) {
uint64 diffInPrice = uint64(
(uint256(originPrice) * uint256(fractionDiff) * LEVERAGE_SCALE) /
FRACTION_SCALE /
uint256(leverage)
);
return diffInPrice;
}
/**
* Receives the wanted sl for a position (with other relevant params) and makes sure the value is within the expected range
* @notice In case of TP == 0 or a breach of max value, the value returned will be the max allowed value
* (can be capped by 0 in case of a SHORT position)
*/
function correctTp(
uint64 maxGainF,
uint64 openPrice,
uint64 leverage, // scaled up from 32
uint64 tp,
bool buy
) internal pure returns (uint64) {
if (
tp == 0 ||
currentProfitFraction(maxGainF, openPrice, tp, buy, leverage) >=
int64(maxGainF)
) {
uint64 tpDiff = uint64(
((uint256(openPrice) * uint256(maxGainF)) * LEVERAGE_SCALE) /
uint256(leverage) /
FRACTION_SCALE
);
return
buy
? openPrice + tpDiff
: tpDiff <= openPrice
? openPrice - tpDiff
: 0;
}
return tp;
}
/**
* Calculates the (positive or negative) profit fraction by given position values
* @return f The profit fraction, with scale of FRACTION_SCALE
*/
function currentProfitFraction(
uint64 maxGainF,
uint64 openPrice,
uint64 currentPrice,
bool buy,
uint64 leverage // scaled from 32
) internal pure returns (int64 f) {
int64 maxPnlF = int64(maxGainF);
int64 priceDiff = buy
? int64(currentPrice) - int64(openPrice)
: int64(openPrice) - int64(currentPrice);
int256 nominator = int256(priceDiff) *
int256(FRACTION_SCALE) *
int256(int64(leverage));
int256 longF = nominator /
int256(LEVERAGE_SCALE) /
int256(int64(openPrice));
f = int64(longF);
f = f > maxPnlF ? maxPnlF : f;
}
// ***** Context Utils *****
/**
* @return The message sender
*/
function _msgSender() public view returns (address) {
return msg.sender;
}
}// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import { ILayerZeroComposer } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroComposer.sol";
/**
* @title IOAppComposer
* @dev This interface defines the OApp Composer, allowing developers to inherit only the OApp package without the protocol.
*/
// solhint-disable-next-line no-empty-blocks
interface IOAppComposer is ILayerZeroComposer {}// 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;
/**
* @title ILayerZeroComposer
*/
interface ILayerZeroComposer {
/**
* @notice Composes a LayerZero message from an OApp.
* @param _from The address initiating the composition, typically the OApp where the lzReceive was called.
* @param _guid The unique identifier for the corresponding LayerZero src/dst tx.
* @param _message The composed message payload in bytes. NOT necessarily the same payload passed via lzReceive.
* @param _executor The address of the executor for the composed message.
* @param _extraData Additional arbitrary data in bytes passed by the entity who executes the lzCompose.
*/
function lzCompose(
address _from,
bytes32 _guid,
bytes calldata _message,
address _executor,
bytes calldata _extraData
) external payable;
}// 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/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.
pragma solidity ^0.8.20;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```solidity
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*
* [WARNING]
* ====
* Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
* unusable.
* See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
*
* In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
* array of EnumerableSet.
* ====
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position is the index of the value in the `values` array plus 1.
// Position 0 is used to mean a value is not in the set.
mapping(bytes32 value => uint256) _positions;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._positions[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We cache the value's position to prevent multiple reads from the same storage slot
uint256 position = set._positions[value];
if (position != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 valueIndex = position - 1;
uint256 lastIndex = set._values.length - 1;
if (valueIndex != lastIndex) {
bytes32 lastValue = set._values[lastIndex];
// Move the lastValue to the index where the value to delete is
set._values[valueIndex] = lastValue;
// Update the tracked position of the lastValue (that was just moved)
set._positions[lastValue] = position;
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the tracked position for the deleted slot
delete set._positions[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._positions[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
bytes32[] memory store = _values(set._inner);
bytes32[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
/// @solidity memory-safe-assembly
assembly {
result := store
}
return result;
}
}// 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;
/**
* @title EIP712Utils
* @notice Utility functions for EIP-712 logic.
* @dev Based on https://github.com/ethereum/EIPs/blob/master/assets/eip-712/Example.sol
*/
contract EIP712Utils {
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
bytes32 public constant EIP712DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
function hashDomain(
EIP712Domain memory eip712Domain
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
)
);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "./EIP712Utils.sol";
/**
* @title MultiChainEIP712Base
* @notice Base contract for EIP712 signature verification using multiple chain ids
*/
contract MultiChainEIP712Base is EIP712Utils {
// ***** Events *****
event DomainSeparatorForChainStored(
uint256 indexed chainId,
bytes32 domainSeparator
);
// ***** Storage *****
string public CONTRACT_DOMAIN_NAME;
string public CONTRACT_DOMAIN_VERSION;
// asset => domain separator for intents
mapping(uint256 => bytes32) public domainSeparatorForChain;
// ***** Constructor *****
constructor(
string memory _contractDomainName,
string memory _contractDomainVersion
) {
CONTRACT_DOMAIN_NAME = _contractDomainName;
CONTRACT_DOMAIN_VERSION = _contractDomainVersion;
}
// ***** Domain Generation *****
function generateAndStoreDomainSeparatorIfMissingInternal(
uint256 chainId
) internal returns (bytes32) {
bytes32 storedDomainSeparator = domainSeparatorForChain[chainId];
if (storedDomainSeparator == bytes32(0)) {
bytes32 domainSeparator = hashDomain(
EIP712Domain({
name: CONTRACT_DOMAIN_NAME,
version: CONTRACT_DOMAIN_VERSION,
chainId: chainId,
verifyingContract: address(this)
})
);
domainSeparatorForChain[chainId] = domainSeparator;
emit DomainSeparatorForChainStored(chainId, domainSeparator);
return domainSeparator;
} else {
return storedDomainSeparator;
}
}
}// 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 "@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;
/**
* @dev only use immutables and constants in this contract
*/
contract CommonScales {
uint256 public constant PRECISION = 1e18; // 18 decimals
uint256 public constant LEVERAGE_SCALE = 100; // 2 decimal points
uint256 public constant FRACTION_SCALE = 100000; // 5 decimal points
uint256 public constant ACCURACY_IMPROVEMENT_SCALE = 1e9;
function calculateLeveragedPosition(
uint256 collateral,
uint256 leverage
) internal pure returns (uint256) {
return (collateral * leverage) / LEVERAGE_SCALE;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "../../AdministrationContracts/ClaimableAdmin.sol";
import "../../CryptographyContracts/MultiChainEIP712Base.sol";
import {IntentsPermissions, PermissionsType} from "../../Peripheral/Chips/IntentsPermissions.sol";
import {OFTChip} from "../Chips/OFTChip/OFTChip.sol";
/**
* @title MultiSourceChainIntentsVerifierBase
* @dev Base contract for verifying intents that can be signed with different 'chainId' values.
*/
contract MultiSourceChainIntentsVerifierBase is
ClaimableAdmin,
MultiChainEIP712Base
{
// ***** Storage *****
string public constant DYN_ROLE_INTENTS_PERMISSIONS_PREFIX =
"INTENTS_PERMISSIONS_";
// OFTChip => open flag to check for intents permissions
mapping(OFTChip => string) public intentsPermissions;
// ***** Events *****
event SourceChainIdForAssetStored(
address indexed asset,
uint256 indexed chainId
);
// asset => source chain ID
mapping(address => uint256) public sourceChainIdForAsset;
constructor(
string memory _contractDomainName,
string memory _contractDomainVersion
) MultiChainEIP712Base(_contractDomainName, _contractDomainVersion) {}
// ***** Views *****
/**
* @notice Returns the domain separator for the given asset.
* @param asset The asset for which to return the domain separator.
* @return The domain separator for the given asset.
*/
function domainSeparatorForAsset(
address asset
) public view returns (bytes32) {
return domainSeparatorForChain[sourceChainIdForAsset[asset]];
}
// ***** Admin Functions *****
/**
* @notice Stores the source chain ID for the given asset.
* @param asset The asset for which to store the source chain ID.
* @param chainId The source chain ID to store.
*/
function storeSourceChainForAsset(
address asset,
uint256 chainId
) external virtual onlyAdmin {
storeSourceChainForAssetInternal(asset, chainId);
}
/**
* @notice Opens/Closes the intents permissions check for the chip.
* @param oftChip The chip for the intents permissions check.
* @param dynAddressSuffix is a suffix for dynamicly set address in the Registry
*/
function setIntentsPermissions(
OFTChip oftChip,
string calldata dynAddressSuffix
) external onlyAdmin {
intentsPermissions[oftChip] = dynAddressSuffix;
}
// ***** Internals *****
/**
* @notice Stores the source chain ID for the given asset.
* @dev chain Ids for assets cannot be changed.
* @param asset The asset for which to store the source chain ID.
* @param chainId The source chain ID to store.
*/
function storeSourceChainForAssetInternal(
address asset,
uint256 chainId
) internal {
// Can only configure once
require(
sourceChainIdForAsset[asset] == 0,
"CHAIN_ID_FOR_ASSET_ALREADY_CONFIGURED"
);
// Cannot set to zero
require(chainId != 0, "CHAIN_ID_ZERO");
// Ensure domain separator is configured for this chain
generateAndStoreDomainSeparatorIfMissingInternal(chainId);
// Store mapping
sourceChainIdForAsset[asset] = chainId;
// event
emit SourceChainIdForAssetStored(asset, chainId);
}
/**
* @notice Returns the domain separator for the given asset.
* @dev Allows inheriting contracts to get the relevant domain separator for intents verifications.
* @param _asset The asset for which to return the domain separator.
* @return The domain separator for the given asset.
*/
function getDomainSeparatorForAssetInternal(
address _asset
) internal view returns (bytes32) {
(bytes32 domainSeparator, ) = getDomainSeparatorAndChainForAssetInternal(
_asset
);
return domainSeparator;
}
/**
* @notice Returns the domain separator and chain ID for the given asset.
* @dev Allows inheriting contracts to get the relevant domain separator and chain ID for intents verifications.
* @param _asset The asset for which to return the domain separator and chain ID.
* @return The domain separator and chain ID for the given asset.
*/
function getDomainSeparatorAndChainForAssetInternal(
address _asset
) internal view returns (bytes32, uint256) {
uint256 chainId = sourceChainIdForAsset[_asset];
require(chainId != 0, "NO_CHAIN_ID_FOR_ASSET");
bytes32 domainSeparator = domainSeparatorForChain[chainId];
require(domainSeparator != bytes32(0), "NO_DOMAIN_SEPARATOR_FOR_CHAIN");
return (domainSeparator, chainId);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/**
* @title HashAndActionSerialNonceBase
* @notice Base contract for managing serial nonces for actions per id
*/
contract HashAndActionSerialNonceBase {
// ***** Storage *****
// id => action type => nonce
mapping(bytes32 => mapping(uint8 => uint256)) public nonceMap;
// ***** Views *****
/**
* @notice Get the next valid nonce for an action type
* @param id The id
* @param actionType The action type
* @return The next valid nonce
*/
function getNextValidNonceFor(
bytes32 id,
uint8 actionType
) external view returns (uint256) {
return nonceMap[id][actionType];
}
// ***** Internal *****
/**
* @notice Validate the nonce for an action type and increase the nonce
* @param id The id
* @param actionType The action type
* @param nonce The nonce
*/
function validateNonceForActionAndIncrease(
bytes32 id,
uint8 actionType,
uint256 nonce
) internal {
uint256 currentNonceMapValue = nonceMap[id][actionType];
require(nonce == currentNonceMapValue, "INCORRECT_NONCE");
nonceMap[id][actionType] = currentNonceMapValue + 1;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "../interfaces/IRegistryV1.sol";
import "../interfaces/ITradingFloorV1.sol";
import "../interfaces/IOrderBookV1.sol";
import "../interfaces/ITradersPortalV1.sol";
import "./NonceMechanisms/HashAndActionSerialNonceBase.sol";
import "./MultiSourceChainIntentsVerifierBase.sol";
/**
* @title TradeIntentsVerifierV1
* @notice This contract is responsible for verifying trade related intents
* @dev All verification functions in this contract work in the same manner
* - Verify that the payload was signed by the trader
* - Verify that the nonce is valid (and mark it as used)
* - Perform the action
* - Emit an event
*
* Only exception is the openNewPosition function, which also stores the domain separator and trader for the position
* so that it can be used in further verifications related to the position.
*/
contract TradeIntentsVerifierV1 is
MultiSourceChainIntentsVerifierBase,
HashAndActionSerialNonceBase
{
// ***** Enums *****
enum TradeIntentsVerifierActions {
NONE,
REQUEST_POSITION_OPEN,
REQUEST_POSITION_MARKET_CLOSE,
REQUEST_POSITION_SINGLE_FIELD_UPDATE,
REQUEST_POSITION_DOUBLE_FIELD_UPDATE,
DIRECT_UPDATE_PENDING_LIMIT_POSITION,
DIRECT_CANCEL_PENDING_LIMIT_POSITION
}
// ***** Action Verifications (Immutable) *****
string public constant REQUEST_PAYLOAD_OPEN_POSITION_TYPE_DESCRIPTOR =
"UserRequestPayload_OpenPosition(uint256 nonce,PositionRequestIdentifiers positionRequestIdentifiers,PositionRequestParams positionRequestParams,uint8 orderType)PositionRequestIdentifiers(address trader,uint16 pairId,address settlementAsset,uint32 positionIndex)PositionRequestParams(bool long,uint256 collateral,uint32 leverage,uint64 minPrice,uint64 maxPrice,uint64 tp,uint64 sl,uint64 tpByFraction,uint64 slByFraction)";
string public constant POSITION_REQUEST_IDENTIFIERS_TYPE_DESCRIPTOR =
"PositionRequestIdentifiers(address trader,uint16 pairId,address settlementAsset,uint32 positionIndex)";
string public constant POSITION_REQUEST_PARAMS_TYPE_DESCRIPTOR =
"PositionRequestParams(bool long,uint256 collateral,uint32 leverage,uint64 minPrice,uint64 maxPrice,uint64 tp,uint64 sl,uint64 tpByFraction,uint64 slByFraction)";
string public constant REQUEST_PAYLOAD_CLOSE_MARKET_TYPE_DESCRIPTOR =
"UserRequestPayload_CloseMarket(uint256 nonce,bytes32 positionId,uint64 minPrice,uint64 maxPrice)";
string
public constant REQUEST_PAYLOAD_UPDATE_POSITION_SINGLE_FIELD_TYPE_DESCRIPTOR =
"UserRequestPayload_UpdatePositionSingleField(uint256 nonce,bytes32 positionId,uint8 orderType,uint64 fieldValue)";
string
public constant REQUEST_PAYLOAD_UPDATE_POSITION_DOUBLE_FIELD_TYPE_DESCRIPTOR =
"UserRequestPayload_UpdatePositionDoubleField(uint256 nonce,bytes32 positionId,uint8 orderType,uint64 fieldValueA,uint64 fieldValueB)";
string
public constant DIRECT_PAYLOAD_UPDATE_PENDING_LIMIT_POSITION_TYPE_DESCRIPTOR =
"UserDirectPayload_UpdatePendingLimitPosition(uint256 nonce,bytes32 positionId,uint64 minPrice,uint64 maxPrice,uint64 tp,uint64 sl)";
string
public constant DIRECT_PAYLOAD_CANCEL_PENDING_LIMIT_POSITION_TYPE_DESCRIPTOR =
"UserDirectPayload_CancelPendingLimitPosition(uint256 nonce,bytes32 positionId)";
struct UserRequestPayload_OpenPosition {
uint256 nonce;
ITradingFloorV1.PositionRequestIdentifiers positionRequestIdentifiers;
ITradingFloorV1.PositionRequestParams positionRequestParams;
ITradingFloorV1.OpenOrderType orderType;
}
struct UserRequestPayload_CloseMarket {
uint256 nonce;
bytes32 positionId;
uint64 minPrice;
uint64 maxPrice;
}
struct UserRequestPayload_UpdatePositionSingleField {
uint256 nonce;
bytes32 positionId;
OrderBookStructsV1.UpdatePositionFieldOrderType orderType;
uint64 fieldValue;
}
struct UserRequestPayload_UpdatePositionDoubleField {
uint256 nonce;
bytes32 positionId;
OrderBookStructsV1.UpdatePositionFieldOrderType orderType;
uint64 fieldValueA;
uint64 fieldValueB;
}
struct UserDirectPayload_UpdatePendingLimitPosition {
uint256 nonce;
bytes32 positionId;
uint64 minPrice;
uint64 maxPrice;
uint64 tp;
uint64 sl;
}
struct UserDirectPayload_CancelPendingLimitPosition {
uint256 nonce;
bytes32 positionId;
}
// ***** Contracts (Immutable) *****
IRegistryV1 public immutable registry;
// ***** Params *****
// position id => domain separator
mapping(bytes32 => bytes32) public domainSeparatorsForPosition;
// position id => trader
mapping(bytes32 => address) public tradersForPosition;
// position id => settlement asset
mapping(bytes32 => address) public settlementAssetsForPosition;
// ***** Events *****
event TradeIntentVerified(
address indexed sender,
TradeIntentsVerifierActions indexed action,
bytes32 positionId,
uint256 nonce
);
// ***** Modifiers *****
modifier notContract() {
require(tx.origin == _msgSender());
_;
}
// ***** Views *****
function getTradersPortal() public view returns (ITradersPortalV1) {
return ITradersPortalV1(registry.tradersPortal());
}
function getTradingFloor() public view returns (ITradingFloorV1) {
return
ITradingFloorV1(
ITradersPortalV1(registry.tradersPortal()).tradingFloor()
);
}
function recoverOpenPositionPayloadSigner(
UserRequestPayload_OpenPosition calldata payload,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 domainSeparator
) public pure returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
hashOpenPositionPayload(payload)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), "INVALID_SIGNATURE");
return recoveredAddress;
}
function recoverCloseMarketPayloadSigner(
UserRequestPayload_CloseMarket calldata payload,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 domainSeparator
) public pure returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
hashCloseMarketPayload(payload)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), "INVALID_SIGNATURE");
return recoveredAddress;
}
function recoverUpdatePositionSingleFieldPayloadSigner(
UserRequestPayload_UpdatePositionSingleField calldata payload,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 domainSeparator
) public pure returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
hashUpdatePositionSingleFieldPayload(payload)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), "INVALID_SIGNATURE");
return recoveredAddress;
}
function recoverUpdatePositionDoubleFieldPayloadSigner(
UserRequestPayload_UpdatePositionDoubleField calldata payload,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 domainSeparator
) public pure returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
hashUpdatePositionDoubleFieldPayload(payload)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), "INVALID_SIGNATURE");
return recoveredAddress;
}
function recoverUpdatePendingLimitPositionSigner(
UserDirectPayload_UpdatePendingLimitPosition calldata payload,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 domainSeparator
) public pure returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
hashUpdatePendingLimitPositionPayload(payload)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), "INVALID_SIGNATURE");
return recoveredAddress;
}
function recoverCancelPendingLimitPositionSigner(
UserDirectPayload_CancelPendingLimitPosition calldata payload,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 domainSeparator
) public pure returns (address) {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
hashCancelPendingLimitPositionPayload(payload)
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0), "INVALID_SIGNATURE");
return recoveredAddress;
}
// ***** Constructor *****
constructor(
IRegistryV1 _registry
) MultiSourceChainIntentsVerifierBase("Trade Intents Verifier", "1") {
require(address(_registry) != address(0), "WRONG_PARAMS");
registry = _registry;
}
// ***** Admin functions *****
// ***** Traders Interactions -- Requests *****
function verifyIntent_traderRequest_openNewPosition(
UserRequestPayload_OpenPosition calldata payload,
uint8 v,
bytes32 r,
bytes32 s,
bytes32 domain,
bytes32 referralCode,
bool runCapTests
) external payable notContract {
bytes32 domainSeparator = getDomainSeparatorForAssetInternal(
payload.positionRequestIdentifiers.settlementAsset
);
// Recover trader
address recoveredSigner = recoverOpenPositionPayloadSigner(
payload,
v,
r,
s,
domainSeparator
);
// Sanity
require(
payload.positionRequestIdentifiers.trader == recoveredSigner ||
isIntentPermitted(
payload.positionRequestIdentifiers.settlementAsset,
payload.positionRequestIdentifiers.trader,
recoveredSigner
),
"NOT_SIGNED_BY_TRADER"
);
// Generate expected position id
bytes32 expectedPositionId = getTradingFloor().generatePositionHashId(
payload.positionRequestIdentifiers.settlementAsset,
payload.positionRequestIdentifiers.trader,
payload.positionRequestIdentifiers.pairId,
payload.positionRequestIdentifiers.positionIndex
);
// Validate & Register Nonce
validateNonceForActionAndIncrease(
expectedPositionId,
uint8(TradeIntentsVerifierActions.REQUEST_POSITION_OPEN),
payload.nonce
);
// Perform action
bytes32 positionId = getTradersPortal().traderRequest_openNewPosition{
value: msg.value
}(
payload.positionRequestIdentifiers,
payload.positionRequestParams,
payload.orderType,
domain,
referralCode,
runCapTests
);
// SANITY : Ensure that the positionId is the expected one
// NOTE : This should never fail and if it is the case, it is a critical error.
require(positionId == expectedPositionId, "UNEXPECTED_POSITION_ID");
// Store position domain and trader for further verifications
domainSeparatorsForPosition[positionId] = domainSeparator;
tradersForPosition[positionId] = payload.positionRequestIdentifiers.trader;
// Save settlement asset for positionId
settlementAssetsForPosition[positionId] = payload
.positionRequestIdentifiers
.settlementAsset;
// Event
emit TradeIntentVerified(
msg.sender,
TradeIntentsVerifierActions.REQUEST_POSITION_OPEN,
positionId,
payload.nonce
);
}
function verifyIntent_traderRequest_marketClosePosition(
UserRequestPayload_CloseMarket calldata payload,
uint8 v,
bytes32 r,
bytes32 s
) external payable notContract {
// Get verification values
(
bytes32 domainSeparatorForPosition,
address traderForPosition
) = getDomainSeparatorAndTraderForPositionInternal(payload.positionId);
// Recover trader
address recoveredSigner = recoverCloseMarketPayloadSigner(
payload,
v,
r,
s,
domainSeparatorForPosition
);
// Sanity
require(
traderForPosition == recoveredSigner ||
isIntentPermittedByPositionId(
payload.positionId,
traderForPosition,
recoveredSigner
),
"NOT_SIGNED_BY_TRADER"
);
// Validate & Register Nonce
validateNonceForActionAndIncrease(
payload.positionId,
uint8(TradeIntentsVerifierActions.REQUEST_POSITION_MARKET_CLOSE),
payload.nonce
);
// Perform action
getTradersPortal().traderRequest_marketClosePosition{value: msg.value}(
payload.positionId,
payload.minPrice,
payload.maxPrice
);
// Event
emit TradeIntentVerified(
msg.sender,
TradeIntentsVerifierActions.REQUEST_POSITION_MARKET_CLOSE,
payload.positionId,
payload.nonce
);
}
function verifyIntent_traderRequest_updatePositionSingleField(
UserRequestPayload_UpdatePositionSingleField calldata payload,
uint8 v,
bytes32 r,
bytes32 s
) external payable notContract {
// Get verification values
(
bytes32 domainSeparatorForPosition,
address traderForPosition
) = getDomainSeparatorAndTraderForPositionInternal(payload.positionId);
// Recover trader
address recoveredSigner = recoverUpdatePositionSingleFieldPayloadSigner(
payload,
v,
r,
s,
domainSeparatorForPosition
);
// Sanity
require(
traderForPosition == recoveredSigner ||
isIntentPermittedByPositionId(
payload.positionId,
traderForPosition,
recoveredSigner
),
"NOT_SIGNED_BY_TRADER"
);
// Validate & Register Nonce
validateNonceForActionAndIncrease(
payload.positionId,
uint8(TradeIntentsVerifierActions.REQUEST_POSITION_SINGLE_FIELD_UPDATE),
payload.nonce
);
// Perform action
getTradersPortal().traderRequest_updatePositionSingleField{
value: msg.value
}(payload.positionId, payload.orderType, payload.fieldValue);
// Event
emit TradeIntentVerified(
msg.sender,
TradeIntentsVerifierActions.REQUEST_POSITION_SINGLE_FIELD_UPDATE,
payload.positionId,
payload.nonce
);
}
function verifyIntent_traderRequest_updatePositionDoubleField(
UserRequestPayload_UpdatePositionDoubleField calldata payload,
uint8 v,
bytes32 r,
bytes32 s
) external payable notContract {
// Get verification values
(
bytes32 domainSeparatorForPosition,
address traderForPosition
) = getDomainSeparatorAndTraderForPositionInternal(payload.positionId);
// Recover trader
address recoveredSigner = recoverUpdatePositionDoubleFieldPayloadSigner(
payload,
v,
r,
s,
domainSeparatorForPosition
);
// Sanity
require(
traderForPosition == recoveredSigner ||
isIntentPermittedByPositionId(
payload.positionId,
traderForPosition,
recoveredSigner
),
"NOT_SIGNED_BY_TRADER"
);
// Validate & Register Nonce
validateNonceForActionAndIncrease(
payload.positionId,
uint8(TradeIntentsVerifierActions.REQUEST_POSITION_DOUBLE_FIELD_UPDATE),
payload.nonce
);
// Perform action
getTradersPortal().traderRequest_updatePositionDoubleField{
value: msg.value
}(
payload.positionId,
payload.orderType,
payload.fieldValueA,
payload.fieldValueB
);
// Event
emit TradeIntentVerified(
msg.sender,
TradeIntentsVerifierActions.REQUEST_POSITION_DOUBLE_FIELD_UPDATE,
payload.positionId,
payload.nonce
);
}
// ***** Traders Interactions -- Direct Actions *****
function verifyIntent_traderAction_updatePendingLimitPosition(
UserDirectPayload_UpdatePendingLimitPosition calldata payload,
uint8 v,
bytes32 r,
bytes32 s
) external payable notContract {
// Get verification values
(
bytes32 domainSeparatorForPosition,
address traderForPosition
) = getDomainSeparatorAndTraderForPositionInternal(payload.positionId);
// Recover trader
address recoveredSigner = recoverUpdatePendingLimitPositionSigner(
payload,
v,
r,
s,
domainSeparatorForPosition
);
// Sanity
require(
traderForPosition == recoveredSigner ||
isIntentPermittedByPositionId(
payload.positionId,
traderForPosition,
recoveredSigner
),
"NOT_SIGNED_BY_TRADER"
);
// Validate & Register Nonce
validateNonceForActionAndIncrease(
payload.positionId,
uint8(TradeIntentsVerifierActions.DIRECT_UPDATE_PENDING_LIMIT_POSITION),
payload.nonce
);
// Perform action
getTradersPortal().directAction_updatePendingPosition_limit(
payload.positionId,
payload.minPrice,
payload.maxPrice,
payload.tp,
payload.sl
);
// Event
emit TradeIntentVerified(
msg.sender,
TradeIntentsVerifierActions.DIRECT_UPDATE_PENDING_LIMIT_POSITION,
payload.positionId,
payload.nonce
);
}
function verifyIntent_traderAction_cancelPendingLimitPosition(
UserDirectPayload_CancelPendingLimitPosition calldata payload,
uint8 v,
bytes32 r,
bytes32 s
) external payable notContract {
// Get verification values
(
bytes32 domainSeparatorForPosition,
address traderForPosition
) = getDomainSeparatorAndTraderForPositionInternal(payload.positionId);
// Recover trader
address recoveredSigner = recoverCancelPendingLimitPositionSigner(
payload,
v,
r,
s,
domainSeparatorForPosition
);
// Sanity
require(
traderForPosition == recoveredSigner ||
isIntentPermittedByPositionId(
payload.positionId,
traderForPosition,
recoveredSigner
),
"NOT_SIGNED_BY_TRADER"
);
// Validate & Register Nonce
validateNonceForActionAndIncrease(
payload.positionId,
uint8(TradeIntentsVerifierActions.DIRECT_CANCEL_PENDING_LIMIT_POSITION),
payload.nonce
);
// Perform action
getTradersPortal().directAction_cancelPendingPosition_limit(
payload.positionId
);
// Event
emit TradeIntentVerified(
msg.sender,
TradeIntentsVerifierActions.DIRECT_CANCEL_PENDING_LIMIT_POSITION,
payload.positionId,
payload.nonce
);
}
// ***** Domain Separator Distinction *****
function getDomainSeparatorAndTraderForPositionInternal(
bytes32 _positionId
) internal returns (bytes32 domainSeparator, address trader) {
domainSeparator = domainSeparatorsForPosition[_positionId];
trader = tradersForPosition[_positionId];
if (domainSeparator == bytes32(0) || trader == address(0)) {
ITradingFloorV1 tradingFloor = getTradingFloor();
TradingFloorStructsV1.PositionIdentifiers
memory positionIdentifiers = tradingFloor.positionIdentifiersById(
_positionId
);
domainSeparator = getDomainSeparatorForAssetInternal(
positionIdentifiers.settlementAsset
);
trader = positionIdentifiers.trader;
require(domainSeparator != bytes32(0), "NO_DOMAIN_SEPARATOR_FOR_CHAIN");
require(trader != address(0), "NO_TRADER_FOR_POSITION");
domainSeparatorsForPosition[_positionId] = domainSeparator;
tradersForPosition[_positionId] = trader;
}
}
// ***** Domain Separator Distinction *****
function getSettlementAssetForPositionInternal(
bytes32 _positionId
) internal returns (address settlementAsset) {
settlementAsset = settlementAssetsForPosition[_positionId];
if (settlementAsset == address(0)) {
settlementAsset = getTradingFloor()
.positionIdentifiersById(_positionId)
.settlementAsset;
require(settlementAsset != address(0), "NO_SA_FOR_POSITION");
settlementAssetsForPosition[_positionId] = settlementAsset;
}
}
// ***** Intents Permissions *****
function isIntentPermittedByPositionId(
bytes32 positionId,
address owner,
address spender
) internal returns (bool) {
address settlementAsset = getSettlementAssetForPositionInternal(positionId);
return isIntentPermitted(settlementAsset, owner, spender);
}
function isIntentPermitted(
address settlementAsset,
address owner,
address spender
) internal view returns (bool) {
string memory dynRoleIntentsPermissionsSuffix = intentsPermissions[
OFTChip(settlementAsset)
];
if (bytes(dynRoleIntentsPermissionsSuffix).length == 0) {
return false;
}
IntentsPermissions intentsPermissionsContract = IntentsPermissions(
registry.getDynamicRoleAddress(
string(
abi.encodePacked(
DYN_ROLE_INTENTS_PERMISSIONS_PREFIX,
dynRoleIntentsPermissionsSuffix
)
)
)
);
if (address(intentsPermissionsContract) == address(0)) {
return false;
}
return
intentsPermissionsContract.permission(
PermissionsType.TRADING,
owner,
spender
);
}
// ***** Context Utils *****
function _msgSender() public view returns (address) {
return msg.sender;
}
// ***** Signed Payloads Utils *****
function hashOpenPositionPayload(
UserRequestPayload_OpenPosition memory payload
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(bytes(REQUEST_PAYLOAD_OPEN_POSITION_TYPE_DESCRIPTOR)),
payload.nonce,
hashPositionRequestIdentifiers(payload.positionRequestIdentifiers),
hashPositionRequestParams(payload.positionRequestParams),
payload.orderType
)
);
}
function hashPositionRequestIdentifiers(
ITradingFloorV1.PositionRequestIdentifiers memory payload
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(bytes(POSITION_REQUEST_IDENTIFIERS_TYPE_DESCRIPTOR)),
payload.trader,
payload.pairId,
payload.settlementAsset,
payload.positionIndex
)
);
}
function hashPositionRequestParams(
ITradingFloorV1.PositionRequestParams memory payload
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(bytes(POSITION_REQUEST_PARAMS_TYPE_DESCRIPTOR)),
payload.long,
payload.collateral,
payload.leverage,
payload.minPrice,
payload.maxPrice,
payload.tp,
payload.sl,
payload.tpByFraction,
payload.slByFraction
)
);
}
function hashCloseMarketPayload(
UserRequestPayload_CloseMarket memory payload
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(bytes(REQUEST_PAYLOAD_CLOSE_MARKET_TYPE_DESCRIPTOR)),
payload.nonce,
payload.positionId,
payload.minPrice,
payload.maxPrice
)
);
}
function hashUpdatePositionSingleFieldPayload(
UserRequestPayload_UpdatePositionSingleField memory payload
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(
bytes(REQUEST_PAYLOAD_UPDATE_POSITION_SINGLE_FIELD_TYPE_DESCRIPTOR)
),
payload.nonce,
payload.positionId,
payload.orderType,
payload.fieldValue
)
);
}
function hashUpdatePositionDoubleFieldPayload(
UserRequestPayload_UpdatePositionDoubleField memory payload
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(
bytes(REQUEST_PAYLOAD_UPDATE_POSITION_DOUBLE_FIELD_TYPE_DESCRIPTOR)
),
payload.nonce,
payload.positionId,
payload.orderType,
payload.fieldValueA,
payload.fieldValueB
)
);
}
function hashUpdatePendingLimitPositionPayload(
UserDirectPayload_UpdatePendingLimitPosition memory payload
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(
bytes(DIRECT_PAYLOAD_UPDATE_PENDING_LIMIT_POSITION_TYPE_DESCRIPTOR)
),
payload.nonce,
payload.positionId,
payload.minPrice,
payload.maxPrice,
payload.tp,
payload.sl
)
);
}
function hashCancelPendingLimitPositionPayload(
UserDirectPayload_CancelPendingLimitPosition memory payload
) internal pure returns (bytes32) {
return
keccak256(
abi.encode(
keccak256(
bytes(DIRECT_PAYLOAD_CANCEL_PENDING_LIMIT_POSITION_TYPE_DESCRIPTOR)
),
payload.nonce,
payload.positionId
)
);
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
contract ChipEnumsV1 {
enum ChipMode {
NONE,
LOCAL,
REMOTE,
HYBRID
}
}// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
interface IAffiliationV1 {
event PositionRequested(
bytes32 indexed domain,
bytes32 indexed referralCode,
bytes32 indexed positionId
);
event LiquidityProvided(
bytes32 indexed domain,
bytes32 indexed referralCode,
address indexed user,
uint amountUnderlying,
uint processingEpoch
);
}// 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;
/**
* @title IOnBehalfTradingV1
* @notice Interface for the OnBehalfTrading contract that manages sub-account trading permissions
* @dev Allows main accounts to grant partial trading permissions to sub-accounts (EOAs)
*/
interface IOnBehalfTradingV1 {
// ***** Structs *****
struct TradingPermission {
uint256 amountLimit; // Maximum amount that can be used for trading
uint256 amountUsed; // Amount already used
uint256 expiryTime; // Unix timestamp when permission expires
bool isActive; // Whether the permission is active
}
// ***** Events *****
event PermissionGranted(
address indexed owner,
address indexed spender,
address indexed token,
uint256 amountLimit,
uint256 expiryTime
);
event PermissionRevoked(
address indexed owner,
address indexed spender,
address indexed token
);
event AllPermissionsPermanentlyRevoked(
address indexed owner,
address indexed spender
);
event PermissionCharged(
address indexed owner,
address indexed spender,
address indexed token,
uint256 amountUsed,
uint256 remainingAmount
);
event PausedToggled(bool isPaused);
event MaxPermissionDurationUpdated(uint256 newMaxDuration);
event MaxPermissionAmountUpdatedForToken(
address indexed token,
uint256 newMaxAmount
);
event DynamicRoleCallerUpdated(address indexed caller, string roleName);
// ***** External Functions - Main Account Actions *****
/**
* @notice Grant trading permission to a sub-account for a specific token
* @param spender The address of the sub-account
* @param token The token (settlement asset) address
* @param amountLimit The maximum amount the sub-account can use
* @param duration The duration in seconds for which the permission is valid
*/
function grantPermission(
address spender,
address token,
uint256 amountLimit,
uint256 duration
) external;
/**
* @notice Revoke trading permission from a sub-account for a specific token
* @param spender The address of the sub-account
* @param token The token address
*/
function revokePermission(address spender, address token) external;
/**
* @notice Revoke all permissions from a sub-account permanently
* @dev This function is irreversible and permanently blocks future permissions to this sub-account
* @param spender The address of the sub-account
*/
function revokeAllPermissions(address spender) external;
// ***** External Functions - Permission Charging *****
/**
* @notice Charge permission for a sub-account to use collateral
* @dev Called by TradersPortal when a sub-account opens a position
* @param owner The main account that granted the permission
* @param spender The sub-account using the permission
* @param token The token (settlement asset) address
* @param amount The amount to charge against the permission
*/
function chargePermission(
address owner,
address spender,
address token,
uint256 amount
) external;
/**
* @notice Check if a sub-account has valid permission without charging
* @dev Called by TradersPortal when a sub-account manages positions
* @param owner The main account that granted the permission
* @param spender The sub-account
* @param token The token (settlement asset) address
*/
function requirePermission(
address owner,
address spender,
address token
) external view;
// ***** View Functions *****
/**
* @notice Get remaining amount for a permission
* @param owner The main account
* @param spender The sub-account
* @param token The token address
* @return The remaining amount
*/
function getRemainingAmount(
address owner,
address spender,
address token
) external view returns (uint256);
/**
* @notice Check if a permission is valid
* @param owner The main account
* @param spender The sub-account
* @param token The token address
* @return Whether the permission is valid
*/
function isPermissionValid(
address owner,
address spender,
address token
) external view returns (bool);
// ***** Public Variables *****
function isPaused() external view returns (bool);
function maxPermissionDuration() external view returns (uint256);
function maxPermissionAmountPerToken(
address token
) external view returns (uint256);
function permissions(
address owner,
address spender,
address token
)
external
view
returns (
uint256 amountLimit,
uint256 amountUsed,
uint256 expiryTime,
bool isActive
);
function permanentlyRevoked(
address owner,
address spender
) external view returns (bool);
function dynamicRoleCallers(
address caller
) external view returns (string memory);
// ***** Admin Functions *****
/**
* @notice Toggle the pause state
*/
function togglePause() external;
/**
* @notice Set the maximum permission duration
* @param _maxDuration The new maximum duration in seconds
*/
function setMaxPermissionDuration(uint256 _maxDuration) external;
/**
* @notice Set the maximum permission amount for a specific token
* @param token The token address
* @param _maxAmount The new maximum amount that can be granted (0 to remove limit)
*/
function setMaxPermissionAmountForToken(
address token,
uint256 _maxAmount
) external;
/**
* @notice Set the maximum permission amounts for multiple tokens
* @param tokens Array of token addresses
* @param maxAmounts Array of maximum amounts (0 to remove limit)
*/
function setMaxPermissionAmountsForTokens(
address[] calldata tokens,
uint256[] calldata maxAmounts
) external;
/**
* @notice Set a dynamic role for an authorized caller
* @param caller The address to configure
* @param roleName The dynamic role name in registry (empty string to remove)
*/
function setDynamicRoleCaller(
address caller,
string calldata roleName
) external;
/**
* @notice Set multiple dynamic roles for authorized callers
* @param callers Array of addresses to configure
* @param roleNames Array of dynamic role names (empty string to remove)
*/
function setDynamicRoleCallers(
address[] calldata callers,
string[] calldata roleNames
) external;
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "./OrderBookStructsV1.sol";
import "./TradingFloorStructsV1.sol";
interface IOrderBookFunctionalityV1 is OrderBookStructsV1 {
// Update Position Orders
function storeUpdatePositionSingleFieldOrder(
bytes32 _positionId,
UpdatePositionFieldOrderType orderType,
uint64 fieldValue
) external returns (UpdatePositionFieldOrder memory);
function storeUpdatePositionDoubleFieldOrder(
bytes32 _positionId,
UpdatePositionFieldOrderType orderType,
uint64 fieldValueA,
uint64 fieldValueB
) external returns (UpdatePositionFieldOrder memory);
function readAndDeleteUpdatePositionOrder(
bytes32 _positionId
) external returns (UpdatePositionFieldOrder memory order);
}
interface IOrderBookV1 is IOrderBookFunctionalityV1 {
function PRECISION() external pure returns (uint);
// *** Public Storage addresses ***
function tradingFloor() external view returns (address);
// *** Public Storage params ***
function pendingUpdateTradeFieldOrdersById(
bytes32 positionId
) external view returns (UpdatePositionFieldOrder memory);
}// 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: BUSL-1.1
pragma solidity ^0.8.24;
enum PriceValidatorType {
NONE,
PYTH,
FLARE
}
interface IPriceValidatorV1 {
// uint constant PRICE_SCALE = 1e8;
struct ValidatedPrice {
uint256 timestamp;
uint64 price; // Scaled to PRICE_SCALE
uint64 confidence; // Scaled to PRICE_SCALE
}
error NotSupportedError();
function isPriceValidator() external view returns (bool);
// Pyth price validator uses this to calculate the fee
function getUpdateFee(
bytes[] calldata updateData
) external view returns (uint256 feeAmount);
// Used by Flare price validator
function getUpdateFeeByPair(
uint256 pairIndex
) external view returns (uint256 feeAmount);
function validatePrice(
uint256 pairIndex,
bytes[] calldata updateData
) external payable returns (ValidatedPrice memory validatedPrice);
}// 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 "./ITradingFloorV1.sol";
import "./IOrderBookV1.sol";
interface ITradersPortalV1Functionality {
function traderRequest_openNewPosition(
ITradingFloorV1.PositionRequestIdentifiers
calldata positionRequestIdentifiers,
ITradingFloorV1.PositionRequestParams calldata positionRequestParams,
ITradingFloorV1.OpenOrderType orderType,
bytes32 domain,
bytes32 referralCode,
bool runCapTests
) external payable returns (bytes32);
function traderRequest_marketClosePosition(
bytes32 _positionId,
uint64 _minPrice,
uint64 _maxPrice
) external payable;
function traderRequest_updatePositionSingleField(
bytes32 _positionId,
OrderBookStructsV1.UpdatePositionFieldOrderType orderType,
uint64 fieldValue
) external payable;
function traderRequest_updatePositionDoubleField(
bytes32 _positionId,
OrderBookStructsV1.UpdatePositionFieldOrderType orderType,
uint64 fieldValueA,
uint64 fieldValueB
) external payable;
function directAction_updatePendingPosition_limit(
bytes32 positionId,
uint64 minPrice,
uint64 maxPrice,
uint64 tp,
uint64 sl
) external;
function directAction_cancelPendingPosition_limit(
bytes32 _positionId
) external;
}
interface ITradersPortalV1 is ITradersPortalV1Functionality {
// **** Public Storage params ****
function tradingFloor() 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;
// import "./ITokenV1.sol";
import "./TradingFloorStructsV1.sol";
interface OrderBookStructsV1 {
enum UpdatePositionFieldOrderType {
NONE,
UPDATE_TP,
UPDATE_SL,
UPDATE_TP_AND_SL
}
struct UpdatePositionFieldOrder {
// Slot 0
bytes32 positionId; // 32 bytes
// Slot 1
UpdatePositionFieldOrderType orderType; // 01 bytes
uint64 timestamp; // 08 bytes
uint64 fieldValueA; // 08 bytes
uint64 fieldValueB; // 08 bytes
}
}// 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 "../interfaces/IGlobalLock.sol";
/**
* @notice Common contract to handle the global system locks
* @dev This contract MUST NOT have any storage variables to not affect the storage layout
*/
contract SystemLocker {
address private immutable globalLock;
constructor(address _globalLock) {
globalLock = _globalLock;
}
// ***** Reentrancy Guard *****
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
_beforeNonReentrant();
_;
_afterNonReentrant();
}
/**
* @dev Tries to get the system lock
*/
function _beforeNonReentrant() private {
IGlobalLock(globalLock).lock();
}
/**
* @dev Releases the system lock
*/
function _afterNonReentrant() private {
IGlobalLock(globalLock).freeLock();
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
/**
* @title ConfidenceChecker
* @dev Base utility contract for storing confidence levels fractions for prices
*/
contract ConfidenceChecker {
// ***** Immutables *****
uint public immutable MAX_ALLOWED_CONFIDENCE_FRACTION;
// ***** Storage *****
mapping(uint => uint32) public maxConfidenceFractionForPair; // FRACTION_SCALE (5)
// ***** Events *****
event MaxConfidenceForPairSet(
uint indexed pairId,
uint maxConfidenceFraction
);
// ***** Constructor *****
constructor(uint _maxAllowedConfidenceFraction) {
MAX_ALLOWED_CONFIDENCE_FRACTION = _maxAllowedConfidenceFraction;
}
// ***** Internal Functions *****
function setMaxConfidenceForPairInternal(
uint _pairId,
uint32 _maxConfidenceFractionForPair
) internal {
require(
_maxConfidenceFractionForPair <= MAX_ALLOWED_CONFIDENCE_FRACTION,
"CONFIDENCE_FRACTION_TOO_HIGH"
);
maxConfidenceFractionForPair[_pairId] = _maxConfidenceFractionForPair;
emit MaxConfidenceForPairSet(_pairId, _maxConfidenceFractionForPair);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "../Common/CommonScales.sol";
/**
* @title PriceAdjustmentBase
* @dev Allows for adjustment of prices by using a simple spread mechanism
*/
contract PriceAdjustmentBase is CommonScales {
// ***** Immutables *****
uint public immutable MAX_ALLOWED_SPREAD_FRACTION; // FRACTION_SCALE (5)
// ***** Storage *****
mapping(uint => uint32) public spreadFractionForPair; // FRACTION_SCALE (5)
// ***** Events *****
event SpreadFractionForPairSet(uint indexed pairId, uint slippage);
// ***** Constructor *****
constructor(uint _maxAllowedSpreadReduction) {
MAX_ALLOWED_SPREAD_FRACTION = _maxAllowedSpreadReduction;
}
// ***** Internal Functions *****
function setSpreadFractionForPairInternal(
uint _pairId,
uint32 _spreadF
) internal {
require(_spreadF <= MAX_ALLOWED_SPREAD_FRACTION, "SPREAD_TOO_HIGH");
spreadFractionForPair[_pairId] = _spreadF;
emit SpreadFractionForPairSet(_pairId, _spreadF);
}
function calculatePostSpreadPrice(
uint pairId,
uint64 basePrice,
uint32 spreadReductionF,
bool increase
) internal view returns (uint64) {
require(spreadReductionF <= FRACTION_SCALE, "SPREAD_REDUCTION_TOO_HIGH");
uint64 spreadPart = uint64(
(spreadFractionForPair[pairId] * uint256(basePrice)) / FRACTION_SCALE
);
uint64 safeSpreadPart = spreadPart -
uint64(((spreadPart * spreadReductionF) / FRACTION_SCALE));
return increase ? basePrice + safeSpreadPart : basePrice - safeSpreadPart;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
/**
* @title TriggersPermissionBase
* @dev Allows for a basic whitelisting mechanism
*/
contract TriggersPermissionBase {
using EnumerableSet for EnumerableSet.AddressSet;
// ***** Storage *****
EnumerableSet.AddressSet private triggerPermissionSet;
// ***** Modifiers *****
modifier onlyAllowedTriggerAccount() {
require(isAllowedToTrigger(msg.sender), "NOT_ALLOWED_TO_TRIGGER");
_;
}
// ***** Events *****
event TriggerAccountAllowed(address indexed account);
event TriggerAccountDisallowed(address indexed account);
// ***** View *****
function isAllowedToTrigger(address account) public view returns (bool) {
return triggerPermissionSet.contains(account);
}
function getAllTriggerPermissionedAccounts()
public
view
returns (address[] memory)
{
return triggerPermissionSet.values();
}
// ***** Internal Functions *****
function allowTriggerAccountInternal(address account) internal {
require(!isAllowedToTrigger(account), "ACCOUNT_ALREADY_ALLOWED");
triggerPermissionSet.add(account);
emit TriggerAccountAllowed(account);
}
function disallowTriggerAccountInternal(address account) internal {
require(isAllowedToTrigger(account), "ACCOUNT_NOT_ALLOWED");
triggerPermissionSet.remove(account);
emit TriggerAccountDisallowed(account);
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "../interfaces/IRegistryV1.sol";
import "../interfaces/ITradingFloorV1.sol";
import "../interfaces/IPriceValidatorV1.sol";
import "../interfaces/IOrderBookV1.sol";
import "../../AdministrationContracts/ClaimableAdmin.sol";
import "./TriggersPermissionBase.sol";
import "./ConfidenceChecker.sol";
import "./PriceAdjustmentBase.sol";
import "../Locks/SystemLocker.sol";
/**
* @title TriggersV1
* @dev The main contract for handling triggers and executing trade requests and limits triggering
*/
contract TriggersV1 is
ClaimableAdmin,
TriggersPermissionBase,
ConfidenceChecker,
PriceAdjustmentBase,
SystemLocker
{
// ***** Contracts (Immutable) *****
ITradingFloorV1 public immutable tradingFloor;
IOrderBookV1 public immutable orderBook;
IPriceValidatorV1 public priceValidator;
// ***** Trigger Params *****
uint public minTriggerPeriodForMarketOrders = 3; // seconds
uint public maxTriggerPeriodForMarketOrders = 60; // seconds
uint public minTriggerPeriodForLimitOrders = 60; // seconds
uint public marketOrdersTimeout = 60; // seconds e.g 30
// @notice the range in which the market order can be accepted (range is [orderTimestamp, orderTimestamp + range] )
uint public marketOrderTightTimeRange = 60 * 3; // 5 seconds
// @notice the range in which a trigger reported price can accept(range is [blockTimestamp - triggerPriceFreshnessTimeRange, blockTimestamp] )
uint public triggerPriceFreshnessTimeRange = 60 * 30; // 30 minutes
uint public marketOrderCancelFeeFraction = (1 * FRACTION_SCALE) / 1000; // FRACTION_SCALE (0.001 = 0.01%)
uint public openPositionCancellationFeeFraction = (2 * FRACTION_SCALE) / 1000; // FRACTION_SCALE (0.002 = 0.02%)
uint public maxTriggersPerBlock = 3;
mapping(uint => uint) public triggersPerBlock;
// ***** Done/Pause state *****
bool public isPaused; // Prevent opening new trades
bool public isDone; // Prevent any interaction with the contract
// ***** Events *****
event PausedToggled(bool paused);
event DoneToggled(bool done);
event NumberUpdated(string indexed name, uint value);
event AddressUpdated(string indexed name, address value);
// Events
event OpenPositionExecuted(
address indexed triggerer,
bytes32 indexed positionId,
TradingEnumsV1.PositionPhase indexed phase,
uint triggerPrice,
uint basePrice,
uint priceTimestamp
);
event ClosePositionExecuted(
address indexed triggerer,
bytes32 indexed positionId,
TradingEnumsV1.PositionPhase indexed phase,
uint triggerPrice,
uint basePrice,
uint priceTimestamp
);
event SlExecuted(
address indexed triggerer,
bytes32 indexed positionId,
uint16 indexed pairId,
uint triggerPrice,
uint basePrice,
uint priceTimestamp
);
event TpExecuted(
address indexed triggerer,
bytes32 indexed positionId,
uint16 indexed pairId,
uint triggerPrice,
uint basePrice,
uint priceTimestamp
);
event UpdatePositionSingleFieldExecuted(
address indexed triggerer,
bytes32 indexed positionId,
OrderBookStructsV1.UpdatePositionFieldOrderType indexed orderType,
TradingEnumsV1.PositionField positionField,
uint256 fieldValue,
uint64 triggerPrice
);
event UpdatePositionSingleFieldRejected(
address indexed triggerer,
bytes32 indexed positionId,
OrderBookStructsV1.UpdatePositionFieldOrderType indexed orderType,
TradingEnumsV1.PositionField positionField,
uint256 fieldValue,
uint64 triggerPrice,
string rejectionReason,
uint256 rejectionValue
);
event LiquidationExecuted(
address indexed triggerer,
bytes32 indexed positionId,
uint16 indexed pairId,
uint triggerPrice,
uint basePrice,
uint priceTimestamp
);
event MarketOpenTimeoutTriggered(
address indexed triggerer,
bytes32 indexed positionId,
uint16 indexed pairId
);
event MarketCloseTimeoutTriggered(
address indexed triggerer,
bytes32 indexed positionId,
uint16 indexed pairId
);
event PositionUpdateTimeoutTriggered(
address indexed triggerer,
bytes32 indexed positionId,
OrderBookStructsV1.UpdatePositionFieldOrderType indexed orderType,
uint64 fieldValueA,
uint64 fieldValueB
);
// ***** Modifiers *****
modifier notDone() {
require(!isDone, "DONE");
_;
}
modifier notDoneOrPaused() {
require(!isDone, "DONE");
require(!isPaused, "PAUSED");
_;
}
// ***** Views *****
function getValidatedPrice(
uint pairId,
bytes[] calldata pricePayload
) public payable returns (IPriceValidatorV1.ValidatedPrice memory) {
return
validatePriceForPairWithSafeguardsInternal(
pairId,
msg.value,
pricePayload
);
}
// ***** Constructor *****
constructor(
ITradingFloorV1 _tradingFloor
)
ConfidenceChecker((FRACTION_SCALE * 10) / 100) // 10% max confidence
PriceAdjustmentBase((FRACTION_SCALE * 1) / 100) // 1% max spread
SystemLocker(_tradingFloor.registry())
{
require(address(_tradingFloor) != address(0), "WRONG_PARAMS");
tradingFloor = _tradingFloor;
orderBook = IOrderBookV1(IRegistryV1(_tradingFloor.registry()).orderBook());
}
// ***** Pause/Done (Admin) Toggles *****
function togglePause() external onlyAdmin {
isPaused = !isPaused;
emit PausedToggled(isPaused);
}
function toggleDone() external onlyAdmin {
isDone = !isDone;
emit DoneToggled(isDone);
}
// ***** Admin functions *****
function setPriceValidator(address _priceValidator) external onlyAdmin {
// Sanity
require(
IPriceValidatorV1(_priceValidator).isPriceValidator(),
"!PriceValidator"
);
// Setting
priceValidator = IPriceValidatorV1(_priceValidator);
emit AddressUpdated("PriceValidator", _priceValidator);
}
function allowTriggerAccount(address account) external onlyAdmin {
allowTriggerAccountInternal(account);
}
function disallowTriggerAccount(address account) external onlyAdmin {
disallowTriggerAccountInternal(account);
}
function setMaxConfidenceForPair(
uint pairId,
uint32 maxConfidenceFraction
) external onlyAdmin {
setMaxConfidenceForPairInternal(pairId, maxConfidenceFraction);
}
function setSpreadFractionForPair(
uint pairId,
uint32 spreadFraction
) external onlyAdmin {
setSpreadFractionForPairInternal(pairId, spreadFraction);
}
function setMinTriggerPeriodForMarketOrders(
uint _minTriggerPeriodForMarketOrders
) external onlyAdmin {
require(
_minTriggerPeriodForMarketOrders < maxTriggerPeriodForMarketOrders,
"WRONG_VALUE"
);
minTriggerPeriodForMarketOrders = _minTriggerPeriodForMarketOrders;
emit NumberUpdated(
"minTriggerPeriodForMarketOrders",
_minTriggerPeriodForMarketOrders
);
}
function setMaxTriggerPeriodForMarketOrders(
uint _maxTriggerPeriodForMarketOrders
) external onlyAdmin {
require(
_maxTriggerPeriodForMarketOrders > minTriggerPeriodForMarketOrders,
"WRONG_VALUE"
);
maxTriggerPeriodForMarketOrders = _maxTriggerPeriodForMarketOrders;
emit NumberUpdated(
"maxTriggerPeriodForMarketOrders",
_maxTriggerPeriodForMarketOrders
);
}
function setMinTriggerPeriodForLimitOrders(
uint _minTriggerPeriodForLimitOrders
) external onlyAdmin {
minTriggerPeriodForLimitOrders = _minTriggerPeriodForLimitOrders;
emit NumberUpdated(
"minTriggerPeriodForLimitOrders",
_minTriggerPeriodForLimitOrders
);
}
function setMarketOrdersTimeout(
uint _marketOrdersTimeout
) external onlyAdmin {
marketOrdersTimeout = _marketOrdersTimeout;
emit NumberUpdated("marketOrdersTimeout", _marketOrdersTimeout);
}
function setMarketOrderTightTimeRange(
uint _marketOrderTightTimeRange
) external onlyAdmin {
marketOrderTightTimeRange = _marketOrderTightTimeRange;
emit NumberUpdated("marketOrderTightTimeRange", _marketOrderTightTimeRange);
}
function setTriggerPriceFreshnessTimeRange(
uint _triggerPriceFreshnessTimeRange
) external onlyAdmin {
triggerPriceFreshnessTimeRange = _triggerPriceFreshnessTimeRange;
emit NumberUpdated(
"triggerPriceFreshnessTimeRange",
_triggerPriceFreshnessTimeRange
);
}
function setMarketOrderCancelFeeFraction(
uint _marketOrderCancelFeeFraction
) external onlyAdmin {
marketOrderCancelFeeFraction = _marketOrderCancelFeeFraction;
emit NumberUpdated(
"marketOrderCancelFeeFraction",
_marketOrderCancelFeeFraction
);
}
function setOpenPositionCancellationFeeFraction(
uint _openPositionCancellationFeeFraction
) external onlyAdmin {
openPositionCancellationFeeFraction = _openPositionCancellationFeeFraction;
emit NumberUpdated(
"openPositionCancellationFeeFraction",
_openPositionCancellationFeeFraction
);
}
function setMaxTriggersPerBlock(
uint _maxTriggersPerBlock
) external onlyAdmin {
maxTriggersPerBlock = _maxTriggersPerBlock;
emit NumberUpdated("maxTriggersPerBlock", _maxTriggersPerBlock);
}
// ***** Open Position Triggers *****
/**
* Triggers a openTrade at market price.
* @dev This function does not revert (as long as the price is valid and the pending order exists),
* in case of a failed condition for the trade order, The pending market order will be canceled.
*/
function trigger_openTrade_market(
bytes32 _positionId,
bytes[] calldata pricePayload
) external payable notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
(
TradingEnumsV1.PositionPhase phase,
uint timestamp,
uint16 pairId,
bool long,
uint32 spreadReductionF
) = tradingFloor.getPositionTriggerInfo(_positionId);
require(timestamp > 0, "NO_PENDING_MARKET_ORDER");
require(
phase == TradingEnumsV1.PositionPhase.OPEN_MARKET,
"NOT_OPEN_MARKET"
);
// ** Order price validity **
IPriceValidatorV1.ValidatedPrice
memory validatedPrice = validatePriceForPairWithSafeguardsInternal(
pairId,
msg.value,
pricePayload
);
// ** Market order timestamp validity **
validateMarketOrderTimestampInternal(timestamp, validatedPrice.timestamp);
uint64 priceAfterImpact = validatedPrice.price;
uint64 triggerPrice = calculatePostSpreadPrice(
pairId,
priceAfterImpact,
spreadReductionF,
long
);
safelyIncreaseTriggersPerBlock();
tradingFloor.openNewPosition_market(
_positionId,
triggerPrice,
openPositionCancellationFeeFraction
);
emit OpenPositionExecuted(
msg.sender,
_positionId,
phase,
triggerPrice,
validatedPrice.price,
validatedPrice.timestamp
);
}
function trigger_openTrade_limit(
bytes32 _positionId,
bytes[] calldata pricePayload
) external payable notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
(
TradingEnumsV1.PositionPhase phase,
uint timestamp,
uint16 pairId,
bool long,
uint32 spreadReductionF
) = tradingFloor.getPositionTriggerInfo(_positionId);
require(timestamp > 0, "NO_PENDING_LIMIT_ORDER");
require(phase == TradingEnumsV1.PositionPhase.OPEN_LIMIT, "NOT_OPEN_LIMIT");
// Order price validity
IPriceValidatorV1.ValidatedPrice
memory validatedPrice = validatePriceForPairWithSafeguardsInternal(
pairId,
msg.value,
pricePayload
);
// Limit order timestamp validity
validateLimitOrderTimestampInternal(timestamp, validatedPrice.timestamp);
uint64 priceAfterImpact = validatedPrice.price;
uint64 triggerPrice = calculatePostSpreadPrice(
pairId,
priceAfterImpact,
spreadReductionF,
long
);
safelyIncreaseTriggersPerBlock();
tradingFloor.openNewPosition_limit(
_positionId,
triggerPrice,
openPositionCancellationFeeFraction
);
emit OpenPositionExecuted(
msg.sender,
_positionId,
phase,
triggerPrice,
validatedPrice.price,
validatedPrice.timestamp
);
}
// ***** Close Position Triggers *****
function trigger_closeTrade_market(
bytes32 _positionId,
bytes[] calldata pricePayload
) external payable notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
(
TradingEnumsV1.PositionPhase phase,
uint timestamp,
uint16 pairId,
,
) = tradingFloor.getPositionTriggerInfo(_positionId);
require(timestamp > 0, "NO_PENDING_MARKET_ORDER");
require(
phase == TradingEnumsV1.PositionPhase.CLOSE_MARKET,
"NOT_CLOSE_MARKET"
);
// ** Market order price validity **
IPriceValidatorV1.ValidatedPrice
memory validatedPrice = validatePriceForPairWithSafeguardsInternal(
pairId,
msg.value,
pricePayload
);
// ** Market order timestamp validity **
validateMarketOrderTimestampInternal(timestamp, validatedPrice.timestamp);
uint64 priceAfterImpact = validatedPrice.price;
uint64 triggerPrice = priceAfterImpact;
safelyIncreaseTriggersPerBlock();
tradingFloor.closeExistingPosition_Market(
_positionId,
validatedPrice.price,
triggerPrice
);
emit ClosePositionExecuted(
msg.sender,
_positionId,
phase,
triggerPrice,
validatedPrice.price,
validatedPrice.timestamp
);
}
function trigger_closeTrade_SL(
bytes32 _positionId,
bytes[] calldata pricePayload
) external payable notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
(, , uint16 pairId, , ) = tradingFloor.getPositionTriggerInfo(_positionId);
TradingFloorStructsV1.PositionLimitsInfo memory limitInfo = tradingFloor
.positionLimitsInfoById(_positionId);
require(pairId > 0, "NO_SUCH_POSITION");
require(limitInfo.sl > 0, "NO_SL");
uint slLastUpdated = limitInfo.slLastUpdated;
// ** Price validity **
IPriceValidatorV1.ValidatedPrice
memory validatedPrice = validatePriceForPairWithSafeguardsInternal(
pairId,
msg.value,
pricePayload
);
validateLimitOrderTimestampInternal(
slLastUpdated,
validatedPrice.timestamp
);
uint64 triggerPrice = validatedPrice.price;
safelyIncreaseTriggersPerBlock();
tradingFloor.closeExistingPosition_Limit(
_positionId,
TradingEnumsV1.LimitTrigger.SL,
validatedPrice.price,
triggerPrice
);
emit SlExecuted(
msg.sender,
_positionId,
pairId,
triggerPrice,
validatedPrice.price,
validatedPrice.timestamp
);
}
function trigger_closeTrade_TP(
bytes32 _positionId,
bytes[] calldata pricePayload
) external payable notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
(, , uint16 pairId, , ) = tradingFloor.getPositionTriggerInfo(_positionId);
TradingFloorStructsV1.PositionLimitsInfo memory limitInfo = tradingFloor
.positionLimitsInfoById(_positionId);
require(pairId > 0, "NO_SUCH_POSITION");
require(limitInfo.tp > 0, "NO_TP");
uint tpLastUpdated = limitInfo.tpLastUpdated;
// ** Price validity **
IPriceValidatorV1.ValidatedPrice
memory validatedPrice = validatePriceForPairWithSafeguardsInternal(
pairId,
msg.value,
pricePayload
);
validateLimitOrderTimestampInternal(
tpLastUpdated,
validatedPrice.timestamp
);
uint64 triggerPrice = validatedPrice.price;
safelyIncreaseTriggersPerBlock();
tradingFloor.closeExistingPosition_Limit(
_positionId,
TradingEnumsV1.LimitTrigger.TP,
validatedPrice.price,
triggerPrice
);
emit TpExecuted(
msg.sender,
_positionId,
pairId,
triggerPrice,
validatedPrice.price,
validatedPrice.timestamp
);
}
function trigger_closeTrade_LIQ(
bytes32 _positionId,
bytes[] calldata pricePayload
) external payable notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
(, , uint16 pairId, , ) = tradingFloor.getPositionTriggerInfo(_positionId);
require(pairId > 0, "NO_SUCH_POSITION");
IPriceValidatorV1.ValidatedPrice
memory validatedPrice = validatePriceForPairWithSafeguardsInternal(
pairId,
msg.value,
pricePayload
);
uint64 triggerPrice = validatedPrice.price;
safelyIncreaseTriggersPerBlock();
tradingFloor.closeExistingPosition_Limit(
_positionId,
TradingEnumsV1.LimitTrigger.LIQ,
validatedPrice.price,
triggerPrice
);
emit LiquidationExecuted(
msg.sender,
_positionId,
pairId,
triggerPrice,
validatedPrice.price,
validatedPrice.timestamp
);
}
// ***** Update Position Triggers *****
function trigger_update_TP(
bytes32 _positionId,
bytes[] calldata pricePayload
) external payable notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
OrderBookStructsV1.UpdatePositionFieldOrder memory o = orderBook
.readAndDeleteUpdatePositionOrder(_positionId);
require(
o.orderType == OrderBookStructsV1.UpdatePositionFieldOrderType.UPDATE_TP,
"UPDATE_ORDER_NOT_TP"
);
(, , uint16 pairId, , ) = tradingFloor.getPositionTriggerInfo(_positionId);
IPriceValidatorV1.ValidatedPrice
memory validatedPrice = validatePriceForPairWithSafeguardsInternal(
pairId,
msg.value,
pricePayload
);
// ** Market order timestamp validity **
validateMarketOrderTimestampInternal(o.timestamp, validatedPrice.timestamp);
safelyIncreaseTriggersPerBlock();
uint64 triggerPrice = validatedPrice.price;
safePositionSingleFieldUpdateInternal(
msg.sender,
_positionId,
o.orderType,
TradingEnumsV1.PositionField.TP,
o.fieldValueA,
triggerPrice
);
}
function trigger_update_SL(
bytes32 _positionId,
bytes[] calldata pricePayload
) external payable notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
OrderBookStructsV1.UpdatePositionFieldOrder memory o = orderBook
.readAndDeleteUpdatePositionOrder(_positionId);
require(
o.orderType == OrderBookStructsV1.UpdatePositionFieldOrderType.UPDATE_SL,
"UPDATE_ORDER_NOT_SL"
);
(, , uint16 pairId, , ) = tradingFloor.getPositionTriggerInfo(_positionId);
IPriceValidatorV1.ValidatedPrice
memory validatedPrice = validatePriceForPairWithSafeguardsInternal(
pairId,
msg.value,
pricePayload
);
// ** Market order timestamp validity **
validateMarketOrderTimestampInternal(o.timestamp, validatedPrice.timestamp);
safelyIncreaseTriggersPerBlock();
uint64 triggerPrice = validatedPrice.price;
safePositionSingleFieldUpdateInternal(
msg.sender,
_positionId,
o.orderType,
TradingEnumsV1.PositionField.SL,
o.fieldValueA,
triggerPrice
);
}
function trigger_update_TP_and_SL(
bytes32 _positionId,
bytes[] calldata pricePayload
) external payable notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
OrderBookStructsV1.UpdatePositionFieldOrder memory o = orderBook
.readAndDeleteUpdatePositionOrder(_positionId);
require(
o.orderType ==
OrderBookStructsV1.UpdatePositionFieldOrderType.UPDATE_TP_AND_SL,
"UPDATE_ORDER_NOT_TP_AND_SL"
);
(, , uint16 pairId, , ) = tradingFloor.getPositionTriggerInfo(_positionId);
IPriceValidatorV1.ValidatedPrice
memory validatedPrice = validatePriceForPairWithSafeguardsInternal(
pairId,
msg.value,
pricePayload
);
// ** Market order timestamp validity **
validateMarketOrderTimestampInternal(o.timestamp, validatedPrice.timestamp);
safelyIncreaseTriggersPerBlock();
uint64 triggerPrice = validatedPrice.price;
// Update TP
require(
safePositionSingleFieldUpdateInternal(
msg.sender,
_positionId,
o.orderType,
TradingEnumsV1.PositionField.TP,
o.fieldValueA,
triggerPrice
),
"FAILED_TP_UPDATE"
);
// Update SL
require(
safePositionSingleFieldUpdateInternal(
msg.sender,
_positionId,
o.orderType,
TradingEnumsV1.PositionField.SL,
o.fieldValueB,
triggerPrice
),
"FAILED_SL_UPDATE"
);
}
function trigger_timeout_updatePosition(
bytes32 _positionId
) external notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
OrderBookStructsV1.UpdatePositionFieldOrder memory o = orderBook
.readAndDeleteUpdatePositionOrder(_positionId);
require(
block.timestamp >= o.timestamp + marketOrdersTimeout,
"WAIT_TIMEOUT"
);
emit PositionUpdateTimeoutTriggered(
msg.sender,
_positionId,
o.orderType,
o.fieldValueA,
o.fieldValueB
);
}
function safePositionSingleFieldUpdateInternal(
address triggerer,
bytes32 _positionId,
OrderBookStructsV1.UpdatePositionFieldOrderType orderType,
TradingEnumsV1.PositionField positionField,
uint64 fieldValue,
uint64 triggerPrice
) internal returns (bool) {
try
tradingFloor.updateOpenedPosition(
_positionId,
positionField,
fieldValue,
triggerPrice
)
{
emit UpdatePositionSingleFieldExecuted(
triggerer,
_positionId,
orderType,
positionField,
fieldValue,
triggerPrice
);
return true;
} catch Error(string memory error) {
// Note : Will happen from Normal 'require'
emit UpdatePositionSingleFieldRejected(
triggerer,
_positionId,
orderType,
positionField,
fieldValue,
triggerPrice,
error,
0
);
return false;
} catch (bytes memory err) {
// CapError (should only happen when updating TP)
if (bytes4(err) == LexErrors.CapError.selector) {
require(
positionField == TradingEnumsV1.PositionField.TP,
"CAP_ERROR_NOT_ON_TP"
);
LexErrors.CapType capType;
uint256 value;
assembly {
capType := mload(add(err, 0x24))
value := mload(add(err, 0x44))
}
emit UpdatePositionSingleFieldRejected(
triggerer,
_positionId,
orderType,
positionField,
fieldValue,
triggerPrice,
"CAP_ERROR",
uint(capType)
);
return false;
} else {
revert("UNKNOWN_CUSTOM_ERROR");
}
}
}
// ***** Market Requests Timeout Triggers *****
function trigger_timeout_marketOpen(
bytes32 _positionId
) external notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
(
TradingEnumsV1.PositionPhase phase,
uint timestamp,
uint16 pairId,
,
) = tradingFloor.getPositionTriggerInfo(_positionId);
require(timestamp > 0, "NO_SUCH_POSITION");
require(
phase == TradingEnumsV1.PositionPhase.OPEN_MARKET,
"NOT_OPEN_MARKET"
);
require(block.timestamp >= timestamp + marketOrdersTimeout, "WAIT_TIMEOUT");
tradingFloor.cancelPendingPosition(
_positionId,
TradingEnumsV1.OpenOrderType.MARKET,
marketOrderCancelFeeFraction
);
emit MarketOpenTimeoutTriggered(msg.sender, _positionId, pairId);
}
function trigger_timeout_marketClose(
bytes32 _positionId
) external notDoneOrPaused onlyAllowedTriggerAccount nonReentrant {
(
TradingEnumsV1.PositionPhase phase,
uint timestamp,
uint16 pairId,
,
) = tradingFloor.getPositionTriggerInfo(_positionId);
require(timestamp > 0, "NO_SUCH_POSITION");
require(
phase == TradingEnumsV1.PositionPhase.CLOSE_MARKET,
"NOT_CLOSE_MARKET"
);
require(block.timestamp >= timestamp + marketOrdersTimeout, "WAIT_TIMEOUT");
tradingFloor.cancelMarketCloseForPosition(
_positionId,
TradingEnumsV1.CloseOrderType.MARKET,
marketOrderCancelFeeFraction
);
emit MarketCloseTimeoutTriggered(msg.sender, _positionId, pairId);
}
// ***** Price Validations Utils *****
/**
* Validates the payload and reverts if the price confidence is too high
*/
function validatePriceForPairWithSafeguardsInternal(
uint pairId,
uint nativePayment,
bytes[] calldata pricePayload
) internal returns (IPriceValidatorV1.ValidatedPrice memory) {
IPriceValidatorV1.ValidatedPrice
memory validatedPrice = validatePriceForPairInternal(
pairId,
nativePayment,
pricePayload
);
uint maxConfidenceF = maxConfidenceFractionForPair[pairId];
uint maxAllowedConfidence = calculateFractionInternal(
uint(validatedPrice.price),
maxConfidenceF
);
require(
validatedPrice.confidence <= maxAllowedConfidence,
"CONFIDENCE_RANGE_TOO_WIDE"
);
require(
validatedPrice.timestamp <= block.timestamp,
"FUTURE_PRICE_REPORTED"
);
return validatedPrice;
}
function validatePriceForPairInternal(
uint pairIndex,
uint nativePayment,
bytes[] calldata pricePayload
) internal returns (IPriceValidatorV1.ValidatedPrice memory) {
return
priceValidator.validatePrice{value: nativePayment}(
pairIndex,
pricePayload
);
}
/**
* The time frame for triggering market orders is [orderTimestamp + minTriggerPeriodForMarketOrders, orderTimestamp + maxTriggerPeriodForMarketOrders]
* Both the block.timestamp and the price timestamp MUST be withing this frame
*/
function validateMarketOrderTimestampInternal(
uint pendingMarketOrderTimestamp,
uint priceTimestamp
) internal view {
uint orderActivationEarliestTimestamp = pendingMarketOrderTimestamp +
minTriggerPeriodForMarketOrders;
uint orderActivationLatestTimestamp = pendingMarketOrderTimestamp +
maxTriggerPeriodForMarketOrders;
require(
block.timestamp >= orderActivationEarliestTimestamp,
"MARKET_ORDER_TRIGGER_TOO_SOON"
);
require(
block.timestamp <= orderActivationLatestTimestamp,
"MARKET_ORDER_TRIGGER_TOO_LATE"
);
require(
priceTimestamp >= orderActivationEarliestTimestamp &&
priceTimestamp <= orderActivationLatestTimestamp,
"MARKET_ORDER_PRICE_OUT_OF_TIME_FRAME"
);
}
function validateLimitOrderTimestampInternal(
uint pendingLimitOrderTimestamp,
uint priceTimestamp
) internal view {
// ** Limit order timestamp validity **
uint orderActivationEarliestTimestamp = pendingLimitOrderTimestamp +
minTriggerPeriodForLimitOrders;
require(
block.timestamp >= orderActivationEarliestTimestamp,
"LIMIT_ORDER_TRIGGER_TOO_SOON"
);
// The price must be reported after the limit order activation timestamp
require(
priceTimestamp >= orderActivationEarliestTimestamp,
"LIMIT_ORDER_PRICE_OUT_OF_TIME_FRAME"
);
// The reported price cannot be too long in the past
validateTriggerPriceRecentInternal(
priceTimestamp,
triggerPriceFreshnessTimeRange
);
}
/**
* @notice ensures the given timestamp is not older than the given window (in seconds)
*/
function validateTriggerPriceRecentInternal(
uint priceTimestamp,
uint acceptedWindow
) internal view {
uint oldestTimestamp = block.timestamp - acceptedWindow;
require(priceTimestamp >= oldestTimestamp, "PRICE_TOO_OLD");
// Sanity, price cannot be from the future
require(priceTimestamp <= block.timestamp, "PRICE_TOO_NEW");
}
// ***** Limitation functions *****
function safelyIncreaseTriggersPerBlock() internal {
uint currentBlockTriggers = triggersPerBlock[block.number];
require(
currentBlockTriggers < maxTriggersPerBlock,
"MAX_TRIGGERS_PER_BLOCK"
);
triggersPerBlock[block.number] = currentBlockTriggers + 1;
}
// ***** Internal Utils *****
function calculateFractionInternal(
uint amount,
uint fraction
) internal pure returns (uint) {
return (amount * fraction) / FRACTION_SCALE;
}
}// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.24;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IOAppComposer} from "@layerzerolabs/lz-evm-oapp-v2/contracts/oapp/interfaces/IOAppComposer.sol";
import {OFTComposeMsgCodec} from "@layerzerolabs/lz-evm-oapp-v2/contracts/oft/libs/OFTComposeMsgCodec.sol";
import "../../AdministrationContracts/ClaimableAdmin.sol";
import "../../Lynx/Chips/OFTChip/OFTChip.sol";
uint8 constant PERMISSIONS_SIZE = 4; // @dev Change PERMISSIONS_SIZE when changing the enum
enum PermissionsType {
// @dev NEVER CHANGE THE ORDER OF THIS ENUM!
NONE,
TRADING,
LIQUIDITY,
CHIP_OUT
}
struct IntentsPermissionsMsg {
bool allow;
PermissionsType permissionsType;
address spender;
}
/**
* @title IntentsPermissions
* @notice Holds permissions for signing intents on behalf of another account
*/
contract IntentsPermissions is IOAppComposer, ClaimableAdmin {
using SafeERC20 for IERC20;
// ***** Events *****
event IntentsPermissionsSet(
PermissionsType indexed permissionsType,
address indexed owner,
address indexed spender,
bool allow
);
event AllowedCreatePermissionsSet(address indexed owner, bool allowed);
event TokensSwept(
address indexed token,
address indexed receiver,
uint256 amount
);
event NativeSwept(address indexed receiver, uint256 amount);
// ***** Immutable Storage *****
OFTChip public immutable oftChip;
IERC20 public immutable oftChipToken;
// ***** Storage *****
// Owner address => isAllowed
mapping(address => bool) public allowedCreatePermissions;
// PermissionsType => owner address => spender address => is approved
mapping(address => mapping(address => bool))[PERMISSIONS_SIZE]
public permissions;
// ***** Views *****
function isAllowedCreatePermissions(
address owner
) public view returns (bool) {
return allowedCreatePermissions[owner];
}
function permission(
PermissionsType permissionsType,
address owner,
address spender
) public view returns (bool) {
return permissions[uint256(permissionsType)][owner][spender];
}
// ***** Constructor *****
constructor(address _oftChip) {
require(_oftChip != address(0), "INVALID_OFT_CHIP");
oftChip = OFTChip(_oftChip);
oftChipToken = IERC20(oftChip.token());
}
// ***** Admin Functions *****
/// @notice Sets the allowedCreatePermissions flag.
/// @param _allowedCreatePermissions The new allowedCreatePermissions flag.
function setAllowedCreatePermissions(
address _allowedCreatePermissions,
bool _allowed
) external onlyAdmin {
allowedCreatePermissions[_allowedCreatePermissions] = _allowed;
emit AllowedCreatePermissionsSet(_allowedCreatePermissions, _allowed);
}
/**
* @notice Sweep any non-underlying tokens from the contract
* @dev Owner can sweep any tokens, this contract should not hold any tokens
* @param _token The token to sweep
* @param _amount The amount to sweep
*/
function sweepTokens(IERC20 _token, uint256 _amount) external onlyAdmin {
_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);
emit NativeSwept(admin, _amount);
}
// ***** External Functions *****
/// @notice Handles incoming composed messages from LayerZero.
/// @dev Decodes the message payload to perform intents permission setting and pass tokens to the owner.
/// This method expects the encoded compose message to contain the permissions type, spender and a flag to turn on/off permissions.
/// @param oApp The address of the originating OApp.
/// @param /*guid*/ The globally unique identifier of the message (unused).
/// @param message The encoded message content in the format of the OFTComposeMsgCodec.
/// @param /*Executor*/ Executor address (unused).
/// @param /*Executor Data*/ Additional data for checking for a specific executor (unused).
function lzCompose(
address oApp,
bytes32 /*guid*/,
bytes calldata message,
address /*Executor*/,
bytes calldata /*Executor Data*/
) external payable override {
require(oApp == address(oftChip), "INVALID_OAPP_RECEIVED");
require(
msg.sender == address(oftChip.endpoint()),
"INVALID_ENDPOINT_RECEIVED"
);
// Transfer chips to the sender
uint256 amountLD = OFTComposeMsgCodec.amountLD(message);
address owner = OFTComposeMsgCodec.bytes32ToAddress(
OFTComposeMsgCodec.composeFrom(message)
);
oftChipToken.safeTransfer(owner, amountLD);
// Extract the composed message from the delivered message using the MsgCodec
IntentsPermissionsMsg memory intentsPermissionsMsg = abi.decode(
OFTComposeMsgCodec.composeMsg(message),
(IntentsPermissionsMsg)
);
// Check if the owner is allowed to create permissions, always allow to set permissions off
if (!allowedCreatePermissions[owner] && intentsPermissionsMsg.allow) {
return;
}
permissions[uint256(intentsPermissionsMsg.permissionsType)][owner][
intentsPermissionsMsg.spender
] = intentsPermissionsMsg.allow;
// Emit an event to log the given permission
emit IntentsPermissionsSet(
intentsPermissionsMsg.permissionsType,
owner,
intentsPermissionsMsg.spender,
intentsPermissionsMsg.allow
);
}
function setPermissionForSpender(
PermissionsType _permissionsType,
address _spender,
bool _allow
) external {
address owner = msg.sender;
// Check if the owner is allowed to create permissions, always allow to set permissions off
if (!allowedCreatePermissions[owner] && _allow) {
revert("NOT_ALLOWED");
}
// State
require(
permissions[uint256(_permissionsType)][owner][_spender] != _allow,
"ALREADY_SET"
);
permissions[uint256(_permissionsType)][owner][_spender] = _allow;
// Event
emit IntentsPermissionsSet(_permissionsType, owner, _spender, _allow);
}
}{
"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[{"inputs":[{"internalType":"contract ITradingFloorV1","name":"_tradingFloor","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"enum TradersPortalV1.TradersPortalActions","name":"action","type":"uint8"},{"indexed":false,"internalType":"uint256","name":"requiredFee","type":"uint256"}],"name":"ActionFeeSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"done","type":"bool"}],"name":"DoneToggled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"done","type":"bool"}],"name":"IsLimitingMarketClosePriceRangeToggled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"domain","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"referralCode","type":"bytes32"},{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"amountUnderlying","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"processingEpoch","type":"uint256"}],"name":"LiquidityProvided","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"NewAdmin","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldPendingAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newPendingAdmin","type":"address"}],"name":"NewPendingAdmin","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"name","type":"string"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"NumberUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"trader","type":"address"},{"indexed":false,"internalType":"bool","name":"enabled","type":"bool"}],"name":"OnBehalfActivatedToggled","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bool","name":"paused","type":"bool"}],"name":"PausedToggled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"positionId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"PendingMarketCloseOrderTimeoutCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"positionId","type":"bytes32"},{"indexed":true,"internalType":"address","name":"caller","type":"address"}],"name":"PendingMarketOpenOrderTimeoutCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"positionId","type":"bytes32"}],"name":"PendingOpenLimitPositionCancelled","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"domain","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"referralCode","type":"bytes32"},{"indexed":true,"internalType":"bytes32","name":"positionId","type":"bytes32"}],"name":"PositionRequested","type":"event"},{"inputs":[],"name":"ACCURACY_IMPROVEMENT_SCALE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"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":"DYN_ROLE_ON_BEHALF_TRADING","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"FRACTION_SCALE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"LEVERAGE_SCALE","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"NATIVE_UNDERLYING_ADDRESS","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PRECISION","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"_acceptAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"_msgSender","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"newPendingAdmin","type":"address"}],"name":"_setPendingAdmin","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"enum TradersPortalV1.TradersPortalActions","name":"","type":"uint8"}],"name":"actionFees","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"admin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address payable","name":"_to","type":"address"}],"name":"collectNativeFees","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_positionId","type":"bytes32"}],"name":"directAction_cancelPendingPosition_limit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_positionId","type":"bytes32"}],"name":"directAction_timeout_closeMarket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_positionId","type":"bytes32"}],"name":"directAction_timeout_openMarket","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_positionId","type":"bytes32"}],"name":"directAction_timeout_updateTradeField","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"positionId","type":"bytes32"},{"internalType":"uint64","name":"minPrice","type":"uint64"},{"internalType":"uint64","name":"maxPrice","type":"uint64"},{"internalType":"uint64","name":"tp","type":"uint64"},{"internalType":"uint64","name":"sl","type":"uint64"}],"name":"directAction_updatePendingPosition_limit","outputs":[],"stateMutability":"nonpayable","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":[],"name":"getOnBehalfTrading","outputs":[{"internalType":"address","name":"onBehalfTrading","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getOrderBook","outputs":[{"internalType":"contract IOrderBookV1","name":"orderBook","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getTradeIntentsVerifier","outputs":[{"internalType":"address","name":"tradeIntentsVerifier","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isDone","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isLimitingMarketClosePriceRange","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"limitOrdersTimelock","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"marketOrdersTimeout","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"minLiveTimeForMarketClose","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"onBehalfActivated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"pendingAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"registry","outputs":[{"internalType":"contract IRegistryV1","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"setLimitOrdersTimelock","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"setMarketOrdersTimeout","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"value","type":"uint256"}],"name":"setMinLiveTimeForMarketClose","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"enum TradersPortalV1.TradersPortalActions","name":"action","type":"uint8"},{"internalType":"uint256","name":"requiredFee","type":"uint256"}],"name":"setNativeFeeForAction","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"enabled","type":"bool"}],"name":"setOnBehalfActivated","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"toggleDone","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"toggleLimitCloseOrdersRange","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"togglePause","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_positionId","type":"bytes32"},{"internalType":"uint64","name":"_minPrice","type":"uint64"},{"internalType":"uint64","name":"_maxPrice","type":"uint64"}],"name":"traderRequest_marketClosePosition","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"trader","type":"address"},{"internalType":"uint16","name":"pairId","type":"uint16"},{"internalType":"address","name":"settlementAsset","type":"address"},{"internalType":"uint32","name":"positionIndex","type":"uint32"}],"internalType":"struct TradingFloorStructsV1.PositionRequestIdentifiers","name":"positionRequestIdentifiers","type":"tuple"},{"components":[{"internalType":"bool","name":"long","type":"bool"},{"internalType":"uint256","name":"collateral","type":"uint256"},{"internalType":"uint32","name":"leverage","type":"uint32"},{"internalType":"uint64","name":"minPrice","type":"uint64"},{"internalType":"uint64","name":"maxPrice","type":"uint64"},{"internalType":"uint64","name":"tp","type":"uint64"},{"internalType":"uint64","name":"sl","type":"uint64"},{"internalType":"uint64","name":"tpByFraction","type":"uint64"},{"internalType":"uint64","name":"slByFraction","type":"uint64"}],"internalType":"struct TradingFloorStructsV1.PositionRequestParams","name":"positionRequestParams","type":"tuple"},{"internalType":"enum TradingEnumsV1.OpenOrderType","name":"orderType","type":"uint8"},{"internalType":"bytes32","name":"domain","type":"bytes32"},{"internalType":"bytes32","name":"referralCode","type":"bytes32"},{"internalType":"bool","name":"runCapTests","type":"bool"}],"name":"traderRequest_openNewPosition","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_positionId","type":"bytes32"},{"internalType":"enum OrderBookStructsV1.UpdatePositionFieldOrderType","name":"orderType","type":"uint8"},{"internalType":"uint64","name":"fieldValueA","type":"uint64"},{"internalType":"uint64","name":"fieldValueB","type":"uint64"}],"name":"traderRequest_updatePositionDoubleField","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"_positionId","type":"bytes32"},{"internalType":"enum OrderBookStructsV1.UpdatePositionFieldOrderType","name":"orderType","type":"uint8"},{"internalType":"uint64","name":"fieldValue","type":"uint64"}],"name":"traderRequest_updatePositionSingleField","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"tradingFloor","outputs":[{"internalType":"contract ITradingFloorV1","name":"","type":"address"}],"stateMutability":"view","type":"function"}]Contract Creation Code
60e0604052600280546001600160a01b03191673eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee1790553480156200003757600080fd5b50604051620055be380380620055be8339810160408190526200005a91620001be565b806001600160a01b0316637b1039996040518163ffffffff1660e01b8152600401602060405180830381865afa15801562000099573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620000bf9190620001be565b600080546001600160a01b031916331790556001600160a01b039081166080528116620001215760405162461bcd60e51b815260206004820152600c60248201526b57524f4e475f504152414d5360a01b604482015260640160405180910390fd5b6001600160a01b03811660a081905260408051637b10399960e01b81529051637b103999916004808201926020929091908290030181865afa1580156200016c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190620001929190620001be565b6001600160a01b031660c05250620001e5565b6001600160a01b0381168114620001bb57600080fd5b50565b600060208284031215620001d157600080fd5b8151620001de81620001a5565b9392505050565b60805160a05160c0516152c9620002f56000396000818161050d015281816109cb01528181610c3501528181610d4701528181610ec90152818161120f01528181611509015281816116830152818161187001528181611a7101528181611d650152818161235d01526123c40152600081816102ff01528181610ff70152818161115d015281816113150152818161145001528181611b7701528181611cb301528181611e24015281816124ef015281816126780152818161276501528181612ef701528181612fac0152818161316c01528181613250015281816133fb0152818161358c015281816136590152818161374b01526137d50152600081816126f1015261290801526152c96000f3fe60806040526004361061027d5760003560e01c80638f0622271161014f578063b71f3cfe116100c1578063e9c714f21161007a578063e9c714f214610799578063f5f5ba72146107ae578063f714bdc2146107e6578063f851a440146107fb578063f86d29481461081b578063fd4a2c431461083b57600080fd5b8063b71f3cfe146106df578063b81bfa05146106f7578063c4ae316814610717578063d060576b1461072c578063d33b671614610759578063d4a1caa71461077957600080fd5b8063ad1f2b5611610113578063ad1f2b561461063b578063b187bd2614610650578063b248c4ef1461066a578063b26d1b911461067f578063b48ae6361461069f578063b71d1a0c146106bf57600080fd5b80638f06222714610573578063922e2db4146105a2578063a6eb0a78146105c2578063aaf5eb68146105e2578063ac2bff1f146105fe57600080fd5b8063410c0b7c116101f35780636b8b5e22116101ac5780636b8b5e22146104c0578063719683ea146104d357806372f8c620146104e65780637b103999146104fb57806380193b261461052f5780638aa104351461054657600080fd5b8063410c0b7c14610406578063441762661461041c578063441f64bb1461042f578063568b6add14610445578063609393c714610465578063614d08f81461048557600080fd5b80631d3e4d46116102455780631d3e4d461461034c578063217cf74f1461035f578063267822471461037f5780632904fb4b1461039f57806338b90333146103b45780633be3d626146103f157600080fd5b80630310a65b146102825780630890d22a146102a45780630c7d4d8b146102cd5780630d3b0b76146102ed578063119df25f14610339575b600080fd5b34801561028e57600080fd5b506102a261029d366004614629565b61086b565b005b3480156102b057600080fd5b506102ba60035481565b6040519081526020015b60405180910390f35b3480156102d957600080fd5b506102a26102e8366004614663565b610920565b3480156102f957600080fd5b506103217f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020016102c4565b34801561034557600080fd5b5033610321565b6102a261035a3660046146ab565b6109c0565b34801561036b57600080fd5b506102a261037a3660046146ed565b610b38565b34801561038b57600080fd5b50600154610321906001600160a01b031681565b3480156103ab57600080fd5b50610321610bf5565b3480156103c057600080fd5b506103e4604051806040016040528060048152602001630313031360e41b81525081565b6040516102c49190614706565b3480156103fd57600080fd5b506102a2610cae565b34801561041257600080fd5b506102ba60045481565b6102ba61042a366004614755565b610d3a565b34801561043b57600080fd5b506102ba60055481565b34801561045157600080fd5b506102a26104603660046146ed565b610ebe565b34801561047157600080fd5b506102a26104803660046146ed565b611204565b34801561049157600080fd5b506103e46040518060400160405280600f81526020016e54726164657273506f7274616c563160881b81525081565b6102a26104ce3660046147d9565b6114fe565b6102a26104e136600461482c565b611678565b3480156104f257600080fd5b506102a26117e1565b34801561050757600080fd5b506103217f000000000000000000000000000000000000000000000000000000000000000081565b34801561053b57600080fd5b506102ba620186a081565b34801561055257600080fd5b506040805180820190915260048152630313031360e41b60208201526103e4565b34801561057f57600080fd5b5060075461059290610100900460ff1681565b60405190151581526020016102c4565b3480156105ae57600080fd5b506102a26105bd3660046146ed565b611865565b3480156105ce57600080fd5b506102a26105dd3660046146ed565b611a66565b3480156105ee57600080fd5b506102ba670de0b6b3a764000081565b34801561060a57600080fd5b506103e4604051806040016040528060118152602001704f4e5f424548414c465f54524144494e4760781b81525081565b34801561064757600080fd5b506102ba606481565b34801561065c57600080fd5b506007546105929060ff1681565b34801561067657600080fd5b50610321611d61565b34801561068b57600080fd5b506102a261069a366004614868565b611e22565b3480156106ab57600080fd5b50600254610321906001600160a01b031681565b3480156106cb57600080fd5b506102a26106da366004614868565b611fc9565b3480156106eb57600080fd5b506102ba633b9aca0081565b34801561070357600080fd5b506102a26107123660046146ed565b612071565b34801561072357600080fd5b506102a261211d565b34801561073857600080fd5b506102ba61074736600461488c565b60066020526000908152604090205481565b34801561076557600080fd5b506007546105929062010000900460ff1681565b34801561078557600080fd5b506102a26107943660046146ed565b61218f565b3480156107a557600080fd5b506102a261223b565b3480156107ba57600080fd5b5060408051808201909152600f81526e54726164657273506f7274616c563160881b60208201526103e4565b3480156107f257600080fd5b50610321612359565b34801561080757600080fd5b50600054610321906001600160a01b031681565b34801561082757600080fd5b506102a26108363660046148a7565b6123b9565b34801561084757600080fd5b50610592610856366004614868565b60086020526000908152604090205460ff1681565b6000546001600160a01b0316331461089e5760405162461bcd60e51b81526004016108959061490f565b60405180910390fd5b80600660008460048111156108b5576108b5614933565b60048111156108c6576108c6614933565b81526020810191909152604001600020558160048111156108e9576108e9614933565b6040518281527f91a91c5b64100d89985f4e4754369ab7d9e78ec146a78570d7a491aedcc0787a9060200160405180910390a25050565b600754610100900460ff16156109485760405162461bcd60e51b815260040161089590614949565b60075460ff161561096b5760405162461bcd60e51b815260040161089590614967565b33600081815260086020908152604091829020805460ff191685151590811790915591519182527f533b5000656942008bd4fd4fc5b23c925d6b3773e042e7c62e82331ee3797b74910160405180910390a250565b32331480610a6057507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a27573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a4b9190614987565b6001600160a01b0316336001600160a01b0316145b610a7c5760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff1615610aa45760405162461bcd60e51b815260040161089590614949565b60075460ff1615610ac75760405162461bcd60e51b815260040161089590614967565b610acf6126ef565b6003600081905260066020527f75f96ab15d697e93042dc45b5c896c4b27e89bb6eaf39475c5c371cb2513f7d254341015610b1c5760405162461bcd60e51b8152600401610895906149ca565b33610b298186868661275e565b5050610b33612906565b505050565b6000546001600160a01b03163314610b625760405162461bcd60e51b81526004016108959061490f565b60008111610b825760405162461bcd60e51b8152600401610895906149f5565b6005819055604080518181526019918101919091527f6d696e4c69766554696d65466f724d61726b6574436c6f7365000000000000006060820152602081018290527f8cf3e35f6221b16e1670a3413180c9484bf5aa71787905909fa82a6a2662e9ab906080015b60405180910390a150565b60408051808201825260118152704f4e5f424548414c465f54524144494e4760781b60208201529051632c652ce760e11b81526000916001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016916358ca59ce91610c6891600401614706565b602060405180830381865afa158015610c85573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ca99190614987565b905090565b6000546001600160a01b03163314610cd85760405162461bcd60e51b81526004016108959061490f565b6007805460ff610100808304821615810261ff001990931692909217928390556040517f8e47bd62470c6cba4d30c023548622607c9c84402a5655f2569b7934c36a9e4f93610d309390049091161515815260200190565b60405180910390a1565b600032331480610ddc57507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015610da3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dc79190614987565b6001600160a01b0316336001600160a01b0316145b610df85760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff1615610e205760405162461bcd60e51b815260040161089590614949565b60075460ff1615610e435760405162461bcd60e51b815260040161089590614967565b610e4b6126ef565b6001600081905260066020527f3e5fec24aa4dc4e5aee2e025e51e1392c72a2500577559fae9665c6d52bd6a3154341015610e985760405162461bcd60e51b8152600401610895906149ca565b33610ea8818a8a8a8a8a8a612961565b92505050610eb4612906565b9695505050505050565b32331480610f5e57507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f25573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f499190614987565b6001600160a01b0316336001600160a01b0316145b610f7a5760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff1615610fa25760405162461bcd60e51b815260040161089590614949565b60075460ff1615610fc55760405162461bcd60e51b815260040161089590614967565b610fcd6126ef565b604051637cdca42760e11b8152600481018290526002903390600090819081906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063f9b9484e90602401606060405180830381865afa15801561103e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110629190614a1d565b9250925092506000826001600160401b0316116110915760405162461bcd60e51b815260040161089590614a63565b61109c848288613059565b60028360058111156110b0576110b0614933565b146110ee5760405162461bcd60e51b815260206004820152600e60248201526d1393d517d3d4115397d31253525560921b6044820152606401610895565b6003546111046001600160401b03841642614aa3565b10156111435760405162461bcd60e51b815260206004820152600e60248201526d4c494d49545f54494d454c4f434b60901b6044820152606401610895565b604051636e01af8d60e01b81526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636e01af8d90611196908a908a908690600401614aca565b600060405180830381600087803b1580156111b057600080fd5b505af11580156111c4573d6000803e3d6000fd5b50506040518992507f466f76860d9f560f8e3b355310f75ee22ac739fbd5c3815295c94d060882f0369150600090a2505050505050611201612906565b50565b323314806112a457507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa15801561126b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061128f9190614987565b6001600160a01b0316336001600160a01b0316145b6112c05760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff16156112e85760405162461bcd60e51b815260040161089590614949565b6112f06126ef565b604051637cdca42760e11b815260048101829052339060009081906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063f9b9484e90602401606060405180830381865afa15801561135c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113809190614a1d565b50915091506000816001600160401b0316116113ae5760405162461bcd60e51b815260040161089590614a63565b60018260058111156113c2576113c2614933565b146114015760405162461bcd60e51b815260206004820152600f60248201526e1393d517d3d4115397d3505492d155608a1b6044820152606401610895565b600454611417906001600160401b038316614aec565b4210156114365760405162461bcd60e51b815260040161089590614aff565b604051636e01af8d60e01b81526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690636e01af8d9061148a9088906001908690600401614aca565b600060405180830381600087803b1580156114a457600080fd5b505af11580156114b8573d6000803e3d6000fd5b50506040516001600160a01b03871692508791507facea7bb63fc54a1f0aacafafd5888c41cb76fdfd5cd2d085b7e39c49d4ba685390600090a350505050611201612906565b3233148061159e57507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015611565573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115899190614987565b6001600160a01b0316336001600160a01b0316145b6115ba5760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff16156115e25760405162461bcd60e51b815260040161089590614949565b60075460ff16156116055760405162461bcd60e51b815260040161089590614967565b61160d6126ef565b6004600081905260066020527fc5069e24aaadb2addc3e52e868fcf3f4f8acf5a87e24300992fd4540c2a87eed5434101561165a5760405162461bcd60e51b8152600401610895906149ca565b336116688187878787613249565b5050611672612906565b50505050565b3233148061171857507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116df573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117039190614987565b6001600160a01b0316336001600160a01b0316145b6117345760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff161561175c5760405162461bcd60e51b815260040161089590614949565b60075460ff161561177f5760405162461bcd60e51b815260040161089590614967565b6117876126ef565b6002600081905260066020527f8819ef417987f8ae7a81f42cdfb18815282fe989326fbff903d13cf0e03ace29543410156117d45760405162461bcd60e51b8152600401610895906149ca565b33610b29818686866133f4565b6000546001600160a01b0316331461180b5760405162461bcd60e51b81526004016108959061490f565b6007805460ff62010000808304821615810262ff00001990931692909217928390556040517fec086d142e6bc011f02adaa251a708b6bb48e2098b6c05fd26571b356ac0ee1693610d309390049091161515815260200190565b3233148061190557507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118cc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118f09190614987565b6001600160a01b0316336001600160a01b0316145b6119215760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff16156119495760405162461bcd60e51b815260040161089590614949565b6119516126ef565b600061195b611d61565b60405163c608b6c160e01b8152600481018490529091506000906001600160a01b0383169063c608b6c19060240160a0604051808303816000875af11580156119a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119cc9190614b8c565b9050600081604001516001600160401b031611611a225760405162461bcd60e51b81526020600482015260146024820152732727afa9aaa1a42faaa82220aa22afa7a92222a960611b6044820152606401610895565b60045481604001516001600160401b0316611a3d9190614aec565b421015611a5c5760405162461bcd60e51b815260040161089590614aff565b5050611201612906565b32331480611b0657507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015611acd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611af19190614987565b6001600160a01b0316336001600160a01b0316145b611b225760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff1615611b4a5760405162461bcd60e51b815260040161089590614949565b611b526126ef565b604051637cdca42760e11b815260048101829052339060009081906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063f9b9484e90602401606060405180830381865afa158015611bbe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611be29190614a1d565b50915091506000816001600160401b031611611c105760405162461bcd60e51b815260040161089590614a63565b6004826005811115611c2457611c24614933565b14611c645760405162461bcd60e51b815260206004820152601060248201526f1393d517d0d313d4d157d3505492d15560821b6044820152606401610895565b600454611c7a906001600160401b038316614aec565b421015611c995760405162461bcd60e51b815260040161089590614aff565b604051634ebe5c3360e01b81526000906001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001690634ebe5c3390611ced9088906001908690600401614c28565b600060405180830381600087803b158015611d0757600080fd5b505af1158015611d1b573d6000803e3d6000fd5b50506040516001600160a01b03871692508791507f2e5d992457367955712550a3f339e00ae07c6539e59a97aa66645d300677c9b090600090a350505050611201612906565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316637bbb19dc6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611dc1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611de59190614987565b6001600160a01b031663776af5ba6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c85573d6000803e3d6000fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316637b1039996040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e80573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ea49190614987565b60025460405163a8e36e5b60e01b81526001600160a01b03918216600482015291169063a8e36e5b90602401602060405180830381865afa158015611eed573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f119190614987565b6001600160a01b0316336001600160a01b031614611f645760405162461bcd60e51b815260206004820152601060248201526f2727aa2fa322a2a9afa6a0a720a3a2a960811b6044820152606401610895565b60405147906001600160a01b0383169082156108fc029083906000818181858888f19350505050611fc55760405162461bcd60e51b815260206004820152600b60248201526a14d1539117d1905253115160aa1b6044820152606401610895565b5050565b6000546001600160a01b0316331461200f5760405162461bcd60e51b81526020600482015260096024820152682737ba1020b236b4b760b91b6044820152606401610895565b600180546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a991015b60405180910390a15050565b6000546001600160a01b0316331461209b5760405162461bcd60e51b81526004016108959061490f565b600081116120bb5760405162461bcd60e51b8152600401610895906149f5565b600481905560408051818152601391810191909152721b585c9ad95d13dc99195c9cd51a5b595bdd5d606a1b6060820152602081018290527f8cf3e35f6221b16e1670a3413180c9484bf5aa71787905909fa82a6a2662e9ab90608001610bea565b6000546001600160a01b031633146121475760405162461bcd60e51b81526004016108959061490f565b6007805460ff8082161560ff1990921682179092556040519116151581527fda88b5dfaac55549d4ddddd43a09d4b911233df354952ebc9ac2041aa185343690602001610d30565b6000546001600160a01b031633146121b95760405162461bcd60e51b81526004016108959061490f565b600081116121d95760405162461bcd60e51b8152600401610895906149f5565b600381905560408051818152601391810191909152726c696d69744f726465727354696d656c6f636b60681b6060820152602081018290527f8cf3e35f6221b16e1670a3413180c9484bf5aa71787905909fa82a6a2662e9ab90608001610bea565b6001546001600160a01b03163314801561225f57506001546001600160a01b031615155b6122ab5760405162461bcd60e51b815260206004820152601e60248201527f4e6f7420746865204558495354494e472070656e64696e672061646d696e00006044820152606401610895565b60008054600180546001600160a01b038082166001600160a01b031980861682179096559490911690915560408051919092168082526020820184905292917ff9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc910160405180910390a1600154604080516001600160a01b03808516825290921660208301527fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a99101612065565b60007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c85573d6000803e3d6000fd5b3233148061245957507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015612420573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124449190614987565b6001600160a01b0316336001600160a01b0316145b6124755760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff161561249d5760405162461bcd60e51b815260040161089590614949565b60075460ff16156124c05760405162461bcd60e51b815260040161089590614967565b6124c86126ef565b604051637cdca42760e11b8152600481018690523390600090819081906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063f9b9484e90602401606060405180830381865afa158015612536573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061255a9190614a1d565b9250925092506000826001600160401b0316116125895760405162461bcd60e51b815260040161089590614a63565b61259484828b613059565b60028360058111156125a8576125a8614933565b146125e65760405162461bcd60e51b815260206004820152600e60248201526d1393d517d3d4115397d31253525560921b6044820152606401610895565b6003546125fc6001600160401b03841642614aa3565b101561263b5760405162461bcd60e51b815260206004820152600e60248201526d4c494d49545f54494d454c4f434b60901b6044820152606401610895565b604051634ffb4ffd60e11b8152600481018a90526001600160401b03808a16602483015280891660448301528088166064830152861660848201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031690639ff69ffa9060a401600060405180830381600087803b1580156126c457600080fd5b505af11580156126d8573d6000803e3d6000fd5b50505050505050506126e8612906565b5050505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f83d08ba6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561274a57600080fd5b505af1158015611672573d6000803e3d6000fd5b60008060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f9b9484e876040518263ffffffff1660e01b81526004016127b191815260200190565b606060405180830381865afa1580156127ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127f29190614a1d565b9250925092506000826001600160401b0316116128215760405162461bcd60e51b815260040161089590614a63565b61282c878288613059565b600383600581111561284057612840614933565b1461287b5760405162461bcd60e51b815260206004820152600b60248201526a13d3931657d3d41153915160aa1b6044820152606401610895565b6000612885611d61565b6040516320e5cf4560e11b81529091506001600160a01b038216906341cb9e8a906128b8908a908a908a90600401614c60565b60a0604051808303816000875af11580156128d7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128fb9190614b8c565b505050505050505050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03166340da020f6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561274a57600080fd5b60006129706020880188614868565b6001600160a01b0316886001600160a01b0316141580156129aa5750612994612359565b6001600160a01b0316886001600160a01b031614155b15612b1d57600860006129c060208a018a614868565b6001600160a01b0316815260208101919091526040016000205460ff16612a1d5760405162461bcd60e51b815260206004820152601160248201527021a0a62622a92fa727aa2faa2920a222a960791b6044820152606401610895565b6000612a27610bf5565b90506001600160a01b038116612a7b5760405162461bcd60e51b815260206004820152601960248201527813d397d0915210531197d5149051125391d7d393d517d4d155603a1b6044820152606401610895565b6001600160a01b038116638416f9b3612a9760208b018b614868565b8b612aa860608d0160408e01614868565b60405160e085901b6001600160e01b03191681526001600160a01b0393841660048201529183166024830152909116604482015260208a01356064820152608401600060405180830381600087803b158015612b0357600080fd5b505af1158015612b17573d6000803e3d6000fd5b50505050505b612b2d60a0870160808801614c8b565b6001600160401b0316612b466080880160608901614c8b565b6001600160401b03161115612b8f5760405162461bcd60e51b815260206004820152600f60248201526e4d494e5f4d41585f5245564552534560881b6044820152606401610895565b612b9f60c0870160a08801614c8b565b6001600160401b03161580612bcb5750612bc0610100870160e08801614c8b565b6001600160401b0316155b612c175760405162461bcd60e51b815260206004820152601760248201527f4d554c5449504c455f54505f444546494e4954494f4e530000000000000000006044820152606401610895565b612c2760e0870160c08801614c8b565b6001600160401b03161580612c545750612c4961012087016101008801614c8b565b6001600160401b0316155b612ca05760405162461bcd60e51b815260206004820152601760248201527f4d554c5449504c455f534c5f444546494e4954494f4e530000000000000000006044820152606401610895565b620186a0612cb661012088016101008901614c8b565b6001600160401b031610612d0c5760405162461bcd60e51b815260206004820152601b60248201527f534c5f4f465f4d4f52455f5448414e5f3130305f50455243454e5400000000006044820152606401610895565b612d1c60c0870160a08801614c8b565b6001600160401b03161580612da95750612d396020870187614663565b612d7557612d4d6080870160608801614c8b565b6001600160401b0316612d6660c0880160a08901614c8b565b6001600160401b031610612da9565b612d8560a0870160808801614c8b565b6001600160401b0316612d9e60c0880160a08901614c8b565b6001600160401b0316115b612de05760405162461bcd60e51b8152602060048201526008602482015267057524f4e475f54560c41b6044820152606401610895565b612df060e0870160c08801614c8b565b6001600160401b03161580612e7d5750612e0d6020870187614663565b612e4957612e2160a0870160808801614c8b565b6001600160401b0316612e3a60e0880160c08901614c8b565b6001600160401b031611612e7d565b612e596080870160608801614c8b565b6001600160401b0316612e7260e0880160c08901614c8b565b6001600160401b0316105b612eb45760405162461bcd60e51b815260206004820152600860248201526715d493d391d7d4d360c21b6044820152606401610895565b8115612ec457612ec4878761364d565b6000806002876002811115612edb57612edb614933565b03612f7c5760405163195c521960e31b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063cae290c890612f32908a908d908d908890600401614cca565b6020604051808303816000875af1158015612f51573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f759190614e45565b905061301d565b6001876002811115612f9057612f90614933565b03612fe75760405163195c521960e31b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169063cae290c890612f32908a908d908d908890600401614cca565b60405162461bcd60e51b815260206004820152600b60248201526a155394d5541413d495115160aa1b6044820152606401610895565b8085877f076eb959a98c5de701c0d3d1bbb7b7b28fdef080e1356cb1d6c710a0c8b5cf6360405160405180910390a49998505050505050505050565b816001600160a01b0316836001600160a01b031614158015613094575061307e612359565b6001600160a01b0316836001600160a01b031614155b15610b33576001600160a01b03821660009081526008602052604090205460ff166130f55760405162461bcd60e51b815260206004820152601160248201527021a0a62622a92fa727aa2faa2920a222a960791b6044820152606401610895565b60006130ff610bf5565b90506001600160a01b0381166131535760405162461bcd60e51b815260206004820152601960248201527813d397d0915210531197d5149051125391d7d393d517d4d155603a1b6044820152606401610895565b60405163042e37c560e01b8152600481018390526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03169063042e37c590602401608060405180830381865afa1580156131bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131df9190614e74565b516040516381e6a99d60e01b81526001600160a01b03868116600483015287811660248301528083166044830152919250908316906381e6a99d9060640160006040518083038186803b15801561323557600080fd5b505afa1580156128fb573d6000803e3d6000fd5b60008060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f9b9484e886040518263ffffffff1660e01b815260040161329c91815260200190565b606060405180830381865afa1580156132b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132dd9190614a1d565b9250925092506000826001600160401b03161161330c5760405162461bcd60e51b815260040161089590614a63565b613317888289613059565b600383600581111561332b5761332b614933565b146133665760405162461bcd60e51b815260206004820152600b60248201526a13d3931657d3d41153915160aa1b6044820152606401610895565b6000613370611d61565b604051636277297960e01b81529091506001600160a01b038216906362772979906133a5908b908b908b908b90600401614edb565b60a0604051808303816000875af11580156133c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133e89190614b8c565b50505050505050505050565b60008060007f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f9b9484e876040518263ffffffff1660e01b815260040161344791815260200190565b606060405180830381865afa158015613464573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134889190614a1d565b9250925092506000826001600160401b0316116134b75760405162461bcd60e51b815260040161089590614a63565b6134c2878288613059565b60048360058111156134d6576134d6614933565b0361351a5760405162461bcd60e51b81526020600482015260146024820152731053149150511657d091525391d7d0d313d4d15160621b6044820152606401610895565b6005546135306001600160401b03841642614aa3565b101561357e5760405162461bcd60e51b815260206004820152601e60248201527f4d494e5f4c4956455f54494d455f464f525f4d41524b45545f434c4f534500006044820152606401610895565b60075462010000900460ff167f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e640f33b88836135c557886135c8565b60005b846135d357886135dc565b6001600160401b035b6040516001600160e01b031960e086901b16815260048101939093526001600160401b039182166024840152166044820152606401600060405180830381600087803b15801561362b57600080fd5b505af115801561363f573d6000803e3d6000fd5b505050505050505050505050565b60006001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000166303b90a8761368e6060860160408701614868565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602401602060405180830381865afa1580156136d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136f69190614987565b90506001600160a01b03811661373e5760405162461bcd60e51b815260206004820152600d60248201526c1393d7d050d0d3d55395105395609a1b6044820152606401610895565b613749818484613daf565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663f65d9dbe6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156137a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137cb9190614e45565b6001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016638c01936e61380a6060870160408801614868565b6138176020880188614868565b6138276040890160208a01614f11565b6040516001600160e01b031960e086901b1681526001600160a01b03938416600482015292909116602483015261ffff1660448201526064016040805180830381865afa15801561387c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138a09190614f2e565b5163ffffffff16106138ea5760405162461bcd60e51b815260206004820152601360248201527226a0ac2faa2920a222a9afa822a92fa820a4a960691b6044820152606401610895565b60006001600160a01b03821663c2b1088361390b6040870160208801614f11565b6040516001600160e01b031960e084901b16815261ffff909116600482015260240161018060405180830381865afa15801561394b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061396f9190614f9a565b6020810151604051633979324d60e01b815261ffff90911660048201529091506000906001600160a01b03841690633979324d9060240160c060405180830381865afa1580156139c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139e7919061505e565b6040808401519051632f08b92f60e21b815261ffff90911660048201529091506000906001600160a01b0385169063bc22e4bc90602401608060405180830381865afa158015613a3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a5f9190615106565b90506000613a736060870160408801615161565b63ffffffff16118015613aa6575060608084015163ffffffff1690613a9d90870160408801615161565b63ffffffff1610155b613af25760405162461bcd60e51b815260206004820152601960248201527f4c455645524147455f544f4f5f4c4f575f464f525f50414952000000000000006044820152606401610895565b608083015163ffffffff16613b0d6060870160408801615161565b63ffffffff161115613b615760405162461bcd60e51b815260206004820152601a60248201527f4c455645524147455f544f4f5f484947485f464f525f504149520000000000006044820152606401610895565b6000613b736060870160408801615161565b63ffffffff16118015613ba55750602082015163ffffffff16613b9c6060870160408801615161565b63ffffffff1610155b613bf15760405162461bcd60e51b815260206004820152601a60248201527f4c455645524147455f544f4f5f4c4f575f464f525f47524f55500000000000006044820152606401610895565b816040015163ffffffff16856040016020810190613c0f9190615161565b63ffffffff161115613c635760405162461bcd60e51b815260206004820152601b60248201527f4c455645524147455f544f4f5f484947485f464f525f47524f555000000000006044820152606401610895565b6000613c886020870135613c7d6060890160408a01615161565b63ffffffff16614352565b90508360c00151811115613cd15760405162461bcd60e51b815260206004820152601060248201526f504f534954494f4e5f544f4f5f42494760801b6044820152606401610895565b6000856001600160a01b0316631dcf50ef6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613d11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d359190614e45565b602084015190915063ffffffff166000620186a0613d53838661517e565b613d5d91906151ab565b9050828110156133e85760405162461bcd60e51b815260206004820152601b60248201527f444f45535f4e4f545f52454143485f4d494e5f4f50454e5f46454500000000006044820152606401610895565b6000613dbe6020830183614663565b613dd757613dd260a0830160808401614c8b565b613de7565b613de76080830160608401614c8b565b90506000613e578284876001600160a01b0316631cb92ed36040518163ffffffff1660e01b8152600401602060405180830381865afa158015613e2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613e529190614e45565b614373565b905060006001600160a01b03861663167ba8bf6020860135613e7f6060880160408901615161565b613e8c6020890189614663565b6040516001600160e01b031960e086901b168152600481019390935263ffffffff919091166024830152151560448201526001600160401b0380871660648301528516608482015260a401602060405180830381865afa158015613ef4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f189190614e45565b905060006001600160a01b03871663657d6edf613f3b6040890160208a01614f11565b6040516001600160e01b031960e084901b16815261ffff9091166004820152602401602060405180830381865afa158015613f7a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f9e9190614e45565b90506000613fac8383614aec565b90506001600160a01b038816633cb57be7613fcd60408a0160208b01614f11565b6040516001600160e01b031960e084901b16815261ffff9091166004820152602401602060405180830381865afa15801561400c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906140309190614e45565b8111156140715760405162461bcd60e51b815260206004820152600f60248201526e26a0ac2fa127a92927abafa820a4a960891b6044820152606401610895565b60006001600160a01b03891663c2b1088361409260408b0160208c01614f11565b6040516001600160e01b031960e084901b16815261ffff909116600482015260240161018060405180830381865afa1580156140d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906140f69190614f9a565b6020015160405163340de84760e21b815261ffff821660048201529091506000906001600160a01b038b169063d037a11c90602401602060405180830381865afa158015614148573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061416c9190614e45565b9050600061417a8683614aec565b6040516340691c9560e01b815261ffff851660048201529091506001600160a01b038c16906340691c9590602401602060405180830381865afa1580156141c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906141e99190614e45565b81111561422b5760405162461bcd60e51b815260206004820152601060248201526f04d41585f424f52524f575f47524f55560841b6044820152606401610895565b60008b6001600160a01b03166347bd37186040518163ffffffff1660e01b8152600401602060405180830381865afa15801561426b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061428f9190614e45565b9050600061429d8883614aec565b90508c6001600160a01b03166388c8f1786040518163ffffffff1660e01b8152600401602060405180830381865afa1580156142dd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906143019190614e45565b8111156143435760405162461bcd60e51b815260206004820152601060248201526f4d41585f544f54414c5f424f52524f5760801b6044820152606401610895565b50505050505050505050505050565b60006064614360838561517e565b61436a91906151ab565b90505b92915050565b600061438560c0840160a08501614c8b565b9050600061439a610100850160e08601614c8b565b6001600160401b0316111561442b5760006143db856143c0610100870160e08801614c8b565b6143d06060880160408901615161565b63ffffffff16614461565b90506143ea6020850185614663565b61441d57846001600160401b0316816001600160401b03161061440e576000614427565b61441881866151bf565b614427565b61442781866151e6565b9150505b61445982856144406060870160408801615161565b63ffffffff16846144546020890189614663565b6144b9565b949350505050565b600080826001600160401b0316620186a06064866001600160401b0316886001600160401b0316614492919061517e565b61449c919061517e565b6144a691906151ab565b6144b091906151ab565b95945050505050565b60006001600160401b03831615806144e357508560070b6144dd8787868689614589565b60070b12155b1561457f576000620186a0856001600160401b03166064896001600160401b0316896001600160401b0316614518919061517e565b614522919061517e565b61452c91906151ab565b61453691906151ab565b90508261456d57856001600160401b0316816001600160401b0316111561455e576000614577565b61456881876151bf565b614577565b61457781876151e6565b9150506144b0565b5090949350505050565b60008581846145a15761459c8688615206565b6145ab565b6145ab8787615206565b905060008460070b620186a08360070b6145c59190615235565b6145cf9190615235565b90506000600789900b6145e3606484615265565b6145ed9190615265565b90508094508360070b8560070b136146055784614607565b835b9a9950505050505050505050565b80356005811061462457600080fd5b919050565b6000806040838503121561463c57600080fd5b61464583614615565b946020939093013593505050565b8035801515811461462457600080fd5b60006020828403121561467557600080fd5b61436a82614653565b6004811061120157600080fd5b6001600160401b038116811461120157600080fd5b80356146248161468b565b6000806000606084860312156146c057600080fd5b8335925060208401356146d28161467e565b915060408401356146e28161468b565b809150509250925092565b6000602082840312156146ff57600080fd5b5035919050565b60006020808352835180602085015260005b8181101561473457858101830151858201604001528201614718565b506000604082860101526040601f19601f8301168501019250505092915050565b60008060008060008086880361022081121561477057600080fd5b608081121561477e57600080fd5b879650610120607f198201121561479457600080fd5b506080870194506101a0870135600381106147ae57600080fd5b93506101c087013592506101e087013591506147cd6102008801614653565b90509295509295509295565b600080600080608085870312156147ef57600080fd5b8435935060208501356148018161467e565b925060408501356148118161468b565b915060608501356148218161468b565b939692955090935050565b60008060006060848603121561484157600080fd5b8335925060208401356146d28161468b565b6001600160a01b038116811461120157600080fd5b60006020828403121561487a57600080fd5b813561488581614853565b9392505050565b60006020828403121561489e57600080fd5b61436a82614615565b600080600080600060a086880312156148bf57600080fd5b8535945060208601356148d18161468b565b935060408601356148e18161468b565b925060608601356148f18161468b565b915060808601356149018161468b565b809150509295509295909350565b6020808252600a908201526927a7262cafa0a226a4a760b11b604082015260600190565b634e487b7160e01b600052602160045260246000fd5b602080825260049082015263444f4e4560e01b604082015260600190565b60208082526006908201526514105554d15160d21b604082015260600190565b60006020828403121561499957600080fd5b815161488581614853565b6020808252600c908201526b1393d517d0d3d395149050d560a21b604082015260600190565b6020808252601190820152704e4f545f454e4f5547485f4e415449564560781b604082015260600190565b6020808252600e908201526d43414e4e4f545f42455f5a45524f60901b604082015260600190565b600080600060608486031215614a3257600080fd5b835160068110614a4157600080fd5b6020850151909350614a528161468b565b60408501519092506146e281614853565b60208082526010908201526f2727afa9aaa1a42fa827a9a4aa24a7a760811b604082015260600190565b634e487b7160e01b600052601160045260246000fd5b8181038181111561436d5761436d614a8d565b60038110614ac657614ac6614933565b9052565b83815260608101614ade6020830185614ab6565b826040830152949350505050565b8082018082111561436d5761436d614a8d565b6020808252600c908201526b15d0525517d512535153d55560a21b604082015260600190565b604051608081016001600160401b0381118282101715614b5557634e487b7160e01b600052604160045260246000fd5b60405290565b60405161018081016001600160401b0381118282101715614b5557634e487b7160e01b600052604160045260246000fd5b600060a08284031215614b9e57600080fd5b60405160a081018181106001600160401b0382111715614bce57634e487b7160e01b600052604160045260246000fd5b604052825181526020830151614be38161467e565b60208201526040830151614bf68161468b565b60408201526060830151614c098161468b565b60608201526080830151614c1c8161468b565b60808201529392505050565b8381526060810160028410614c3f57614c3f614933565b602082019390935260400152919050565b60048110614ac657614ac6614933565b83815260608101614c746020830185614c50565b6001600160401b0383166040830152949350505050565b600060208284031215614c9d57600080fd5b81356148858161468b565b61ffff8116811461120157600080fd5b63ffffffff8116811461120157600080fd5b6101e08101614cd98287614ab6565b8435614ce481614853565b6001600160a01b0390811660208481019190915286013590614d0582614ca8565b61ffff8216604085015260408701359150614d1f82614853565b16606083810191909152850135614d3581614cb8565b63ffffffff166080830152614d4984614653565b151560a0830152602084013560c08301526040840135614d6881614cb8565b63ffffffff1660e0830152614d7f606085016146a0565b610100614d96818501836001600160401b03169052565b614da2608087016146a0565b6001600160401b0381166101208601529150614dc060a087016146a0565b6001600160401b0381166101408601529150614dde60c087016146a0565b6001600160401b0381166101608601529150614dfc60e087016146a0565b6001600160401b0381166101808601529150614e198187016146a0565b915050614e326101a08401826001600160401b03169052565b5063ffffffff83166101c08301526144b0565b600060208284031215614e5757600080fd5b5051919050565b805161462481614ca8565b805161462481614cb8565b600060808284031215614e8657600080fd5b614e8e614b25565b8251614e9981614853565b81526020830151614ea981614ca8565b60208201526040830151614ebc81614cb8565b60408201526060830151614ecf81614853565b60608201529392505050565b84815260808101614eef6020830186614c50565b6001600160401b03808516604084015280841660608401525095945050505050565b600060208284031215614f2357600080fd5b813561488581614ca8565b600060408284031215614f4057600080fd5b604051604081018181106001600160401b0382111715614f7057634e487b7160e01b600052604160045260246000fd5b6040528251614f7e81614cb8565b81526020830151614f8e81614cb8565b60208201529392505050565b60006101808284031215614fad57600080fd5b614fb5614b5b565b614fbe83614e5e565b8152614fcc60208401614e5e565b6020820152614fdd60408401614e5e565b6040820152614fee60608401614e69565b6060820152614fff60808401614e69565b608082015261501060a08401614e69565b60a082015260c0838101519082015260e08084015190820152610100808401519082015261012080840151908201526101408084015190820152610160928301519281019290925250919050565b600060c0828403121561507057600080fd5b60405160c081018181106001600160401b03821117156150a057634e487b7160e01b600052604160045260246000fd5b60405282516150ae81614ca8565b815260208301516150be81614cb8565b602082015260408301516150d181614cb8565b604082015260608301516150e481614cb8565b60608201526080838101519082015260a0928301519281019290925250919050565b60006080828403121561511857600080fd5b615120614b25565b825161512b81614ca8565b8152602083015161513b81614cb8565b6020820152604083015161514e81614cb8565b60408201526060830151614ecf81614cb8565b60006020828403121561517357600080fd5b813561488581614cb8565b808202811582820484141761436d5761436d614a8d565b634e487b7160e01b600052601260045260246000fd5b6000826151ba576151ba615195565b500490565b6001600160401b038281168282160390808211156151df576151df614a8d565b5092915050565b6001600160401b038181168382160190808211156151df576151df614a8d565b600782810b9082900b03677fffffffffffffff198112677fffffffffffffff8213171561436d5761436d614a8d565b80820260008212600160ff1b8414161561525157615251614a8d565b818105831482151761436d5761436d614a8d565b60008261527457615274615195565b600160ff1b82146000198414161561528e5761528e614a8d565b50059056fea2646970667358221220d2642bdb87ca976377e5f48ccd444796041570cbc6701874f8a73fb234c3ef1b64736f6c6343000818003300000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868
Deployed Bytecode
0x60806040526004361061027d5760003560e01c80638f0622271161014f578063b71f3cfe116100c1578063e9c714f21161007a578063e9c714f214610799578063f5f5ba72146107ae578063f714bdc2146107e6578063f851a440146107fb578063f86d29481461081b578063fd4a2c431461083b57600080fd5b8063b71f3cfe146106df578063b81bfa05146106f7578063c4ae316814610717578063d060576b1461072c578063d33b671614610759578063d4a1caa71461077957600080fd5b8063ad1f2b5611610113578063ad1f2b561461063b578063b187bd2614610650578063b248c4ef1461066a578063b26d1b911461067f578063b48ae6361461069f578063b71d1a0c146106bf57600080fd5b80638f06222714610573578063922e2db4146105a2578063a6eb0a78146105c2578063aaf5eb68146105e2578063ac2bff1f146105fe57600080fd5b8063410c0b7c116101f35780636b8b5e22116101ac5780636b8b5e22146104c0578063719683ea146104d357806372f8c620146104e65780637b103999146104fb57806380193b261461052f5780638aa104351461054657600080fd5b8063410c0b7c14610406578063441762661461041c578063441f64bb1461042f578063568b6add14610445578063609393c714610465578063614d08f81461048557600080fd5b80631d3e4d46116102455780631d3e4d461461034c578063217cf74f1461035f578063267822471461037f5780632904fb4b1461039f57806338b90333146103b45780633be3d626146103f157600080fd5b80630310a65b146102825780630890d22a146102a45780630c7d4d8b146102cd5780630d3b0b76146102ed578063119df25f14610339575b600080fd5b34801561028e57600080fd5b506102a261029d366004614629565b61086b565b005b3480156102b057600080fd5b506102ba60035481565b6040519081526020015b60405180910390f35b3480156102d957600080fd5b506102a26102e8366004614663565b610920565b3480156102f957600080fd5b506103217f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa86881565b6040516001600160a01b0390911681526020016102c4565b34801561034557600080fd5b5033610321565b6102a261035a3660046146ab565b6109c0565b34801561036b57600080fd5b506102a261037a3660046146ed565b610b38565b34801561038b57600080fd5b50600154610321906001600160a01b031681565b3480156103ab57600080fd5b50610321610bf5565b3480156103c057600080fd5b506103e4604051806040016040528060048152602001630313031360e41b81525081565b6040516102c49190614706565b3480156103fd57600080fd5b506102a2610cae565b34801561041257600080fd5b506102ba60045481565b6102ba61042a366004614755565b610d3a565b34801561043b57600080fd5b506102ba60055481565b34801561045157600080fd5b506102a26104603660046146ed565b610ebe565b34801561047157600080fd5b506102a26104803660046146ed565b611204565b34801561049157600080fd5b506103e46040518060400160405280600f81526020016e54726164657273506f7274616c563160881b81525081565b6102a26104ce3660046147d9565b6114fe565b6102a26104e136600461482c565b611678565b3480156104f257600080fd5b506102a26117e1565b34801561050757600080fd5b506103217f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c20781565b34801561053b57600080fd5b506102ba620186a081565b34801561055257600080fd5b506040805180820190915260048152630313031360e41b60208201526103e4565b34801561057f57600080fd5b5060075461059290610100900460ff1681565b60405190151581526020016102c4565b3480156105ae57600080fd5b506102a26105bd3660046146ed565b611865565b3480156105ce57600080fd5b506102a26105dd3660046146ed565b611a66565b3480156105ee57600080fd5b506102ba670de0b6b3a764000081565b34801561060a57600080fd5b506103e4604051806040016040528060118152602001704f4e5f424548414c465f54524144494e4760781b81525081565b34801561064757600080fd5b506102ba606481565b34801561065c57600080fd5b506007546105929060ff1681565b34801561067657600080fd5b50610321611d61565b34801561068b57600080fd5b506102a261069a366004614868565b611e22565b3480156106ab57600080fd5b50600254610321906001600160a01b031681565b3480156106cb57600080fd5b506102a26106da366004614868565b611fc9565b3480156106eb57600080fd5b506102ba633b9aca0081565b34801561070357600080fd5b506102a26107123660046146ed565b612071565b34801561072357600080fd5b506102a261211d565b34801561073857600080fd5b506102ba61074736600461488c565b60066020526000908152604090205481565b34801561076557600080fd5b506007546105929062010000900460ff1681565b34801561078557600080fd5b506102a26107943660046146ed565b61218f565b3480156107a557600080fd5b506102a261223b565b3480156107ba57600080fd5b5060408051808201909152600f81526e54726164657273506f7274616c563160881b60208201526103e4565b3480156107f257600080fd5b50610321612359565b34801561080757600080fd5b50600054610321906001600160a01b031681565b34801561082757600080fd5b506102a26108363660046148a7565b6123b9565b34801561084757600080fd5b50610592610856366004614868565b60086020526000908152604090205460ff1681565b6000546001600160a01b0316331461089e5760405162461bcd60e51b81526004016108959061490f565b60405180910390fd5b80600660008460048111156108b5576108b5614933565b60048111156108c6576108c6614933565b81526020810191909152604001600020558160048111156108e9576108e9614933565b6040518281527f91a91c5b64100d89985f4e4754369ab7d9e78ec146a78570d7a491aedcc0787a9060200160405180910390a25050565b600754610100900460ff16156109485760405162461bcd60e51b815260040161089590614949565b60075460ff161561096b5760405162461bcd60e51b815260040161089590614967565b33600081815260086020908152604091829020805460ff191685151590811790915591519182527f533b5000656942008bd4fd4fc5b23c925d6b3773e042e7c62e82331ee3797b74910160405180910390a250565b32331480610a6057507f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a27573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a4b9190614987565b6001600160a01b0316336001600160a01b0316145b610a7c5760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff1615610aa45760405162461bcd60e51b815260040161089590614949565b60075460ff1615610ac75760405162461bcd60e51b815260040161089590614967565b610acf6126ef565b6003600081905260066020527f75f96ab15d697e93042dc45b5c896c4b27e89bb6eaf39475c5c371cb2513f7d254341015610b1c5760405162461bcd60e51b8152600401610895906149ca565b33610b298186868661275e565b5050610b33612906565b505050565b6000546001600160a01b03163314610b625760405162461bcd60e51b81526004016108959061490f565b60008111610b825760405162461bcd60e51b8152600401610895906149f5565b6005819055604080518181526019918101919091527f6d696e4c69766554696d65466f724d61726b6574436c6f7365000000000000006060820152602081018290527f8cf3e35f6221b16e1670a3413180c9484bf5aa71787905909fa82a6a2662e9ab906080015b60405180910390a150565b60408051808201825260118152704f4e5f424548414c465f54524144494e4760781b60208201529051632c652ce760e11b81526000916001600160a01b037f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c20716916358ca59ce91610c6891600401614706565b602060405180830381865afa158015610c85573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ca99190614987565b905090565b6000546001600160a01b03163314610cd85760405162461bcd60e51b81526004016108959061490f565b6007805460ff610100808304821615810261ff001990931692909217928390556040517f8e47bd62470c6cba4d30c023548622607c9c84402a5655f2569b7934c36a9e4f93610d309390049091161515815260200190565b60405180910390a1565b600032331480610ddc57507f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015610da3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610dc79190614987565b6001600160a01b0316336001600160a01b0316145b610df85760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff1615610e205760405162461bcd60e51b815260040161089590614949565b60075460ff1615610e435760405162461bcd60e51b815260040161089590614967565b610e4b6126ef565b6001600081905260066020527f3e5fec24aa4dc4e5aee2e025e51e1392c72a2500577559fae9665c6d52bd6a3154341015610e985760405162461bcd60e51b8152600401610895906149ca565b33610ea8818a8a8a8a8a8a612961565b92505050610eb4612906565b9695505050505050565b32331480610f5e57507f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f25573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f499190614987565b6001600160a01b0316336001600160a01b0316145b610f7a5760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff1615610fa25760405162461bcd60e51b815260040161089590614949565b60075460ff1615610fc55760405162461bcd60e51b815260040161089590614967565b610fcd6126ef565b604051637cdca42760e11b8152600481018290526002903390600090819081906001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868169063f9b9484e90602401606060405180830381865afa15801561103e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110629190614a1d565b9250925092506000826001600160401b0316116110915760405162461bcd60e51b815260040161089590614a63565b61109c848288613059565b60028360058111156110b0576110b0614933565b146110ee5760405162461bcd60e51b815260206004820152600e60248201526d1393d517d3d4115397d31253525560921b6044820152606401610895565b6003546111046001600160401b03841642614aa3565b10156111435760405162461bcd60e51b815260206004820152600e60248201526d4c494d49545f54494d454c4f434b60901b6044820152606401610895565b604051636e01af8d60e01b81526000906001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8681690636e01af8d90611196908a908a908690600401614aca565b600060405180830381600087803b1580156111b057600080fd5b505af11580156111c4573d6000803e3d6000fd5b50506040518992507f466f76860d9f560f8e3b355310f75ee22ac739fbd5c3815295c94d060882f0369150600090a2505050505050611201612906565b50565b323314806112a457507f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa15801561126b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061128f9190614987565b6001600160a01b0316336001600160a01b0316145b6112c05760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff16156112e85760405162461bcd60e51b815260040161089590614949565b6112f06126ef565b604051637cdca42760e11b815260048101829052339060009081906001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868169063f9b9484e90602401606060405180830381865afa15801561135c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906113809190614a1d565b50915091506000816001600160401b0316116113ae5760405162461bcd60e51b815260040161089590614a63565b60018260058111156113c2576113c2614933565b146114015760405162461bcd60e51b815260206004820152600f60248201526e1393d517d3d4115397d3505492d155608a1b6044820152606401610895565b600454611417906001600160401b038316614aec565b4210156114365760405162461bcd60e51b815260040161089590614aff565b604051636e01af8d60e01b81526000906001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8681690636e01af8d9061148a9088906001908690600401614aca565b600060405180830381600087803b1580156114a457600080fd5b505af11580156114b8573d6000803e3d6000fd5b50506040516001600160a01b03871692508791507facea7bb63fc54a1f0aacafafd5888c41cb76fdfd5cd2d085b7e39c49d4ba685390600090a350505050611201612906565b3233148061159e57507f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015611565573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115899190614987565b6001600160a01b0316336001600160a01b0316145b6115ba5760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff16156115e25760405162461bcd60e51b815260040161089590614949565b60075460ff16156116055760405162461bcd60e51b815260040161089590614967565b61160d6126ef565b6004600081905260066020527fc5069e24aaadb2addc3e52e868fcf3f4f8acf5a87e24300992fd4540c2a87eed5434101561165a5760405162461bcd60e51b8152600401610895906149ca565b336116688187878787613249565b5050611672612906565b50505050565b3233148061171857507f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116df573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906117039190614987565b6001600160a01b0316336001600160a01b0316145b6117345760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff161561175c5760405162461bcd60e51b815260040161089590614949565b60075460ff161561177f5760405162461bcd60e51b815260040161089590614967565b6117876126ef565b6002600081905260066020527f8819ef417987f8ae7a81f42cdfb18815282fe989326fbff903d13cf0e03ace29543410156117d45760405162461bcd60e51b8152600401610895906149ca565b33610b29818686866133f4565b6000546001600160a01b0316331461180b5760405162461bcd60e51b81526004016108959061490f565b6007805460ff62010000808304821615810262ff00001990931692909217928390556040517fec086d142e6bc011f02adaa251a708b6bb48e2098b6c05fd26571b356ac0ee1693610d309390049091161515815260200190565b3233148061190557507f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa1580156118cc573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118f09190614987565b6001600160a01b0316336001600160a01b0316145b6119215760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff16156119495760405162461bcd60e51b815260040161089590614949565b6119516126ef565b600061195b611d61565b60405163c608b6c160e01b8152600481018490529091506000906001600160a01b0383169063c608b6c19060240160a0604051808303816000875af11580156119a8573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119cc9190614b8c565b9050600081604001516001600160401b031611611a225760405162461bcd60e51b81526020600482015260146024820152732727afa9aaa1a42faaa82220aa22afa7a92222a960611b6044820152606401610895565b60045481604001516001600160401b0316611a3d9190614aec565b421015611a5c5760405162461bcd60e51b815260040161089590614aff565b5050611201612906565b32331480611b0657507f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015611acd573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611af19190614987565b6001600160a01b0316336001600160a01b0316145b611b225760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff1615611b4a5760405162461bcd60e51b815260040161089590614949565b611b526126ef565b604051637cdca42760e11b815260048101829052339060009081906001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868169063f9b9484e90602401606060405180830381865afa158015611bbe573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611be29190614a1d565b50915091506000816001600160401b031611611c105760405162461bcd60e51b815260040161089590614a63565b6004826005811115611c2457611c24614933565b14611c645760405162461bcd60e51b815260206004820152601060248201526f1393d517d0d313d4d157d3505492d15560821b6044820152606401610895565b600454611c7a906001600160401b038316614aec565b421015611c995760405162461bcd60e51b815260040161089590614aff565b604051634ebe5c3360e01b81526000906001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8681690634ebe5c3390611ced9088906001908690600401614c28565b600060405180830381600087803b158015611d0757600080fd5b505af1158015611d1b573d6000803e3d6000fd5b50506040516001600160a01b03871692508791507f2e5d992457367955712550a3f339e00ae07c6539e59a97aa66645d300677c9b090600090a350505050611201612906565b60007f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b0316637bbb19dc6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611dc1573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611de59190614987565b6001600160a01b031663776af5ba6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c85573d6000803e3d6000fd5b7f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8686001600160a01b0316637b1039996040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e80573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611ea49190614987565b60025460405163a8e36e5b60e01b81526001600160a01b03918216600482015291169063a8e36e5b90602401602060405180830381865afa158015611eed573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f119190614987565b6001600160a01b0316336001600160a01b031614611f645760405162461bcd60e51b815260206004820152601060248201526f2727aa2fa322a2a9afa6a0a720a3a2a960811b6044820152606401610895565b60405147906001600160a01b0383169082156108fc029083906000818181858888f19350505050611fc55760405162461bcd60e51b815260206004820152600b60248201526a14d1539117d1905253115160aa1b6044820152606401610895565b5050565b6000546001600160a01b0316331461200f5760405162461bcd60e51b81526020600482015260096024820152682737ba1020b236b4b760b91b6044820152606401610895565b600180546001600160a01b038381166001600160a01b031983168117909355604080519190921680825260208201939093527fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a991015b60405180910390a15050565b6000546001600160a01b0316331461209b5760405162461bcd60e51b81526004016108959061490f565b600081116120bb5760405162461bcd60e51b8152600401610895906149f5565b600481905560408051818152601391810191909152721b585c9ad95d13dc99195c9cd51a5b595bdd5d606a1b6060820152602081018290527f8cf3e35f6221b16e1670a3413180c9484bf5aa71787905909fa82a6a2662e9ab90608001610bea565b6000546001600160a01b031633146121475760405162461bcd60e51b81526004016108959061490f565b6007805460ff8082161560ff1990921682179092556040519116151581527fda88b5dfaac55549d4ddddd43a09d4b911233df354952ebc9ac2041aa185343690602001610d30565b6000546001600160a01b031633146121b95760405162461bcd60e51b81526004016108959061490f565b600081116121d95760405162461bcd60e51b8152600401610895906149f5565b600381905560408051818152601391810191909152726c696d69744f726465727354696d656c6f636b60681b6060820152602081018290527f8cf3e35f6221b16e1670a3413180c9484bf5aa71787905909fa82a6a2662e9ab90608001610bea565b6001546001600160a01b03163314801561225f57506001546001600160a01b031615155b6122ab5760405162461bcd60e51b815260206004820152601e60248201527f4e6f7420746865204558495354494e472070656e64696e672061646d696e00006044820152606401610895565b60008054600180546001600160a01b038082166001600160a01b031980861682179096559490911690915560408051919092168082526020820184905292917ff9ffabca9c8276e99321725bcb43fb076a6c66a54b7f21c4e8146d8519b417dc910160405180910390a1600154604080516001600160a01b03808516825290921660208301527fca4f2f25d0898edd99413412fb94012f9e54ec8142f9b093e7720646a95b16a99101612065565b60007f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c85573d6000803e3d6000fd5b3233148061245957507f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663372e24706040518163ffffffff1660e01b8152600401602060405180830381865afa158015612420573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906124449190614987565b6001600160a01b0316336001600160a01b0316145b6124755760405162461bcd60e51b8152600401610895906149a4565b600754610100900460ff161561249d5760405162461bcd60e51b815260040161089590614949565b60075460ff16156124c05760405162461bcd60e51b815260040161089590614967565b6124c86126ef565b604051637cdca42760e11b8152600481018690523390600090819081906001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868169063f9b9484e90602401606060405180830381865afa158015612536573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061255a9190614a1d565b9250925092506000826001600160401b0316116125895760405162461bcd60e51b815260040161089590614a63565b61259484828b613059565b60028360058111156125a8576125a8614933565b146125e65760405162461bcd60e51b815260206004820152600e60248201526d1393d517d3d4115397d31253525560921b6044820152606401610895565b6003546125fc6001600160401b03841642614aa3565b101561263b5760405162461bcd60e51b815260206004820152600e60248201526d4c494d49545f54494d454c4f434b60901b6044820152606401610895565b604051634ffb4ffd60e11b8152600481018a90526001600160401b03808a16602483015280891660448301528088166064830152861660848201527f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8686001600160a01b031690639ff69ffa9060a401600060405180830381600087803b1580156126c457600080fd5b505af11580156126d8573d6000803e3d6000fd5b50505050505050506126e8612906565b5050505050565b7f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b031663f83d08ba6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561274a57600080fd5b505af1158015611672573d6000803e3d6000fd5b60008060007f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8686001600160a01b031663f9b9484e876040518263ffffffff1660e01b81526004016127b191815260200190565b606060405180830381865afa1580156127ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906127f29190614a1d565b9250925092506000826001600160401b0316116128215760405162461bcd60e51b815260040161089590614a63565b61282c878288613059565b600383600581111561284057612840614933565b1461287b5760405162461bcd60e51b815260206004820152600b60248201526a13d3931657d3d41153915160aa1b6044820152606401610895565b6000612885611d61565b6040516320e5cf4560e11b81529091506001600160a01b038216906341cb9e8a906128b8908a908a908a90600401614c60565b60a0604051808303816000875af11580156128d7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128fb9190614b8c565b505050505050505050565b7f0000000000000000000000004cf3d61165a6be8ff741320ad27cab57fae5c2076001600160a01b03166340da020f6040518163ffffffff1660e01b8152600401600060405180830381600087803b15801561274a57600080fd5b60006129706020880188614868565b6001600160a01b0316886001600160a01b0316141580156129aa5750612994612359565b6001600160a01b0316886001600160a01b031614155b15612b1d57600860006129c060208a018a614868565b6001600160a01b0316815260208101919091526040016000205460ff16612a1d5760405162461bcd60e51b815260206004820152601160248201527021a0a62622a92fa727aa2faa2920a222a960791b6044820152606401610895565b6000612a27610bf5565b90506001600160a01b038116612a7b5760405162461bcd60e51b815260206004820152601960248201527813d397d0915210531197d5149051125391d7d393d517d4d155603a1b6044820152606401610895565b6001600160a01b038116638416f9b3612a9760208b018b614868565b8b612aa860608d0160408e01614868565b60405160e085901b6001600160e01b03191681526001600160a01b0393841660048201529183166024830152909116604482015260208a01356064820152608401600060405180830381600087803b158015612b0357600080fd5b505af1158015612b17573d6000803e3d6000fd5b50505050505b612b2d60a0870160808801614c8b565b6001600160401b0316612b466080880160608901614c8b565b6001600160401b03161115612b8f5760405162461bcd60e51b815260206004820152600f60248201526e4d494e5f4d41585f5245564552534560881b6044820152606401610895565b612b9f60c0870160a08801614c8b565b6001600160401b03161580612bcb5750612bc0610100870160e08801614c8b565b6001600160401b0316155b612c175760405162461bcd60e51b815260206004820152601760248201527f4d554c5449504c455f54505f444546494e4954494f4e530000000000000000006044820152606401610895565b612c2760e0870160c08801614c8b565b6001600160401b03161580612c545750612c4961012087016101008801614c8b565b6001600160401b0316155b612ca05760405162461bcd60e51b815260206004820152601760248201527f4d554c5449504c455f534c5f444546494e4954494f4e530000000000000000006044820152606401610895565b620186a0612cb661012088016101008901614c8b565b6001600160401b031610612d0c5760405162461bcd60e51b815260206004820152601b60248201527f534c5f4f465f4d4f52455f5448414e5f3130305f50455243454e5400000000006044820152606401610895565b612d1c60c0870160a08801614c8b565b6001600160401b03161580612da95750612d396020870187614663565b612d7557612d4d6080870160608801614c8b565b6001600160401b0316612d6660c0880160a08901614c8b565b6001600160401b031610612da9565b612d8560a0870160808801614c8b565b6001600160401b0316612d9e60c0880160a08901614c8b565b6001600160401b0316115b612de05760405162461bcd60e51b8152602060048201526008602482015267057524f4e475f54560c41b6044820152606401610895565b612df060e0870160c08801614c8b565b6001600160401b03161580612e7d5750612e0d6020870187614663565b612e4957612e2160a0870160808801614c8b565b6001600160401b0316612e3a60e0880160c08901614c8b565b6001600160401b031611612e7d565b612e596080870160608801614c8b565b6001600160401b0316612e7260e0880160c08901614c8b565b6001600160401b0316105b612eb45760405162461bcd60e51b815260206004820152600860248201526715d493d391d7d4d360c21b6044820152606401610895565b8115612ec457612ec4878761364d565b6000806002876002811115612edb57612edb614933565b03612f7c5760405163195c521960e31b81526001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868169063cae290c890612f32908a908d908d908890600401614cca565b6020604051808303816000875af1158015612f51573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612f759190614e45565b905061301d565b6001876002811115612f9057612f90614933565b03612fe75760405163195c521960e31b81526001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868169063cae290c890612f32908a908d908d908890600401614cca565b60405162461bcd60e51b815260206004820152600b60248201526a155394d5541413d495115160aa1b6044820152606401610895565b8085877f076eb959a98c5de701c0d3d1bbb7b7b28fdef080e1356cb1d6c710a0c8b5cf6360405160405180910390a49998505050505050505050565b816001600160a01b0316836001600160a01b031614158015613094575061307e612359565b6001600160a01b0316836001600160a01b031614155b15610b33576001600160a01b03821660009081526008602052604090205460ff166130f55760405162461bcd60e51b815260206004820152601160248201527021a0a62622a92fa727aa2faa2920a222a960791b6044820152606401610895565b60006130ff610bf5565b90506001600160a01b0381166131535760405162461bcd60e51b815260206004820152601960248201527813d397d0915210531197d5149051125391d7d393d517d4d155603a1b6044820152606401610895565b60405163042e37c560e01b8152600481018390526000907f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8686001600160a01b03169063042e37c590602401608060405180830381865afa1580156131bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906131df9190614e74565b516040516381e6a99d60e01b81526001600160a01b03868116600483015287811660248301528083166044830152919250908316906381e6a99d9060640160006040518083038186803b15801561323557600080fd5b505afa1580156128fb573d6000803e3d6000fd5b60008060007f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8686001600160a01b031663f9b9484e886040518263ffffffff1660e01b815260040161329c91815260200190565b606060405180830381865afa1580156132b9573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132dd9190614a1d565b9250925092506000826001600160401b03161161330c5760405162461bcd60e51b815260040161089590614a63565b613317888289613059565b600383600581111561332b5761332b614933565b146133665760405162461bcd60e51b815260206004820152600b60248201526a13d3931657d3d41153915160aa1b6044820152606401610895565b6000613370611d61565b604051636277297960e01b81529091506001600160a01b038216906362772979906133a5908b908b908b908b90600401614edb565b60a0604051808303816000875af11580156133c4573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133e89190614b8c565b50505050505050505050565b60008060007f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8686001600160a01b031663f9b9484e876040518263ffffffff1660e01b815260040161344791815260200190565b606060405180830381865afa158015613464573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906134889190614a1d565b9250925092506000826001600160401b0316116134b75760405162461bcd60e51b815260040161089590614a63565b6134c2878288613059565b60048360058111156134d6576134d6614933565b0361351a5760405162461bcd60e51b81526020600482015260146024820152731053149150511657d091525391d7d0d313d4d15160621b6044820152606401610895565b6005546135306001600160401b03841642614aa3565b101561357e5760405162461bcd60e51b815260206004820152601e60248201527f4d494e5f4c4956455f54494d455f464f525f4d41524b45545f434c4f534500006044820152606401610895565b60075462010000900460ff167f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8686001600160a01b031663e640f33b88836135c557886135c8565b60005b846135d357886135dc565b6001600160401b035b6040516001600160e01b031960e086901b16815260048101939093526001600160401b039182166024840152166044820152606401600060405180830381600087803b15801561362b57600080fd5b505af115801561363f573d6000803e3d6000fd5b505050505050505050505050565b60006001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868166303b90a8761368e6060860160408701614868565b6040516001600160e01b031960e084901b1681526001600160a01b039091166004820152602401602060405180830381865afa1580156136d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136f69190614987565b90506001600160a01b03811661373e5760405162461bcd60e51b815260206004820152600d60248201526c1393d7d050d0d3d55395105395609a1b6044820152606401610895565b613749818484613daf565b7f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa8686001600160a01b031663f65d9dbe6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156137a7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906137cb9190614e45565b6001600160a01b037f00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa86816638c01936e61380a6060870160408801614868565b6138176020880188614868565b6138276040890160208a01614f11565b6040516001600160e01b031960e086901b1681526001600160a01b03938416600482015292909116602483015261ffff1660448201526064016040805180830381865afa15801561387c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906138a09190614f2e565b5163ffffffff16106138ea5760405162461bcd60e51b815260206004820152601360248201527226a0ac2faa2920a222a9afa822a92fa820a4a960691b6044820152606401610895565b60006001600160a01b03821663c2b1088361390b6040870160208801614f11565b6040516001600160e01b031960e084901b16815261ffff909116600482015260240161018060405180830381865afa15801561394b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061396f9190614f9a565b6020810151604051633979324d60e01b815261ffff90911660048201529091506000906001600160a01b03841690633979324d9060240160c060405180830381865afa1580156139c3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906139e7919061505e565b6040808401519051632f08b92f60e21b815261ffff90911660048201529091506000906001600160a01b0385169063bc22e4bc90602401608060405180830381865afa158015613a3b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613a5f9190615106565b90506000613a736060870160408801615161565b63ffffffff16118015613aa6575060608084015163ffffffff1690613a9d90870160408801615161565b63ffffffff1610155b613af25760405162461bcd60e51b815260206004820152601960248201527f4c455645524147455f544f4f5f4c4f575f464f525f50414952000000000000006044820152606401610895565b608083015163ffffffff16613b0d6060870160408801615161565b63ffffffff161115613b615760405162461bcd60e51b815260206004820152601a60248201527f4c455645524147455f544f4f5f484947485f464f525f504149520000000000006044820152606401610895565b6000613b736060870160408801615161565b63ffffffff16118015613ba55750602082015163ffffffff16613b9c6060870160408801615161565b63ffffffff1610155b613bf15760405162461bcd60e51b815260206004820152601a60248201527f4c455645524147455f544f4f5f4c4f575f464f525f47524f55500000000000006044820152606401610895565b816040015163ffffffff16856040016020810190613c0f9190615161565b63ffffffff161115613c635760405162461bcd60e51b815260206004820152601b60248201527f4c455645524147455f544f4f5f484947485f464f525f47524f555000000000006044820152606401610895565b6000613c886020870135613c7d6060890160408a01615161565b63ffffffff16614352565b90508360c00151811115613cd15760405162461bcd60e51b815260206004820152601060248201526f504f534954494f4e5f544f4f5f42494760801b6044820152606401610895565b6000856001600160a01b0316631dcf50ef6040518163ffffffff1660e01b8152600401602060405180830381865afa158015613d11573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613d359190614e45565b602084015190915063ffffffff166000620186a0613d53838661517e565b613d5d91906151ab565b9050828110156133e85760405162461bcd60e51b815260206004820152601b60248201527f444f45535f4e4f545f52454143485f4d494e5f4f50454e5f46454500000000006044820152606401610895565b6000613dbe6020830183614663565b613dd757613dd260a0830160808401614c8b565b613de7565b613de76080830160608401614c8b565b90506000613e578284876001600160a01b0316631cb92ed36040518163ffffffff1660e01b8152600401602060405180830381865afa158015613e2e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613e529190614e45565b614373565b905060006001600160a01b03861663167ba8bf6020860135613e7f6060880160408901615161565b613e8c6020890189614663565b6040516001600160e01b031960e086901b168152600481019390935263ffffffff919091166024830152151560448201526001600160401b0380871660648301528516608482015260a401602060405180830381865afa158015613ef4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f189190614e45565b905060006001600160a01b03871663657d6edf613f3b6040890160208a01614f11565b6040516001600160e01b031960e084901b16815261ffff9091166004820152602401602060405180830381865afa158015613f7a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190613f9e9190614e45565b90506000613fac8383614aec565b90506001600160a01b038816633cb57be7613fcd60408a0160208b01614f11565b6040516001600160e01b031960e084901b16815261ffff9091166004820152602401602060405180830381865afa15801561400c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906140309190614e45565b8111156140715760405162461bcd60e51b815260206004820152600f60248201526e26a0ac2fa127a92927abafa820a4a960891b6044820152606401610895565b60006001600160a01b03891663c2b1088361409260408b0160208c01614f11565b6040516001600160e01b031960e084901b16815261ffff909116600482015260240161018060405180830381865afa1580156140d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906140f69190614f9a565b6020015160405163340de84760e21b815261ffff821660048201529091506000906001600160a01b038b169063d037a11c90602401602060405180830381865afa158015614148573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061416c9190614e45565b9050600061417a8683614aec565b6040516340691c9560e01b815261ffff851660048201529091506001600160a01b038c16906340691c9590602401602060405180830381865afa1580156141c5573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906141e99190614e45565b81111561422b5760405162461bcd60e51b815260206004820152601060248201526f04d41585f424f52524f575f47524f55560841b6044820152606401610895565b60008b6001600160a01b03166347bd37186040518163ffffffff1660e01b8152600401602060405180830381865afa15801561426b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061428f9190614e45565b9050600061429d8883614aec565b90508c6001600160a01b03166388c8f1786040518163ffffffff1660e01b8152600401602060405180830381865afa1580156142dd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906143019190614e45565b8111156143435760405162461bcd60e51b815260206004820152601060248201526f4d41585f544f54414c5f424f52524f5760801b6044820152606401610895565b50505050505050505050505050565b60006064614360838561517e565b61436a91906151ab565b90505b92915050565b600061438560c0840160a08501614c8b565b9050600061439a610100850160e08601614c8b565b6001600160401b0316111561442b5760006143db856143c0610100870160e08801614c8b565b6143d06060880160408901615161565b63ffffffff16614461565b90506143ea6020850185614663565b61441d57846001600160401b0316816001600160401b03161061440e576000614427565b61441881866151bf565b614427565b61442781866151e6565b9150505b61445982856144406060870160408801615161565b63ffffffff16846144546020890189614663565b6144b9565b949350505050565b600080826001600160401b0316620186a06064866001600160401b0316886001600160401b0316614492919061517e565b61449c919061517e565b6144a691906151ab565b6144b091906151ab565b95945050505050565b60006001600160401b03831615806144e357508560070b6144dd8787868689614589565b60070b12155b1561457f576000620186a0856001600160401b03166064896001600160401b0316896001600160401b0316614518919061517e565b614522919061517e565b61452c91906151ab565b61453691906151ab565b90508261456d57856001600160401b0316816001600160401b0316111561455e576000614577565b61456881876151bf565b614577565b61457781876151e6565b9150506144b0565b5090949350505050565b60008581846145a15761459c8688615206565b6145ab565b6145ab8787615206565b905060008460070b620186a08360070b6145c59190615235565b6145cf9190615235565b90506000600789900b6145e3606484615265565b6145ed9190615265565b90508094508360070b8560070b136146055784614607565b835b9a9950505050505050505050565b80356005811061462457600080fd5b919050565b6000806040838503121561463c57600080fd5b61464583614615565b946020939093013593505050565b8035801515811461462457600080fd5b60006020828403121561467557600080fd5b61436a82614653565b6004811061120157600080fd5b6001600160401b038116811461120157600080fd5b80356146248161468b565b6000806000606084860312156146c057600080fd5b8335925060208401356146d28161467e565b915060408401356146e28161468b565b809150509250925092565b6000602082840312156146ff57600080fd5b5035919050565b60006020808352835180602085015260005b8181101561473457858101830151858201604001528201614718565b506000604082860101526040601f19601f8301168501019250505092915050565b60008060008060008086880361022081121561477057600080fd5b608081121561477e57600080fd5b879650610120607f198201121561479457600080fd5b506080870194506101a0870135600381106147ae57600080fd5b93506101c087013592506101e087013591506147cd6102008801614653565b90509295509295509295565b600080600080608085870312156147ef57600080fd5b8435935060208501356148018161467e565b925060408501356148118161468b565b915060608501356148218161468b565b939692955090935050565b60008060006060848603121561484157600080fd5b8335925060208401356146d28161468b565b6001600160a01b038116811461120157600080fd5b60006020828403121561487a57600080fd5b813561488581614853565b9392505050565b60006020828403121561489e57600080fd5b61436a82614615565b600080600080600060a086880312156148bf57600080fd5b8535945060208601356148d18161468b565b935060408601356148e18161468b565b925060608601356148f18161468b565b915060808601356149018161468b565b809150509295509295909350565b6020808252600a908201526927a7262cafa0a226a4a760b11b604082015260600190565b634e487b7160e01b600052602160045260246000fd5b602080825260049082015263444f4e4560e01b604082015260600190565b60208082526006908201526514105554d15160d21b604082015260600190565b60006020828403121561499957600080fd5b815161488581614853565b6020808252600c908201526b1393d517d0d3d395149050d560a21b604082015260600190565b6020808252601190820152704e4f545f454e4f5547485f4e415449564560781b604082015260600190565b6020808252600e908201526d43414e4e4f545f42455f5a45524f60901b604082015260600190565b600080600060608486031215614a3257600080fd5b835160068110614a4157600080fd5b6020850151909350614a528161468b565b60408501519092506146e281614853565b60208082526010908201526f2727afa9aaa1a42fa827a9a4aa24a7a760811b604082015260600190565b634e487b7160e01b600052601160045260246000fd5b8181038181111561436d5761436d614a8d565b60038110614ac657614ac6614933565b9052565b83815260608101614ade6020830185614ab6565b826040830152949350505050565b8082018082111561436d5761436d614a8d565b6020808252600c908201526b15d0525517d512535153d55560a21b604082015260600190565b604051608081016001600160401b0381118282101715614b5557634e487b7160e01b600052604160045260246000fd5b60405290565b60405161018081016001600160401b0381118282101715614b5557634e487b7160e01b600052604160045260246000fd5b600060a08284031215614b9e57600080fd5b60405160a081018181106001600160401b0382111715614bce57634e487b7160e01b600052604160045260246000fd5b604052825181526020830151614be38161467e565b60208201526040830151614bf68161468b565b60408201526060830151614c098161468b565b60608201526080830151614c1c8161468b565b60808201529392505050565b8381526060810160028410614c3f57614c3f614933565b602082019390935260400152919050565b60048110614ac657614ac6614933565b83815260608101614c746020830185614c50565b6001600160401b0383166040830152949350505050565b600060208284031215614c9d57600080fd5b81356148858161468b565b61ffff8116811461120157600080fd5b63ffffffff8116811461120157600080fd5b6101e08101614cd98287614ab6565b8435614ce481614853565b6001600160a01b0390811660208481019190915286013590614d0582614ca8565b61ffff8216604085015260408701359150614d1f82614853565b16606083810191909152850135614d3581614cb8565b63ffffffff166080830152614d4984614653565b151560a0830152602084013560c08301526040840135614d6881614cb8565b63ffffffff1660e0830152614d7f606085016146a0565b610100614d96818501836001600160401b03169052565b614da2608087016146a0565b6001600160401b0381166101208601529150614dc060a087016146a0565b6001600160401b0381166101408601529150614dde60c087016146a0565b6001600160401b0381166101608601529150614dfc60e087016146a0565b6001600160401b0381166101808601529150614e198187016146a0565b915050614e326101a08401826001600160401b03169052565b5063ffffffff83166101c08301526144b0565b600060208284031215614e5757600080fd5b5051919050565b805161462481614ca8565b805161462481614cb8565b600060808284031215614e8657600080fd5b614e8e614b25565b8251614e9981614853565b81526020830151614ea981614ca8565b60208201526040830151614ebc81614cb8565b60408201526060830151614ecf81614853565b60608201529392505050565b84815260808101614eef6020830186614c50565b6001600160401b03808516604084015280841660608401525095945050505050565b600060208284031215614f2357600080fd5b813561488581614ca8565b600060408284031215614f4057600080fd5b604051604081018181106001600160401b0382111715614f7057634e487b7160e01b600052604160045260246000fd5b6040528251614f7e81614cb8565b81526020830151614f8e81614cb8565b60208201529392505050565b60006101808284031215614fad57600080fd5b614fb5614b5b565b614fbe83614e5e565b8152614fcc60208401614e5e565b6020820152614fdd60408401614e5e565b6040820152614fee60608401614e69565b6060820152614fff60808401614e69565b608082015261501060a08401614e69565b60a082015260c0838101519082015260e08084015190820152610100808401519082015261012080840151908201526101408084015190820152610160928301519281019290925250919050565b600060c0828403121561507057600080fd5b60405160c081018181106001600160401b03821117156150a057634e487b7160e01b600052604160045260246000fd5b60405282516150ae81614ca8565b815260208301516150be81614cb8565b602082015260408301516150d181614cb8565b604082015260608301516150e481614cb8565b60608201526080838101519082015260a0928301519281019290925250919050565b60006080828403121561511857600080fd5b615120614b25565b825161512b81614ca8565b8152602083015161513b81614cb8565b6020820152604083015161514e81614cb8565b60408201526060830151614ecf81614cb8565b60006020828403121561517357600080fd5b813561488581614cb8565b808202811582820484141761436d5761436d614a8d565b634e487b7160e01b600052601260045260246000fd5b6000826151ba576151ba615195565b500490565b6001600160401b038281168282160390808211156151df576151df614a8d565b5092915050565b6001600160401b038181168382160190808211156151df576151df614a8d565b600782810b9082900b03677fffffffffffffff198112677fffffffffffffff8213171561436d5761436d614a8d565b80820260008212600160ff1b8414161561525157615251614a8d565b818105831482151761436d5761436d614a8d565b60008261527457615274615195565b600160ff1b82146000198414161561528e5761528e614a8d565b50059056fea2646970667358221220d2642bdb87ca976377e5f48ccd444796041570cbc6701874f8a73fb234c3ef1b64736f6c63430008180033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868
-----Decoded View---------------
Arg [0] : _tradingFloor (address): 0x37792EecFA985D0b00a51864c970e7df406AA868
-----Encoded View---------------
1 Constructor Arguments found :
Arg [0] : 00000000000000000000000037792eecfa985d0b00a51864c970e7df406aa868
Loading...
Loading
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in S
Token Allocations
S
100.00%
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|---|---|---|---|---|
| SONIC | 100.00% | $0.067895 | 0.0000000000000141 | <$0.000001 |
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
[ 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.