Verified contractPartialGPL-3.0-only
SolverNetInbox
Address0x7ef99531f2bd2e8a7772cb440b96a946e6563202
- Balance
0 ETH
- Transactions
1
- Compiler
solc 0.8.24
- Same code
Only this contract
Details
- Compiler
- solc 0.8.24+commit.e11b9ed9
- Language
- solidity
- Optimization
- Yes, 200 runs
- EVM version
- cancun
- License
- GPL-3.0-only
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 22,039,109
- Creation transaction
- 0x011958d1a0…5636a04b4a
18 files
- src/SolverNetInbox.solmain23.79 KB
- ../core/src/interfaces/IOmniPortal.sol5.93 KB
- ../core/src/interfaces/IOmniPortalPausable.sol689 B
- ../core/src/libraries/ConfLevel.sol1.12 KB
- ../core/src/libraries/XTypes.sol4.3 KB
- ../core/src/pkg/XAppBase.sol4.53 KB
- node_modules/solady/src/auth/Ownable.sol12.55 KB
- node_modules/solady/src/auth/OwnableRoles.sol25.85 KB
- node_modules/solady/src/utils/Initializable.sol8.48 KB
- node_modules/solady/src/utils/ReentrancyGuard.sol2.33 KB
- node_modules/solady/src/utils/SafeTransferLib.sol29 KB
- src/erc7683/IERC7683.sol5.49 KB
- src/erc7683/IOriginSettler.sol2.18 KB
- src/ext/IArbSys.sol547 B
- src/interfaces/ISolverNetInbox.sol5.44 KB
- src/lib/AddrUtils.sol514 B
- src/lib/SolverNet.sol4.64 KB
- src/util/DeployedAt.sol1.36 KB
src/SolverNetInbox.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity =0.8.24;
import { OwnableRoles } from "solady/src/auth/OwnableRoles.sol";
import { ReentrancyGuard } from "solady/src/utils/ReentrancyGuard.sol";
import { Initializable } from "solady/src/utils/Initializable.sol";
import { DeployedAt } from "./util/DeployedAt.sol";
import { XAppBase } from "core/src/pkg/XAppBase.sol";
import { IERC7683 } from "./erc7683/IERC7683.sol";
import { ISolverNetInbox } from "./interfaces/ISolverNetInbox.sol";
import { SafeTransferLib } from "solady/src/utils/SafeTransferLib.sol";
import { SolverNet } from "./lib/SolverNet.sol";
import { AddrUtils } from "./lib/AddrUtils.sol";
import { IOmniPortalPausable } from "core/src/interfaces/IOmniPortalPausable.sol";
/**
* @title SolverNetInbox
* @notice Entrypoint and alt-mempool for user solve orders.
*/
contract SolverNetInbox is OwnableRoles, ReentrancyGuard, Initializable, DeployedAt, XAppBase, ISolverNetInbox {
using SafeTransferLib for address;
using AddrUtils for address;
/**
* @notice Maximum number of calls and expenses in an order.
*/
uint8 internal constant MAX_ARRAY_SIZE = 32;
/**
* @notice Buffer for closing orders after fill deadline to give Omni Core relayer time to act.
*/
uint256 internal constant CLOSE_BUFFER = 6 hours;
/**
* @notice Role for solvers.
* @dev _ROLE_0 evaluates to '1'.
*/
uint256 internal constant SOLVER = _ROLE_0;
/**
* @notice Typehash for the OrderData struct.
*/
bytes32 internal constant ORDERDATA_TYPEHASH = keccak256(
"OrderData(address owner,uint64 destChainId,Deposit deposit,Call[] calls,TokenExpense[] expenses)Deposit(address token,uint96 amount)Call(address target,bytes4 selector,uint256 value,bytes params)TokenExpense(address spender,address token,uint96 amount)"
);
/**
* @notice Action ID for xsubmissions, used as Pauseable key in OmniPortal
*/
bytes32 internal constant ACTION_XSUBMIT = keccak256("xsubmit");
/**
* @notice Key for pausing the `open` function.
*/
bytes32 internal constant OPEN = keccak256("OPEN");
/**
* @notice Key for pausing the `close` function.
*/
bytes32 internal constant CLOSE = keccak256("CLOSE");
uint8 internal constant NONE_PAUSED = 0;
uint8 internal constant OPEN_PAUSED = 1;
uint8 internal constant CLOSE_PAUSED = 2;
uint8 internal constant ALL_PAUSED = 3;
/**
* @dev Incremental order offset for source inbox orders.
*/
uint248 internal _offset;
/**
* @notice Pause state.
* @dev 0 = no pause, 1 = open paused, 2 = close paused, 3 = all paused.
*/
uint8 public pauseState;
/**
* @notice Addresses of the outbox contracts.
*/
mapping(uint64 chainId => address outbox) internal _outboxes;
/**
* @notice Map order ID to header parameters.
* @dev (owner, destChainId, fillDeadline)
*/
mapping(bytes32 id => SolverNet.Header) internal _orderHeader;
/**
* @notice Map order ID to deposit parameters.
* @dev (token, amount)
*/
mapping(bytes32 id => SolverNet.Deposit) internal _orderDeposit;
/**
* @notice Map order ID to call parameters.
* @dev (target, selector, value, params)
*/
mapping(bytes32 id => SolverNet.Call[]) internal _orderCalls;
/**
* @notice Map order ID to expense parameters.
* @dev (spender, token, amount)
*/
mapping(bytes32 id => SolverNet.TokenExpense[]) internal _orderExpenses;
/**
* @notice Map order ID to order parameters.
*/
mapping(bytes32 id => OrderState) internal _orderState;
/**
* @notice Map order ID to order offset.
*/
mapping(bytes32 id => uint248) internal _orderOffset;
/**
* @notice Map user to nonce.
*/
mapping(address user => uint256 nonce) internal _userNonce;
/**
* @notice Modifier to ensure contract functions are not paused.
*/
modifier whenNotPaused(bytes32 pauseKey) {
uint8 _pauseState = pauseState;
if (_pauseState != NONE_PAUSED) {
if (_pauseState == OPEN_PAUSED && pauseKey == OPEN) revert IsPaused();
if (_pauseState == CLOSE_PAUSED && pauseKey == CLOSE) revert IsPaused();
if (_pauseState == ALL_PAUSED) revert AllPaused();
}
_;
}
constructor() {
_disableInitializers();
}
/**
* @notice Initialize the contract's owner and solver.
* @dev Used instead of constructor as we want to use the transparent upgradeable proxy pattern.
* @param owner_ Address of the owner.
* @param solver_ Address of the solver.
* @param omni_ Address of the OmniPortal.
*/
function initialize(address owner_, address solver_, address omni_) external initializer {
_initializeOwner(owner_);
_grantRoles(solver_, SOLVER);
_setOmniPortal(omni_);
}
/**
* @notice Pause the `open` function, preventing new orders from being opened.
* @dev Cannot override ALL_PAUSED state.
* @param pause True to pause, false to unpause.
*/
function pauseOpen(bool pause) external onlyOwnerOrRoles(SOLVER) {
_setPauseState(OPEN, pause);
}
/**
* @notice Pause the `close` function, preventing orders from being closed by users.
* @dev `close` should only be paused if the Omni Core relayer is not available.
* @dev Cannot override ALL_PAUSED state.
* @param pause True to pause, false to unpause.
*/
function pauseClose(bool pause) external onlyOwnerOrRoles(SOLVER) {
_setPauseState(CLOSE, pause);
}
/**
* @notice Pause open and close functions.
* @dev Can override OPEN_PAUSED or CLOSE_PAUSED states.
* @param pause True to pause, false to unpause.
*/
function pauseAll(bool pause) external onlyOwnerOrRoles(SOLVER) {
pause ? pauseState = ALL_PAUSED : pauseState = NONE_PAUSED;
}
/**
* @notice Set the outbox addresses for the given chain IDs.
* @param chainIds IDs of the chains.
* @param outboxes Addresses of the outboxes.
*/
function setOutboxes(uint64[] calldata chainIds, address[] calldata outboxes) external onlyOwner {
if (chainIds.length != outboxes.length) revert InvalidArrayLength();
for (uint256 i; i < chainIds.length; ++i) {
_outboxes[chainIds[i]] = outboxes[i];
emit OutboxSet(chainIds[i], outboxes[i]);
}
}
/**
* @notice Returns the order, its state, and offset with the given ID.
* @param id ID of the order.
*/
function getOrder(bytes32 id)
external
view
returns (ResolvedCrossChainOrder memory resolved, OrderState memory state, uint248 offset)
{
SolverNet.Order memory orderData = _getOrder(id);
return (_resolve(orderData, id), _orderState[id], _orderOffset[id]);
}
/**
* @notice Returns the order ID for the given user and nonce.
* @param user Address of the user.
* @param nonce Nonce of the order.
*/
function getOrderId(address user, uint256 nonce) external view returns (bytes32) {
return _getOrderId(user, nonce);
}
/**
* @notice Returns the next order ID for the given user.
* @param user Address of the user.
*/
function getNextOrderId(address user) external view returns (bytes32) {
return _getOrderId(user, _userNonce[user]);
}
/**
* @notice Returns the nonce for the given user.
* @param user Address of the user.
*/
function getUserNonce(address user) external view returns (uint256) {
return _userNonce[user];
}
/**
* @notice Returns the order offset of the latest order opened at this inbox.
*/
function getLatestOrderOffset() external view returns (uint248) {
return _offset;
}
/**
* @dev Validate the onchain order.
* @param order OnchainCrossChainOrder to validate.
*/
function validate(OnchainCrossChainOrder calldata order) external view returns (bool) {
_validate(order);
return true;
}
/**
* @notice Resolve the onchain order with validation.
* @param order OnchainCrossChainOrder to resolve.
*/
function resolve(OnchainCrossChainOrder calldata order) public view returns (ResolvedCrossChainOrder memory) {
SolverNet.Order memory orderData = _validate(order);
address user = orderData.header.owner;
return _resolve(orderData, _getOrderId(user, _userNonce[user]));
}
/**
* @notice Open an order to execute a call on another chain, backed by deposits.
* @dev Token deposits are transferred from msg.sender to this inbox.
* @param order OnchainCrossChainOrder to open.
*/
function open(OnchainCrossChainOrder calldata order) external payable whenNotPaused(OPEN) nonReentrant {
SolverNet.Order memory orderData = _validate(order);
_processDeposit(orderData.deposit);
ResolvedCrossChainOrder memory resolved = _openOrder(orderData);
emit Open(resolved.orderId, resolved);
}
/**
* @notice Reject an open order and refund deposits.
* @dev Only a whitelisted solver can reject.
* @param id ID of the order.
* @param reason Reason code for rejection.
*/
function reject(bytes32 id, uint8 reason) external onlyRoles(SOLVER) nonReentrant {
OrderState memory state = _orderState[id];
if (reason == 0) revert InvalidReason();
if (state.status != Status.Pending) revert OrderNotPending();
_upsertOrder(id, Status.Rejected, reason, msg.sender);
_transferDeposit(id, _orderHeader[id].owner);
_purgeState(id, Status.Rejected);
emit Rejected(id, msg.sender, reason);
}
/**
* @notice Close order and refund deposits after fill deadline has elapsed.
* @dev Only order initiator can close.
* @param id ID of the order.
*/
function close(bytes32 id) external whenNotPaused(CLOSE) nonReentrant {
OrderState memory state = _orderState[id];
SolverNet.Header memory header = _orderHeader[id];
if (state.status != Status.Pending) revert OrderNotPending();
if (header.owner != msg.sender) revert Unauthorized();
if (IOmniPortalPausable(address(omni)).isPaused(ACTION_XSUBMIT, header.destChainId)) revert PortalPaused();
if (header.fillDeadline + CLOSE_BUFFER >= block.timestamp) revert OrderStillValid();
_upsertOrder(id, Status.Closed, 0, msg.sender);
_transferDeposit(id, header.owner);
_purgeState(id, Status.Closed);
emit Closed(id);
}
/**
* @notice Fill an order.
* @dev Only callable by the outbox.
* @param id ID of the order.
* @param fillHash Hash of fill instructions origin data.
* @param creditedTo Address deposits are credited to, provided by the filler.
*/
function markFilled(bytes32 id, bytes32 fillHash, address creditedTo) external xrecv {
SolverNet.Header memory header = _orderHeader[id];
OrderState memory state = _orderState[id];
if (state.status != Status.Pending) revert OrderNotPending();
if (xmsg.sourceChainId != header.destChainId) revert WrongSourceChain();
if (xmsg.sender != _outboxes[xmsg.sourceChainId]) revert Unauthorized();
// Ensure reported fill hash matches origin data
if (fillHash != _fillHash(id)) {
revert WrongFillHash();
}
_upsertOrder(id, Status.Filled, 0, creditedTo);
_purgeState(id, Status.Filled);
emit Filled(id, fillHash, creditedTo);
}
/**
* @notice Claim deposits for a filled order.
* @param id ID of the order.
* @param to Address to send deposits to.
*/
function claim(bytes32 id, address to) external nonReentrant {
OrderState memory state = _orderState[id];
if (state.status != Status.Filled) revert OrderNotFilled();
if (state.updatedBy != msg.sender) revert Unauthorized();
_upsertOrder(id, Status.Claimed, 0, msg.sender);
_transferDeposit(id, to);
_purgeState(id, Status.Claimed);
emit Claimed(id, msg.sender, to);
}
/**
* @dev Return the order for the given ID.
* @param id ID of the order.
*/
function _getOrder(bytes32 id) internal view returns (SolverNet.Order memory) {
return SolverNet.Order({
header: _orderHeader[id],
calls: _orderCalls[id],
deposit: _orderDeposit[id],
expenses: _orderExpenses[id]
});
}
/**
* @dev Parse and return order data, validate correctness.
* @param order OnchainCrossChainOrder to parse
*/
function _validate(OnchainCrossChainOrder calldata order) internal view returns (SolverNet.Order memory) {
// Validate OnchainCrossChainOrder
if (order.fillDeadline <= block.timestamp) revert InvalidFillDeadline();
if (order.orderDataType != ORDERDATA_TYPEHASH) revert InvalidOrderTypehash();
if (order.orderData.length == 0) revert InvalidOrderData();
SolverNet.OrderData memory orderData = abi.decode(order.orderData, (SolverNet.OrderData));
// Validate SolverNet.OrderData.Header fields
if (orderData.owner == address(0)) orderData.owner = msg.sender;
if (orderData.destChainId == 0 || orderData.destChainId == block.chainid) revert InvalidChainId();
SolverNet.Header memory header = SolverNet.Header({
owner: orderData.owner,
destChainId: orderData.destChainId,
fillDeadline: order.fillDeadline
});
// Validate SolverNet.OrderData.Call
SolverNet.Call[] memory calls = orderData.calls;
if (calls.length == 0) revert InvalidMissingCalls();
if (calls.length > MAX_ARRAY_SIZE) revert InvalidArrayLength();
for (uint256 i; i < calls.length; ++i) {
SolverNet.Call memory call = calls[i];
if (call.target == address(0)) revert InvalidCallTarget();
}
// Validate SolverNet.OrderData.Expenses
SolverNet.TokenExpense[] memory expenses = orderData.expenses;
if (expenses.length > MAX_ARRAY_SIZE) revert InvalidArrayLength();
for (uint256 i; i < expenses.length; ++i) {
if (expenses[i].token == address(0)) revert InvalidExpenseToken();
if (expenses[i].amount == 0) revert InvalidExpenseAmount();
}
return SolverNet.Order({ header: header, calls: calls, deposit: orderData.deposit, expenses: expenses });
}
/**
* @dev Derive the maxSpent Output for the order.
* @param orderData Order data to derive from.
*/
function _deriveMaxSpent(SolverNet.Order memory orderData) internal view returns (IERC7683.Output[] memory) {
SolverNet.Header memory header = orderData.header;
SolverNet.Call[] memory calls = orderData.calls;
SolverNet.TokenExpense[] memory expenses = orderData.expenses;
uint256 totalNativeValue;
for (uint256 i; i < calls.length; ++i) {
if (calls[i].value > 0) totalNativeValue += calls[i].value;
}
IERC7683.Output[] memory maxSpent =
new IERC7683.Output[](totalNativeValue > 0 ? expenses.length + 1 : expenses.length);
for (uint256 i; i < expenses.length; ++i) {
maxSpent[i] = IERC7683.Output({
token: expenses[i].token.toBytes32(),
amount: expenses[i].amount,
recipient: _outboxes[header.destChainId].toBytes32(),
chainId: header.destChainId
});
}
if (totalNativeValue > 0) {
maxSpent[expenses.length] = IERC7683.Output({
token: bytes32(0),
amount: totalNativeValue,
recipient: _outboxes[header.destChainId].toBytes32(),
chainId: header.destChainId
});
}
return maxSpent;
}
/**
* @dev Derive the minReceived Output for the order.
* @param orderData Order data to derive from.
*/
function _deriveMinReceived(SolverNet.Order memory orderData) internal view returns (IERC7683.Output[] memory) {
SolverNet.Deposit memory deposit = orderData.deposit;
IERC7683.Output[] memory minReceived = new IERC7683.Output[](deposit.amount > 0 ? 1 : 0);
if (deposit.amount > 0) {
minReceived[0] = IERC7683.Output({
token: deposit.token.toBytes32(),
amount: deposit.amount,
recipient: bytes32(0),
chainId: block.chainid
});
}
return minReceived;
}
/**
* @dev Derive the fillInstructions for the order.
* @param orderData Order data to derive from.
*/
function _deriveFillInstructions(SolverNet.Order memory orderData)
internal
view
returns (IERC7683.FillInstruction[] memory)
{
SolverNet.Header memory header = orderData.header;
SolverNet.Call[] memory calls = orderData.calls;
SolverNet.TokenExpense[] memory expenses = orderData.expenses;
IERC7683.FillInstruction[] memory fillInstructions = new IERC7683.FillInstruction[](1);
fillInstructions[0] = IERC7683.FillInstruction({
destinationChainId: header.destChainId,
destinationSettler: _outboxes[header.destChainId].toBytes32(),
originData: abi.encode(
SolverNet.FillOriginData({
srcChainId: uint64(block.chainid),
destChainId: header.destChainId,
fillDeadline: header.fillDeadline,
calls: calls,
expenses: expenses
})
)
});
return fillInstructions;
}
/**
* @dev Resolve the order without validation.
* @param orderData Order data to resolve.
*/
function _resolve(SolverNet.Order memory orderData, bytes32 id)
internal
view
returns (ResolvedCrossChainOrder memory)
{
SolverNet.Header memory header = orderData.header;
IERC7683.Output[] memory maxSpent = _deriveMaxSpent(orderData);
IERC7683.Output[] memory minReceived = _deriveMinReceived(orderData);
IERC7683.FillInstruction[] memory fillInstructions = _deriveFillInstructions(orderData);
return ResolvedCrossChainOrder({
user: header.owner,
originChainId: block.chainid,
openDeadline: 0,
fillDeadline: header.fillDeadline,
orderId: id,
maxSpent: maxSpent,
minReceived: minReceived,
fillInstructions: fillInstructions
});
}
/**
* @notice Validate and intake an ERC20 or native deposit.
* @param deposit Deposit to process.
*/
function _processDeposit(SolverNet.Deposit memory deposit) internal {
if (deposit.token == address(0)) {
if (msg.value != deposit.amount) revert InvalidNativeDeposit();
} else {
deposit.token.safeTransferFrom(msg.sender, address(this), deposit.amount);
}
}
/**
* @dev Opens a new order by initializing its state.
* @param orderData Order data to open.
*/
function _openOrder(SolverNet.Order memory orderData) internal returns (ResolvedCrossChainOrder memory resolved) {
address user = orderData.header.owner;
bytes32 id = _getOrderId(user, _userNonce[user]++);
resolved = _resolve(orderData, id);
_orderHeader[id] = orderData.header;
_orderDeposit[id] = orderData.deposit;
_orderOffset[id] = _incrementOffset();
for (uint256 i; i < orderData.calls.length; ++i) {
_orderCalls[id].push(orderData.calls[i]);
}
for (uint256 i; i < orderData.expenses.length; ++i) {
_orderExpenses[id].push(orderData.expenses[i]);
}
_upsertOrder(id, Status.Pending, 0, msg.sender);
return resolved;
}
/**
* @dev Transfer deposit to recipient. Used for both refunds and claims.
* @param id ID of the order.
* @param to Address to send deposits to.
*/
function _transferDeposit(bytes32 id, address to) internal {
SolverNet.Deposit memory deposit = _orderDeposit[id];
if (deposit.amount > 0) {
if (deposit.token == address(0)) to.safeTransferETH(deposit.amount);
else deposit.token.safeTransfer(to, deposit.amount);
}
}
/**
* @dev Update or insert order state by id.
* @param id ID of the order.
* @param status Status to upsert.
* @param rejectReason Reason code for rejecting the order, if rejected.
* @param updatedBy Address updating the order.
*/
function _upsertOrder(bytes32 id, Status status, uint8 rejectReason, address updatedBy) internal {
uint8 _rejectReason = _orderState[id].rejectReason;
_orderState[id] = OrderState({
status: status,
rejectReason: rejectReason > 0 ? rejectReason : _rejectReason,
timestamp: uint32(block.timestamp),
updatedBy: updatedBy
});
}
/**
* @dev Purge order state after it is no longer needed.
* @param id ID of the order.
* @param status Status of the order.
*/
function _purgeState(bytes32 id, Status status) internal {
if (status == Status.Pending) return;
if (status != Status.Filled) delete _orderDeposit[id];
if (status != Status.Claimed) {
delete _orderHeader[id];
delete _orderCalls[id];
delete _orderExpenses[id];
}
}
/**
* @dev Derive order ID from user and nonce.
* @param user Address of the user.
* @param nonce Nonce of the order.
*/
function _getOrderId(address user, uint256 nonce) internal view returns (bytes32) {
return keccak256(abi.encode(user, nonce, block.chainid));
}
/**
* @dev Increment and return the next order offset.
*/
function _incrementOffset() internal returns (uint248) {
return ++_offset;
}
/**
* @dev Returns call hash. Used to discern fulfillment.
* @param orderId ID of the order.
*/
function _fillHash(bytes32 orderId) internal view returns (bytes32) {
SolverNet.Header memory header = _orderHeader[orderId];
SolverNet.Call[] memory calls = _orderCalls[orderId];
SolverNet.TokenExpense[] memory expenses = _orderExpenses[orderId];
SolverNet.FillOriginData memory fillOriginData = SolverNet.FillOriginData({
srcChainId: uint64(block.chainid),
destChainId: header.destChainId,
fillDeadline: header.fillDeadline,
calls: calls,
expenses: expenses
});
return keccak256(abi.encode(orderId, abi.encode(fillOriginData)));
}
/**
* @notice Pause the `open` or `close` function
* @dev Cannot override ALL_PAUSED state
* @param key OPEN or CLOSE pause key
* @param pause True to pause, false to unpause
*/
function _setPauseState(bytes32 key, bool pause) internal {
uint8 _pauseState = pauseState;
if (_pauseState == ALL_PAUSED) revert AllPaused();
uint8 targetState = key == OPEN ? OPEN_PAUSED : CLOSE_PAUSED;
if (pause ? _pauseState == targetState : _pauseState != targetState) revert IsPaused();
pauseState = pause ? targetState : NONE_PAUSED;
}
}
../core/src/interfaces/IOmniPortal.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.12;
import { XTypes } from "../libraries/XTypes.sol";
/**
* @title IOmniPortal
* @notice The OmniPortal is the on-chain interface to Omni's cross-chain
* messaging protocol. It is used to initiate and execute cross-chain calls.
*/
interface IOmniPortal {
/**
* @notice Emitted when an xcall is made to a contract on another chain
* @param destChainId Destination chain ID
* @param offset Offset this XMsg in the source -> dest XStream
* @param sender msg.sender of the source xcall
* @param to Address of the contract to call on the destination chain
* @param data Encoded function calldata
* @param gasLimit Gas limit for execution on destination chain
* @param fees Fees paid for the xcall
*/
event XMsg(
uint64 indexed destChainId,
uint64 indexed shardId,
uint64 indexed offset,
address sender,
address to,
bytes data,
uint64 gasLimit,
uint256 fees
);
/**
* @notice Emitted when an XMsg is executed on its destination chain
* @param sourceChainId Source chain ID
* @param shardId Shard ID of the XStream (last byte is the confirmation level)
* @param offset Offset the XMsg in the source -> dest XStream
* @param gasUsed Gas used in execution of the XMsg
* @param relayer Address of the relayer who submitted the XMsg
* @param success Whether the execution succeeded
* @param err Result of XMsg execution, if success == false. Limited to
* xreceiptMaxErrorBytes(). Empty if success == true.
*/
event XReceipt(
uint64 indexed sourceChainId,
uint64 indexed shardId,
uint64 indexed offset,
uint256 gasUsed,
address relayer,
bool success,
bytes err
);
/**
* @notice Maximum allowed xmsg gas limit
*/
function xmsgMaxGasLimit() external view returns (uint64);
/**
* @notice Minimum allowed xmsg gas limit
*/
function xmsgMinGasLimit() external view returns (uint64);
/**
* @notice Maximum number of bytes allowed in xmsg data
*/
function xmsgMaxDataSize() external view returns (uint16);
/**
* @notice Maximum number of bytes allowed in xreceipt result
*/
function xreceiptMaxErrorSize() external view returns (uint16);
/**
* @notice Returns the fee oracle address
*/
function feeOracle() external view returns (address);
/**
* @notice Returns the chain ID of the chain to which this portal is deployed
*/
function chainId() external view returns (uint64);
/**
* @notice Returns the chain ID of Omni's EVM execution chain
*/
function omniChainId() external view returns (uint64);
/**
* @notice Returns the offset of the last outbound XMsg sent to destChainId in shardId
*/
function outXMsgOffset(uint64 destChainId, uint64 shardId) external view returns (uint64);
/**
* @notice Returns the offset of the last inbound XMsg received from srcChainId in shardId
*/
function inXMsgOffset(uint64 srcChainId, uint64 shardId) external view returns (uint64);
/**
* @notice Returns the offset of the last inbound XBlock received from srcChainId in shardId
*/
function inXBlockOffset(uint64 srcChainId, uint64 shardId) external view returns (uint64);
/**
* @notice Returns the current XMsg being executed via this portal.
* - xmsg().sourceChainId Chain ID of the source xcall
* - xmsg().sender msg.sender of the source xcall
* If no XMsg is being executed, all fields will be zero.
* - xmsg().sourceChainId == 0
* - xmsg().sender == address(0)
*/
function xmsg() external view returns (XTypes.MsgContext memory);
/**
* @notice Returns true the current transaction is an xcall, false otherwise
*/
function isXCall() external view returns (bool);
/**
* @notice Returns the shard ID is supported by this portal
*/
function isSupportedShard(uint64 shardId) external view returns (bool);
/**
* @notice Returns the destination chain ID is supported by this portal
*/
function isSupportedDest(uint64 destChainId) external view returns (bool);
/**
* @notice Calculate the fee for calling a contract on another chain
* Fees denominated in wei.
* @param destChainId Destination chain ID
* @param data Encoded function calldata
* @param gasLimit Execution gas limit, enforced on destination chain
*/
function feeFor(uint64 destChainId, bytes calldata data, uint64 gasLimit) external view returns (uint256);
/**
* @notice Call a contract on another chain.
* @param destChainId Destination chain ID
* @param conf Confirmation level;
* @param to Address of contract to call on destination chain
* @param data ABI Encoded function calldata
* @param gasLimit Execution gas limit, enforced on destination chain
*/
function xcall(uint64 destChainId, uint8 conf, address to, bytes calldata data, uint64 gasLimit) external payable;
/**
* @notice Submit a batch of XMsgs to be executed on this chain
* @param xsub An xchain submission, including an attestation root w/ validator signatures,
* and a block header and message batch, proven against the attestation root.
*/
function xsubmit(XTypes.Submission calldata xsub) external;
/**
* @notice Returns the current network (supported chain IDs and shards)
*/
function network() external view returns (XTypes.Chain[] memory);
}
../core/src/interfaces/IOmniPortalPausable.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.12;
interface IOmniPortalPausable {
/**
* @notice Return true if actionId for is paused for the given chain
* @dev Also returns if all actions are paused or if the action is globally paused
*/
function isPaused(bytes32 actionId, uint64 chainId) external view returns (bool);
/**
* @notice Return true if actionId is paused for all chains
* @dev Also returns if all actions are paused
*/
function isPaused(bytes32 actionId) external view returns (bool);
/**
* @notice Return true if all actions are paused
*/
function isPaused() external view returns (bool);
}
../core/src/libraries/ConfLevel.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.12;
/**
* @title ConfLevel
* @notice XMsg confirmation levels. Matches ConfLevels in lib/xchain/types.go
* @dev We prefer explicit constants over Enums, because we want uint8 values to start at 1, not 0, as they do in
* lib/xchain/types.go, such that 0 can represent "unset". Note only latest and finalized levels are supported
* on-chain.
*/
library ConfLevel {
/**
* @notice XMsg confirmation level "latest", last byte of xmsg.shardId.
*/
uint8 internal constant Latest = 1;
/**
* @notice XMsg confirmation level "finalized", last byte of xmsg.shardId.
*/
uint8 internal constant Finalized = 4;
/**
* @notice Returns true if the given level is valid.
*/
function isValid(uint8 level) internal pure returns (bool) {
return level == Latest || level == Finalized;
}
/**
* @notice Returns broadcast shard version of the given level.
*/
function toBroadcastShard(uint8 level) internal pure returns (uint64) {
return uint64(level) | 0x0100;
}
}
../core/src/libraries/XTypes.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.12;
/**
* @title XTypes
* @dev Defines xchain types, core to Omni's xchain messaging protocol. These
* types mirror those defined in omni/lib/xchain/types.go.
*/
library XTypes {
/**
* @notice A cross chain message - the product of an xcall. This matches the XMsg type used
* throughout Omni's cross-chain messaging protocol. Msg is used to construct and verify
* XSubmission merkle trees / proofs.
* @custom:field destChainId Chain ID of the destination chain
* @custom:field shardId Shard ID of the XStream (last byte is the confirmation level)
* @custom:field offset Monotonically incremented offset of Msg in source -> dest Stream
* @custom:field sender msg.sender of xcall on source chain
* @custom:field to Target address to call on destination chain
* @custom:field data Data to provide to call on destination chain
* @custom:field gasLimit Gas limit to use for call execution on destination chain
*/
struct Msg {
uint64 destChainId;
uint64 shardId;
uint64 offset;
address sender;
address to;
bytes data;
uint64 gasLimit;
}
/**
* @notice Msg context exposed during its execution to consuming xapps.
* @custom:field sourceChainId Chain ID of the source chain
* @custom:field sender msg.sender of xcall on source chain
*/
struct MsgContext {
uint64 sourceChainId;
address sender;
}
/**
* @notice BlockHeader of an XBlock.
* @custom:field sourceChainId Chain ID of the source chain
* @custom:field consensusChainId Chain ID of the Omni consensus chain
* @custom:field confLevel Confirmation level of the cross chain block
* @custom:field offset Offset of the cross chain block
* @custom:field sourceBlockHeight Height of the source chain block
* @custom:field sourceBlockHash Hash of the source chain block
*/
struct BlockHeader {
uint64 sourceChainId;
uint64 consensusChainId;
uint8 confLevel;
uint64 offset;
uint64 sourceBlockHeight;
bytes32 sourceBlockHash;
}
/**
* @notice The required parameters to submit xmsgs to an OmniPortal. Constructed by the relayer
* by watching Omni's consensus chain, and source chain blocks.
* @custom:field attestationRoot Merkle root of xchain block (XBlockRoot), attested to and signed by validators
* @custom:field validatorSetId Unique identifier of the validator set that attested to this root
* @custom:field blockHeader Block header, identifies xchain block
* @custom:field msgs Messages to execute
* @custom:field proof Multi proof of block header and messages, proven against attestationRoot
* @custom:field proofFlags Multi proof flags
* @custom:field signatures Array of validator signatures of the attestationRoot, and their public keys
*/
struct Submission {
bytes32 attestationRoot;
uint64 validatorSetId;
BlockHeader blockHeader;
Msg[] msgs;
bytes32[] proof;
bool[] proofFlags;
SigTuple[] signatures;
}
/**
* @notice A tuple of a validator's ethereum address and signature over some digest.
* @custom:field validatorAddr Validator ethereum address
* @custom:field signature Validator signature over some digest; Ethereum 65 bytes [R || S || V] format.
*/
struct SigTuple {
address validatorAddr;
bytes signature;
}
/**
* @notice An Omni validator, specified by their ethereum address and voting power.
* @custom:field addr Validator ethereum address
* @custom:field power Validator voting power
*/
struct Validator {
address addr;
uint64 power;
}
/**
* @notice A chain in the "omni network" specified by its chain ID and supported shards.
* @custom:field chainId Chain ID
* @custom:field shards Supported shards
*/
struct Chain {
uint64 chainId;
uint64[] shards;
}
}
../core/src/pkg/XAppBase.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.8.12;
import { IOmniPortal } from "../interfaces/IOmniPortal.sol";
import { XTypes } from "../libraries/XTypes.sol";
import { ConfLevel } from "../libraries/ConfLevel.sol";
/**
* @title XAppBase
* @notice Shared XApp storage and logic.
*/
abstract contract XAppBase {
/**
* @notice Emitted when the OmniPortal contract address is set
*/
event OmniPortalSet(address omni);
/**
* @notice Emitted when the default confirmation level is set
* @param conf Confirmation level
*/
event DefaultConfLevelSet(uint8 conf);
/**
* @notice The OmniPortal contract
*/
IOmniPortal public omni;
/**
* @notice Default confirmation level for xcalls
*/
uint8 public defaultConfLevel;
/**
* @notice Transient storage for the current xmsg
*/
XTypes.MsgContext internal xmsg;
/**
* @notice Read current xmsg into storage before execution, delete it afterwards
*/
modifier xrecv() {
xmsg = omni.xmsg();
_;
delete xmsg;
}
/**
* @notice Return true if the current call is an xcall from the OmniPortal
*/
function isXCall() internal view returns (bool) {
return omni.isXCall() && msg.sender == address(omni);
}
/**
* @notice Returns the fee for calling a contract on another chain, with the specified gas limit
*/
function feeFor(uint64 destChainId, bytes memory data, uint64 gasLimit) internal view returns (uint256) {
return omni.feeFor(destChainId, data, gasLimit);
}
/**
* @notice Returns the chain ID of the Omni EVM in this Omni network
*/
function omniChainId() internal view returns (uint64) {
return omni.omniChainId();
}
/**
* @notice Call a contract on another. (Default ConfLevel)
* @dev This function pays the xcall fee to the OmniPortal from the
* contract's balance. If you would prefer charge callers for the
* fee, you must check msg.value.
* Ex:
* uint256 fee = xcall(...)
* require(msg.value >= fee)
*
* @param destChainId Destination chain ID
* @param to Address of contract to call on destination chain
* @param data ABI Encoded function calldata
* @param gasLimit Execution gas limit, enforced on destination chain
*/
function xcall(uint64 destChainId, address to, bytes memory data, uint64 gasLimit) internal returns (uint256) {
uint256 fee = omni.feeFor(destChainId, data, gasLimit);
require(address(this).balance >= fee, "XApp: insufficient funds");
omni.xcall{ value: fee }(destChainId, defaultConfLevel, to, data, gasLimit);
return fee;
}
/**
* @notice Call a contract on another chain. (Explicit ConfLevel)
* @dev This function pays the xcall fee to the OmniPortal from the
* contract's balance. If you would prefer charge callers for the
* fee, you must check msg.value.
* Ex:
* uint256 fee = xcall(...)
* require(msg.value >= fee)
*
* @param destChainId Destination chain ID
* @param conf Confirmation level
* @param to Address of contract to call on destination chain
* @param data ABI Encoded function calldata
* @param gasLimit Execution gas limit, enforced on destination chain
*/
function xcall(uint64 destChainId, uint8 conf, address to, bytes memory data, uint64 gasLimit)
internal
returns (uint256)
{
uint256 fee = omni.feeFor(destChainId, data, gasLimit);
require(address(this).balance >= fee, "XApp: insufficient funds");
omni.xcall{ value: fee }(destChainId, conf, to, data, gasLimit);
return fee;
}
/**
* @notice Set the default confirmation level for xcalls
* @param conf Confirmation level
*/
function _setDefaultConfLevel(uint8 conf) internal {
require(ConfLevel.isValid(conf), "XApp: invalid conf level");
defaultConfLevel = conf;
emit DefaultConfLevelSet(conf);
}
/**
* @notice Set the OmniPortal contract address
* @param _omni The OmniPortal contract address
*/
function _setOmniPortal(address _omni) internal {
require(_omni != address(0), "XApp: no zero omni");
omni = IOmniPortal(_omni);
emit OmniPortalSet(_omni);
}
}
node_modules/solady/src/auth/Ownable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Simple single owner authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/Ownable.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The caller is not authorized to call the function.
error Unauthorized();
/// @dev The `newOwner` cannot be the zero address.
error NewOwnerIsZeroAddress();
/// @dev The `pendingOwner` does not have a valid handover request.
error NoHandoverRequest();
/// @dev Cannot double-initialize.
error AlreadyInitialized();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ownership is transferred from `oldOwner` to `newOwner`.
/// This event is intentionally kept the same as OpenZeppelin's Ownable to be
/// compatible with indexers and [EIP-173](https://eips.ethereum.org/EIPS/eip-173),
/// despite it not being as lightweight as a single argument event.
event OwnershipTransferred(address indexed oldOwner, address indexed newOwner);
/// @dev An ownership handover to `pendingOwner` has been requested.
event OwnershipHandoverRequested(address indexed pendingOwner);
/// @dev The ownership handover to `pendingOwner` has been canceled.
event OwnershipHandoverCanceled(address indexed pendingOwner);
/// @dev `keccak256(bytes("OwnershipTransferred(address,address)"))`.
uint256 private constant _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE =
0x8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0;
/// @dev `keccak256(bytes("OwnershipHandoverRequested(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE =
0xdbf36a107da19e49527a7176a1babf963b4b0ff8cde35ee35d6cd8f1f9ac7e1d;
/// @dev `keccak256(bytes("OwnershipHandoverCanceled(address)"))`.
uint256 private constant _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE =
0xfa7b8eab7da67f412cc9575ed43464468f9bfbae89d1675917346ca6d8fe3c92;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The owner slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))))`.
/// It is intentionally chosen to be a high value
/// to avoid collision with lower slots.
/// The choice of manual storage layout is to enable compatibility
/// with both regular and upgradeable contracts.
bytes32 internal constant _OWNER_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffff74873927;
/// The ownership handover slot of `newOwner` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _HANDOVER_SLOT_SEED))
/// let handoverSlot := keccak256(0x00, 0x20)
/// ```
/// It stores the expiry timestamp of the two-step ownership handover.
uint256 private constant _HANDOVER_SLOT_SEED = 0x389a75e1;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return true to make `_initializeOwner` prevent double-initialization.
function _guardInitializeOwner() internal pure virtual returns (bool guard) {}
/// @dev Initializes the owner directly without authorization guard.
/// This function must be called upon initialization,
/// regardless of whether the contract is upgradeable or not.
/// This is to enable generalization to both regular and upgradeable contracts,
/// and to save gas in case the initial owner is not the caller.
/// For performance reasons, this function will not check if there
/// is an existing owner.
function _initializeOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
if sload(ownerSlot) {
mstore(0x00, 0x0dc149f0) // `AlreadyInitialized()`.
revert(0x1c, 0x04)
}
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
} else {
/// @solidity memory-safe-assembly
assembly {
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Store the new value.
sstore(_OWNER_SLOT, newOwner)
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, 0, newOwner)
}
}
}
/// @dev Sets the owner directly without authorization guard.
function _setOwner(address newOwner) internal virtual {
if (_guardInitializeOwner()) {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, or(newOwner, shl(255, iszero(newOwner))))
}
} else {
/// @solidity memory-safe-assembly
assembly {
let ownerSlot := _OWNER_SLOT
// Clean the upper 96 bits.
newOwner := shr(96, shl(96, newOwner))
// Emit the {OwnershipTransferred} event.
log3(0, 0, _OWNERSHIP_TRANSFERRED_EVENT_SIGNATURE, sload(ownerSlot), newOwner)
// Store the new value.
sstore(ownerSlot, newOwner)
}
}
}
/// @dev Throws if the sender is not the owner.
function _checkOwner() internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner, revert.
if iszero(eq(caller(), sload(_OWNER_SLOT))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Returns how long a two-step ownership handover is valid for in seconds.
/// Override to return a different value if needed.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ownershipHandoverValidFor() internal view virtual returns (uint64) {
return 48 * 3600;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to transfer the ownership to `newOwner`.
function transferOwnership(address newOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
if iszero(shl(96, newOwner)) {
mstore(0x00, 0x7448fbae) // `NewOwnerIsZeroAddress()`.
revert(0x1c, 0x04)
}
}
_setOwner(newOwner);
}
/// @dev Allows the owner to renounce their ownership.
function renounceOwnership() public payable virtual onlyOwner {
_setOwner(address(0));
}
/// @dev Request a two-step ownership handover to the caller.
/// The request will automatically expire in 48 hours (172800 seconds) by default.
function requestOwnershipHandover() public payable virtual {
unchecked {
uint256 expires = block.timestamp + _ownershipHandoverValidFor();
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to `expires`.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), expires)
// Emit the {OwnershipHandoverRequested} event.
log2(0, 0, _OWNERSHIP_HANDOVER_REQUESTED_EVENT_SIGNATURE, caller())
}
}
}
/// @dev Cancels the two-step ownership handover to the caller, if any.
function cancelOwnershipHandover() public payable virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, caller())
sstore(keccak256(0x0c, 0x20), 0)
// Emit the {OwnershipHandoverCanceled} event.
log2(0, 0, _OWNERSHIP_HANDOVER_CANCELED_EVENT_SIGNATURE, caller())
}
}
/// @dev Allows the owner to complete the two-step ownership handover to `pendingOwner`.
/// Reverts if there is no existing ownership handover requested by `pendingOwner`.
function completeOwnershipHandover(address pendingOwner) public payable virtual onlyOwner {
/// @solidity memory-safe-assembly
assembly {
// Compute and set the handover slot to 0.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
let handoverSlot := keccak256(0x0c, 0x20)
// If the handover does not exist, or has expired.
if gt(timestamp(), sload(handoverSlot)) {
mstore(0x00, 0x6f5e8818) // `NoHandoverRequest()`.
revert(0x1c, 0x04)
}
// Set the handover slot to 0.
sstore(handoverSlot, 0)
}
_setOwner(pendingOwner);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the owner of the contract.
function owner() public view virtual returns (address result) {
/// @solidity memory-safe-assembly
assembly {
result := sload(_OWNER_SLOT)
}
}
/// @dev Returns the expiry timestamp for the two-step ownership handover to `pendingOwner`.
function ownershipHandoverExpiresAt(address pendingOwner)
public
view
virtual
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
// Compute the handover slot.
mstore(0x0c, _HANDOVER_SLOT_SEED)
mstore(0x00, pendingOwner)
// Load the handover slot.
result := sload(keccak256(0x0c, 0x20))
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by the owner.
modifier onlyOwner() virtual {
_checkOwner();
_;
}
}
node_modules/solady/src/auth/OwnableRoles.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import {Ownable} from "./Ownable.sol";
/// @notice Simple single owner and multiroles authorization mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/auth/OwnableRoles.sol)
///
/// @dev Note:
/// This implementation does NOT auto-initialize the owner to `msg.sender`.
/// You MUST call the `_initializeOwner` in the constructor / initializer.
///
/// While the ownable portion follows
/// [EIP-173](https://eips.ethereum.org/EIPS/eip-173) for compatibility,
/// the nomenclature for the 2-step ownership handover may be unique to this codebase.
abstract contract OwnableRoles is Ownable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The `user`'s roles is updated to `roles`.
/// Each bit of `roles` represents whether the role is set.
event RolesUpdated(address indexed user, uint256 indexed roles);
/// @dev `keccak256(bytes("RolesUpdated(address,uint256)"))`.
uint256 private constant _ROLES_UPDATED_EVENT_SIGNATURE =
0x715ad5ce61fc9595c7b415289d59cf203f23a94fa06f04af7e489a0a76e1fe26;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The role slot of `user` is given by:
/// ```
/// mstore(0x00, or(shl(96, user), _ROLE_SLOT_SEED))
/// let roleSlot := keccak256(0x00, 0x20)
/// ```
/// This automatically ignores the upper bits of the `user` in case
/// they are not clean, as well as keep the `keccak256` under 32-bytes.
///
/// Note: This is equivalent to `uint32(bytes4(keccak256("_OWNER_SLOT_NOT")))`.
uint256 private constant _ROLE_SLOT_SEED = 0x8b78c6d8;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* INTERNAL FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Overwrite the roles directly without authorization guard.
function _setRoles(address user, uint256 roles) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, user)
// Store the new value.
sstore(keccak256(0x0c, 0x20), roles)
// Emit the {RolesUpdated} event.
log3(0, 0, _ROLES_UPDATED_EVENT_SIGNATURE, shr(96, mload(0x0c)), roles)
}
}
/// @dev Updates the roles directly without authorization guard.
/// If `on` is true, each set bit of `roles` will be turned on,
/// otherwise, each set bit of `roles` will be turned off.
function _updateRoles(address user, uint256 roles, bool on) internal virtual {
/// @solidity memory-safe-assembly
assembly {
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, user)
let roleSlot := keccak256(0x0c, 0x20)
// Load the current value.
let current := sload(roleSlot)
// Compute the updated roles if `on` is true.
let updated := or(current, roles)
// Compute the updated roles if `on` is false.
// Use `and` to compute the intersection of `current` and `roles`,
// `xor` it with `current` to flip the bits in the intersection.
if iszero(on) { updated := xor(current, and(current, roles)) }
// Then, store the new value.
sstore(roleSlot, updated)
// Emit the {RolesUpdated} event.
log3(0, 0, _ROLES_UPDATED_EVENT_SIGNATURE, shr(96, mload(0x0c)), updated)
}
}
/// @dev Grants the roles directly without authorization guard.
/// Each bit of `roles` represents the role to turn on.
function _grantRoles(address user, uint256 roles) internal virtual {
_updateRoles(user, roles, true);
}
/// @dev Removes the roles directly without authorization guard.
/// Each bit of `roles` represents the role to turn off.
function _removeRoles(address user, uint256 roles) internal virtual {
_updateRoles(user, roles, false);
}
/// @dev Throws if the sender does not have any of the `roles`.
function _checkRoles(uint256 roles) internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, caller())
// Load the stored value, and if the `and` intersection
// of the value and `roles` is zero, revert.
if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Throws if the sender is not the owner,
/// and does not have any of the `roles`.
/// Checks for ownership first, then lazily checks for roles.
function _checkOwnerOrRoles(uint256 roles) internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// If the caller is not the stored owner.
// Note: `_ROLE_SLOT_SEED` is equal to `_OWNER_SLOT_NOT`.
if iszero(eq(caller(), sload(not(_ROLE_SLOT_SEED)))) {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, caller())
// Load the stored value, and if the `and` intersection
// of the value and `roles` is zero, revert.
if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Throws if the sender does not have any of the `roles`,
/// and is not the owner.
/// Checks for roles first, then lazily checks for ownership.
function _checkRolesOrOwner(uint256 roles) internal view virtual {
/// @solidity memory-safe-assembly
assembly {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, caller())
// Load the stored value, and if the `and` intersection
// of the value and `roles` is zero, revert.
if iszero(and(sload(keccak256(0x0c, 0x20)), roles)) {
// If the caller is not the stored owner.
// Note: `_ROLE_SLOT_SEED` is equal to `_OWNER_SLOT_NOT`.
if iszero(eq(caller(), sload(not(_ROLE_SLOT_SEED)))) {
mstore(0x00, 0x82b42900) // `Unauthorized()`.
revert(0x1c, 0x04)
}
}
}
}
/// @dev Convenience function to return a `roles` bitmap from an array of `ordinals`.
/// This is meant for frontends like Etherscan, and is therefore not fully optimized.
/// Not recommended to be called on-chain.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _rolesFromOrdinals(uint8[] memory ordinals) internal pure returns (uint256 roles) {
/// @solidity memory-safe-assembly
assembly {
for { let i := shl(5, mload(ordinals)) } i { i := sub(i, 0x20) } {
// We don't need to mask the values of `ordinals`, as Solidity
// cleans dirty upper bits when storing variables into memory.
roles := or(shl(mload(add(ordinals, i)), 1), roles)
}
}
}
/// @dev Convenience function to return an array of `ordinals` from the `roles` bitmap.
/// This is meant for frontends like Etherscan, and is therefore not fully optimized.
/// Not recommended to be called on-chain.
/// Made internal to conserve bytecode. Wrap it in a public function if needed.
function _ordinalsFromRoles(uint256 roles) internal pure returns (uint8[] memory ordinals) {
/// @solidity memory-safe-assembly
assembly {
// Grab the pointer to the free memory.
ordinals := mload(0x40)
let ptr := add(ordinals, 0x20)
let o := 0
// The absence of lookup tables, De Bruijn, etc., here is intentional for
// smaller bytecode, as this function is not meant to be called on-chain.
for { let t := roles } 1 {} {
mstore(ptr, o)
// `shr` 5 is equivalent to multiplying by 0x20.
// Push back into the ordinals array if the bit is set.
ptr := add(ptr, shl(5, and(t, 1)))
o := add(o, 1)
t := shr(o, roles)
if iszero(t) { break }
}
// Store the length of `ordinals`.
mstore(ordinals, shr(5, sub(ptr, add(ordinals, 0x20))))
// Allocate the memory.
mstore(0x40, ptr)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC UPDATE FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Allows the owner to grant `user` `roles`.
/// If the `user` already has a role, then it will be an no-op for the role.
function grantRoles(address user, uint256 roles) public payable virtual onlyOwner {
_grantRoles(user, roles);
}
/// @dev Allows the owner to remove `user` `roles`.
/// If the `user` does not have a role, then it will be an no-op for the role.
function revokeRoles(address user, uint256 roles) public payable virtual onlyOwner {
_removeRoles(user, roles);
}
/// @dev Allow the caller to remove their own roles.
/// If the caller does not have a role, then it will be an no-op for the role.
function renounceRoles(uint256 roles) public payable virtual {
_removeRoles(msg.sender, roles);
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* PUBLIC READ FUNCTIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the roles of `user`.
function rolesOf(address user) public view virtual returns (uint256 roles) {
/// @solidity memory-safe-assembly
assembly {
// Compute the role slot.
mstore(0x0c, _ROLE_SLOT_SEED)
mstore(0x00, user)
// Load the stored value.
roles := sload(keccak256(0x0c, 0x20))
}
}
/// @dev Returns whether `user` has any of `roles`.
function hasAnyRole(address user, uint256 roles) public view virtual returns (bool) {
return rolesOf(user) & roles != 0;
}
/// @dev Returns whether `user` has all of `roles`.
function hasAllRoles(address user, uint256 roles) public view virtual returns (bool) {
return rolesOf(user) & roles == roles;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* MODIFIERS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Marks a function as only callable by an account with `roles`.
modifier onlyRoles(uint256 roles) virtual {
_checkRoles(roles);
_;
}
/// @dev Marks a function as only callable by the owner or by an account
/// with `roles`. Checks for ownership first, then lazily checks for roles.
modifier onlyOwnerOrRoles(uint256 roles) virtual {
_checkOwnerOrRoles(roles);
_;
}
/// @dev Marks a function as only callable by an account with `roles`
/// or the owner. Checks for roles first, then lazily checks for ownership.
modifier onlyRolesOrOwner(uint256 roles) virtual {
_checkRolesOrOwner(roles);
_;
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ROLE CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// IYKYK
uint256 internal constant _ROLE_0 = 1 << 0;
uint256 internal constant _ROLE_1 = 1 << 1;
uint256 internal constant _ROLE_2 = 1 << 2;
uint256 internal constant _ROLE_3 = 1 << 3;
uint256 internal constant _ROLE_4 = 1 << 4;
uint256 internal constant _ROLE_5 = 1 << 5;
uint256 internal constant _ROLE_6 = 1 << 6;
uint256 internal constant _ROLE_7 = 1 << 7;
uint256 internal constant _ROLE_8 = 1 << 8;
uint256 internal constant _ROLE_9 = 1 << 9;
uint256 internal constant _ROLE_10 = 1 << 10;
uint256 internal constant _ROLE_11 = 1 << 11;
uint256 internal constant _ROLE_12 = 1 << 12;
uint256 internal constant _ROLE_13 = 1 << 13;
uint256 internal constant _ROLE_14 = 1 << 14;
uint256 internal constant _ROLE_15 = 1 << 15;
uint256 internal constant _ROLE_16 = 1 << 16;
uint256 internal constant _ROLE_17 = 1 << 17;
uint256 internal constant _ROLE_18 = 1 << 18;
uint256 internal constant _ROLE_19 = 1 << 19;
uint256 internal constant _ROLE_20 = 1 << 20;
uint256 internal constant _ROLE_21 = 1 << 21;
uint256 internal constant _ROLE_22 = 1 << 22;
uint256 internal constant _ROLE_23 = 1 << 23;
uint256 internal constant _ROLE_24 = 1 << 24;
uint256 internal constant _ROLE_25 = 1 << 25;
uint256 internal constant _ROLE_26 = 1 << 26;
uint256 internal constant _ROLE_27 = 1 << 27;
uint256 internal constant _ROLE_28 = 1 << 28;
uint256 internal constant _ROLE_29 = 1 << 29;
uint256 internal constant _ROLE_30 = 1 << 30;
uint256 internal constant _ROLE_31 = 1 << 31;
uint256 internal constant _ROLE_32 = 1 << 32;
uint256 internal constant _ROLE_33 = 1 << 33;
uint256 internal constant _ROLE_34 = 1 << 34;
uint256 internal constant _ROLE_35 = 1 << 35;
uint256 internal constant _ROLE_36 = 1 << 36;
uint256 internal constant _ROLE_37 = 1 << 37;
uint256 internal constant _ROLE_38 = 1 << 38;
uint256 internal constant _ROLE_39 = 1 << 39;
uint256 internal constant _ROLE_40 = 1 << 40;
uint256 internal constant _ROLE_41 = 1 << 41;
uint256 internal constant _ROLE_42 = 1 << 42;
uint256 internal constant _ROLE_43 = 1 << 43;
uint256 internal constant _ROLE_44 = 1 << 44;
uint256 internal constant _ROLE_45 = 1 << 45;
uint256 internal constant _ROLE_46 = 1 << 46;
uint256 internal constant _ROLE_47 = 1 << 47;
uint256 internal constant _ROLE_48 = 1 << 48;
uint256 internal constant _ROLE_49 = 1 << 49;
uint256 internal constant _ROLE_50 = 1 << 50;
uint256 internal constant _ROLE_51 = 1 << 51;
uint256 internal constant _ROLE_52 = 1 << 52;
uint256 internal constant _ROLE_53 = 1 << 53;
uint256 internal constant _ROLE_54 = 1 << 54;
uint256 internal constant _ROLE_55 = 1 << 55;
uint256 internal constant _ROLE_56 = 1 << 56;
uint256 internal constant _ROLE_57 = 1 << 57;
uint256 internal constant _ROLE_58 = 1 << 58;
uint256 internal constant _ROLE_59 = 1 << 59;
uint256 internal constant _ROLE_60 = 1 << 60;
uint256 internal constant _ROLE_61 = 1 << 61;
uint256 internal constant _ROLE_62 = 1 << 62;
uint256 internal constant _ROLE_63 = 1 << 63;
uint256 internal constant _ROLE_64 = 1 << 64;
uint256 internal constant _ROLE_65 = 1 << 65;
uint256 internal constant _ROLE_66 = 1 << 66;
uint256 internal constant _ROLE_67 = 1 << 67;
uint256 internal constant _ROLE_68 = 1 << 68;
uint256 internal constant _ROLE_69 = 1 << 69;
uint256 internal constant _ROLE_70 = 1 << 70;
uint256 internal constant _ROLE_71 = 1 << 71;
uint256 internal constant _ROLE_72 = 1 << 72;
uint256 internal constant _ROLE_73 = 1 << 73;
uint256 internal constant _ROLE_74 = 1 << 74;
uint256 internal constant _ROLE_75 = 1 << 75;
uint256 internal constant _ROLE_76 = 1 << 76;
uint256 internal constant _ROLE_77 = 1 << 77;
uint256 internal constant _ROLE_78 = 1 << 78;
uint256 internal constant _ROLE_79 = 1 << 79;
uint256 internal constant _ROLE_80 = 1 << 80;
uint256 internal constant _ROLE_81 = 1 << 81;
uint256 internal constant _ROLE_82 = 1 << 82;
uint256 internal constant _ROLE_83 = 1 << 83;
uint256 internal constant _ROLE_84 = 1 << 84;
uint256 internal constant _ROLE_85 = 1 << 85;
uint256 internal constant _ROLE_86 = 1 << 86;
uint256 internal constant _ROLE_87 = 1 << 87;
uint256 internal constant _ROLE_88 = 1 << 88;
uint256 internal constant _ROLE_89 = 1 << 89;
uint256 internal constant _ROLE_90 = 1 << 90;
uint256 internal constant _ROLE_91 = 1 << 91;
uint256 internal constant _ROLE_92 = 1 << 92;
uint256 internal constant _ROLE_93 = 1 << 93;
uint256 internal constant _ROLE_94 = 1 << 94;
uint256 internal constant _ROLE_95 = 1 << 95;
uint256 internal constant _ROLE_96 = 1 << 96;
uint256 internal constant _ROLE_97 = 1 << 97;
uint256 internal constant _ROLE_98 = 1 << 98;
uint256 internal constant _ROLE_99 = 1 << 99;
uint256 internal constant _ROLE_100 = 1 << 100;
uint256 internal constant _ROLE_101 = 1 << 101;
uint256 internal constant _ROLE_102 = 1 << 102;
uint256 internal constant _ROLE_103 = 1 << 103;
uint256 internal constant _ROLE_104 = 1 << 104;
uint256 internal constant _ROLE_105 = 1 << 105;
uint256 internal constant _ROLE_106 = 1 << 106;
uint256 internal constant _ROLE_107 = 1 << 107;
uint256 internal constant _ROLE_108 = 1 << 108;
uint256 internal constant _ROLE_109 = 1 << 109;
uint256 internal constant _ROLE_110 = 1 << 110;
uint256 internal constant _ROLE_111 = 1 << 111;
uint256 internal constant _ROLE_112 = 1 << 112;
uint256 internal constant _ROLE_113 = 1 << 113;
uint256 internal constant _ROLE_114 = 1 << 114;
uint256 internal constant _ROLE_115 = 1 << 115;
uint256 internal constant _ROLE_116 = 1 << 116;
uint256 internal constant _ROLE_117 = 1 << 117;
uint256 internal constant _ROLE_118 = 1 << 118;
uint256 internal constant _ROLE_119 = 1 << 119;
uint256 internal constant _ROLE_120 = 1 << 120;
uint256 internal constant _ROLE_121 = 1 << 121;
uint256 internal constant _ROLE_122 = 1 << 122;
uint256 internal constant _ROLE_123 = 1 << 123;
uint256 internal constant _ROLE_124 = 1 << 124;
uint256 internal constant _ROLE_125 = 1 << 125;
uint256 internal constant _ROLE_126 = 1 << 126;
uint256 internal constant _ROLE_127 = 1 << 127;
uint256 internal constant _ROLE_128 = 1 << 128;
uint256 internal constant _ROLE_129 = 1 << 129;
uint256 internal constant _ROLE_130 = 1 << 130;
uint256 internal constant _ROLE_131 = 1 << 131;
uint256 internal constant _ROLE_132 = 1 << 132;
uint256 internal constant _ROLE_133 = 1 << 133;
uint256 internal constant _ROLE_134 = 1 << 134;
uint256 internal constant _ROLE_135 = 1 << 135;
uint256 internal constant _ROLE_136 = 1 << 136;
uint256 internal constant _ROLE_137 = 1 << 137;
uint256 internal constant _ROLE_138 = 1 << 138;
uint256 internal constant _ROLE_139 = 1 << 139;
uint256 internal constant _ROLE_140 = 1 << 140;
uint256 internal constant _ROLE_141 = 1 << 141;
uint256 internal constant _ROLE_142 = 1 << 142;
uint256 internal constant _ROLE_143 = 1 << 143;
uint256 internal constant _ROLE_144 = 1 << 144;
uint256 internal constant _ROLE_145 = 1 << 145;
uint256 internal constant _ROLE_146 = 1 << 146;
uint256 internal constant _ROLE_147 = 1 << 147;
uint256 internal constant _ROLE_148 = 1 << 148;
uint256 internal constant _ROLE_149 = 1 << 149;
uint256 internal constant _ROLE_150 = 1 << 150;
uint256 internal constant _ROLE_151 = 1 << 151;
uint256 internal constant _ROLE_152 = 1 << 152;
uint256 internal constant _ROLE_153 = 1 << 153;
uint256 internal constant _ROLE_154 = 1 << 154;
uint256 internal constant _ROLE_155 = 1 << 155;
uint256 internal constant _ROLE_156 = 1 << 156;
uint256 internal constant _ROLE_157 = 1 << 157;
uint256 internal constant _ROLE_158 = 1 << 158;
uint256 internal constant _ROLE_159 = 1 << 159;
uint256 internal constant _ROLE_160 = 1 << 160;
uint256 internal constant _ROLE_161 = 1 << 161;
uint256 internal constant _ROLE_162 = 1 << 162;
uint256 internal constant _ROLE_163 = 1 << 163;
uint256 internal constant _ROLE_164 = 1 << 164;
uint256 internal constant _ROLE_165 = 1 << 165;
uint256 internal constant _ROLE_166 = 1 << 166;
uint256 internal constant _ROLE_167 = 1 << 167;
uint256 internal constant _ROLE_168 = 1 << 168;
uint256 internal constant _ROLE_169 = 1 << 169;
uint256 internal constant _ROLE_170 = 1 << 170;
uint256 internal constant _ROLE_171 = 1 << 171;
uint256 internal constant _ROLE_172 = 1 << 172;
uint256 internal constant _ROLE_173 = 1 << 173;
uint256 internal constant _ROLE_174 = 1 << 174;
uint256 internal constant _ROLE_175 = 1 << 175;
uint256 internal constant _ROLE_176 = 1 << 176;
uint256 internal constant _ROLE_177 = 1 << 177;
uint256 internal constant _ROLE_178 = 1 << 178;
uint256 internal constant _ROLE_179 = 1 << 179;
uint256 internal constant _ROLE_180 = 1 << 180;
uint256 internal constant _ROLE_181 = 1 << 181;
uint256 internal constant _ROLE_182 = 1 << 182;
uint256 internal constant _ROLE_183 = 1 << 183;
uint256 internal constant _ROLE_184 = 1 << 184;
uint256 internal constant _ROLE_185 = 1 << 185;
uint256 internal constant _ROLE_186 = 1 << 186;
uint256 internal constant _ROLE_187 = 1 << 187;
uint256 internal constant _ROLE_188 = 1 << 188;
uint256 internal constant _ROLE_189 = 1 << 189;
uint256 internal constant _ROLE_190 = 1 << 190;
uint256 internal constant _ROLE_191 = 1 << 191;
uint256 internal constant _ROLE_192 = 1 << 192;
uint256 internal constant _ROLE_193 = 1 << 193;
uint256 internal constant _ROLE_194 = 1 << 194;
uint256 internal constant _ROLE_195 = 1 << 195;
uint256 internal constant _ROLE_196 = 1 << 196;
uint256 internal constant _ROLE_197 = 1 << 197;
uint256 internal constant _ROLE_198 = 1 << 198;
uint256 internal constant _ROLE_199 = 1 << 199;
uint256 internal constant _ROLE_200 = 1 << 200;
uint256 internal constant _ROLE_201 = 1 << 201;
uint256 internal constant _ROLE_202 = 1 << 202;
uint256 internal constant _ROLE_203 = 1 << 203;
uint256 internal constant _ROLE_204 = 1 << 204;
uint256 internal constant _ROLE_205 = 1 << 205;
uint256 internal constant _ROLE_206 = 1 << 206;
uint256 internal constant _ROLE_207 = 1 << 207;
uint256 internal constant _ROLE_208 = 1 << 208;
uint256 internal constant _ROLE_209 = 1 << 209;
uint256 internal constant _ROLE_210 = 1 << 210;
uint256 internal constant _ROLE_211 = 1 << 211;
uint256 internal constant _ROLE_212 = 1 << 212;
uint256 internal constant _ROLE_213 = 1 << 213;
uint256 internal constant _ROLE_214 = 1 << 214;
uint256 internal constant _ROLE_215 = 1 << 215;
uint256 internal constant _ROLE_216 = 1 << 216;
uint256 internal constant _ROLE_217 = 1 << 217;
uint256 internal constant _ROLE_218 = 1 << 218;
uint256 internal constant _ROLE_219 = 1 << 219;
uint256 internal constant _ROLE_220 = 1 << 220;
uint256 internal constant _ROLE_221 = 1 << 221;
uint256 internal constant _ROLE_222 = 1 << 222;
uint256 internal constant _ROLE_223 = 1 << 223;
uint256 internal constant _ROLE_224 = 1 << 224;
uint256 internal constant _ROLE_225 = 1 << 225;
uint256 internal constant _ROLE_226 = 1 << 226;
uint256 internal constant _ROLE_227 = 1 << 227;
uint256 internal constant _ROLE_228 = 1 << 228;
uint256 internal constant _ROLE_229 = 1 << 229;
uint256 internal constant _ROLE_230 = 1 << 230;
uint256 internal constant _ROLE_231 = 1 << 231;
uint256 internal constant _ROLE_232 = 1 << 232;
uint256 internal constant _ROLE_233 = 1 << 233;
uint256 internal constant _ROLE_234 = 1 << 234;
uint256 internal constant _ROLE_235 = 1 << 235;
uint256 internal constant _ROLE_236 = 1 << 236;
uint256 internal constant _ROLE_237 = 1 << 237;
uint256 internal constant _ROLE_238 = 1 << 238;
uint256 internal constant _ROLE_239 = 1 << 239;
uint256 internal constant _ROLE_240 = 1 << 240;
uint256 internal constant _ROLE_241 = 1 << 241;
uint256 internal constant _ROLE_242 = 1 << 242;
uint256 internal constant _ROLE_243 = 1 << 243;
uint256 internal constant _ROLE_244 = 1 << 244;
uint256 internal constant _ROLE_245 = 1 << 245;
uint256 internal constant _ROLE_246 = 1 << 246;
uint256 internal constant _ROLE_247 = 1 << 247;
uint256 internal constant _ROLE_248 = 1 << 248;
uint256 internal constant _ROLE_249 = 1 << 249;
uint256 internal constant _ROLE_250 = 1 << 250;
uint256 internal constant _ROLE_251 = 1 << 251;
uint256 internal constant _ROLE_252 = 1 << 252;
uint256 internal constant _ROLE_253 = 1 << 253;
uint256 internal constant _ROLE_254 = 1 << 254;
uint256 internal constant _ROLE_255 = 1 << 255;
}
node_modules/solady/src/utils/Initializable.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Initializable mixin for the upgradeable contracts.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/Initializable.sol)
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/tree/master/contracts/proxy/utils/Initializable.sol)
abstract contract Initializable {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The contract is already initialized.
error InvalidInitialization();
/// @dev The contract is not initializing.
error NotInitializing();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* EVENTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Triggered when the contract has been initialized.
event Initialized(uint64 version);
/// @dev `keccak256(bytes("Initialized(uint64)"))`.
bytes32 private constant _INTIALIZED_EVENT_SIGNATURE =
0xc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d2;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The default initializable slot is given by:
/// `bytes32(~uint256(uint32(bytes4(keccak256("_INITIALIZABLE_SLOT")))))`.
///
/// Bits Layout:
/// - [0] `initializing`
/// - [1..64] `initializedVersion`
bytes32 private constant _INITIALIZABLE_SLOT =
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffbf601132;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTRUCTOR */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
constructor() {
// Construction time check to ensure that `_initializableSlot()` is not
// overridden to zero. Will be optimized away if there is no revert.
require(_initializableSlot() != bytes32(0));
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Override to return a non-zero custom storage slot if required.
function _initializableSlot() internal pure virtual returns (bytes32) {
return _INITIALIZABLE_SLOT;
}
/// @dev Guards an initializer function so that it can be invoked at most once.
///
/// You can guard a function with `onlyInitializing` such that it can be called
/// through a function guarded with `initializer`.
///
/// This is similar to `reinitializer(1)`, except that in the context of a constructor,
/// an `initializer` guarded function can be invoked multiple times.
/// This can be useful during testing and is not expected to be used in production.
///
/// Emits an {Initialized} event.
modifier initializer() virtual {
bytes32 s = _initializableSlot();
/// @solidity memory-safe-assembly
assembly {
let i := sload(s)
// Set `initializing` to 1, `initializedVersion` to 1.
sstore(s, 3)
// If `!(initializing == 0 && initializedVersion == 0)`.
if i {
// If `!(address(this).code.length == 0 && initializedVersion == 1)`.
if iszero(lt(extcodesize(address()), eq(shr(1, i), 1))) {
mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`.
revert(0x1c, 0x04)
}
s := shl(shl(255, i), s) // Skip initializing if `initializing == 1`.
}
}
_;
/// @solidity memory-safe-assembly
assembly {
if s {
// Set `initializing` to 0, `initializedVersion` to 1.
sstore(s, 2)
// Emit the {Initialized} event.
mstore(0x20, 1)
log1(0x20, 0x20, _INTIALIZED_EVENT_SIGNATURE)
}
}
}
/// @dev Guards an reinitialzer function so that it can be invoked at most once.
///
/// You can guard a function with `onlyInitializing` such that it can be called
/// through a function guarded with `reinitializer`.
///
/// Emits an {Initialized} event.
modifier reinitializer(uint64 version) virtual {
bytes32 s = _initializableSlot();
/// @solidity memory-safe-assembly
assembly {
// Clean upper bits, and shift left by 1 to make space for the initializing bit.
version := shl(1, and(version, 0xffffffffffffffff))
let i := sload(s)
// If `initializing == 1 || initializedVersion >= version`.
if iszero(lt(and(i, 1), lt(i, version))) {
mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`.
revert(0x1c, 0x04)
}
// Set `initializing` to 1, `initializedVersion` to `version`.
sstore(s, or(1, version))
}
_;
/// @solidity memory-safe-assembly
assembly {
// Set `initializing` to 0, `initializedVersion` to `version`.
sstore(s, version)
// Emit the {Initialized} event.
mstore(0x20, shr(1, version))
log1(0x20, 0x20, _INTIALIZED_EVENT_SIGNATURE)
}
}
/// @dev Guards a function such that it can only be called in the scope
/// of a function guarded with `initializer` or `reinitializer`.
modifier onlyInitializing() virtual {
_checkInitializing();
_;
}
/// @dev Reverts if the contract is not initializing.
function _checkInitializing() internal view virtual {
bytes32 s = _initializableSlot();
/// @solidity memory-safe-assembly
assembly {
if iszero(and(1, sload(s))) {
mstore(0x00, 0xd7e6bcf8) // `NotInitializing()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Locks any future initializations by setting the initialized version to `2**64 - 1`.
///
/// Calling this in the constructor will prevent the contract from being initialized
/// or reinitialized. It is recommended to use this to lock implementation contracts
/// that are designed to be called through proxies.
///
/// Emits an {Initialized} event the first time it is successfully called.
function _disableInitializers() internal virtual {
bytes32 s = _initializableSlot();
/// @solidity memory-safe-assembly
assembly {
let i := sload(s)
if and(i, 1) {
mstore(0x00, 0xf92ee8a9) // `InvalidInitialization()`.
revert(0x1c, 0x04)
}
let uint64max := 0xffffffffffffffff
if iszero(eq(shr(1, i), uint64max)) {
// Set `initializing` to 0, `initializedVersion` to `2**64 - 1`.
sstore(s, shl(1, uint64max))
// Emit the {Initialized} event.
mstore(0x20, uint64max)
log1(0x20, 0x20, _INTIALIZED_EVENT_SIGNATURE)
}
}
}
/// @dev Returns the highest version that has been initialized.
function _getInitializedVersion() internal view virtual returns (uint64 version) {
bytes32 s = _initializableSlot();
/// @solidity memory-safe-assembly
assembly {
version := shr(1, sload(s))
}
}
/// @dev Returns whether the contract is currently initializing.
function _isInitializing() internal view virtual returns (bool result) {
bytes32 s = _initializableSlot();
/// @solidity memory-safe-assembly
assembly {
result := and(1, sload(s))
}
}
}
node_modules/solady/src/utils/ReentrancyGuard.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Reentrancy guard mixin.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Unauthorized reentrant call.
error Reentrancy();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* STORAGE */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Equivalent to: `uint72(bytes9(keccak256("_REENTRANCY_GUARD_SLOT")))`.
/// 9 bytes is large enough to avoid collisions with lower slots,
/// but not too large to result in excessive bytecode bloat.
uint256 private constant _REENTRANCY_GUARD_SLOT = 0x929eee149b4bd21268;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* REENTRANCY GUARD */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Guards a function from reentrancy.
modifier nonReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
sstore(_REENTRANCY_GUARD_SLOT, address())
}
_;
/// @solidity memory-safe-assembly
assembly {
sstore(_REENTRANCY_GUARD_SLOT, codesize())
}
}
/// @dev Guards a view function from read-only reentrancy.
modifier nonReadReentrant() virtual {
/// @solidity memory-safe-assembly
assembly {
if eq(sload(_REENTRANCY_GUARD_SLOT), address()) {
mstore(0x00, 0xab143c06) // `Reentrancy()`.
revert(0x1c, 0x04)
}
}
_;
}
}
node_modules/solady/src/utils/SafeTransferLib.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The ETH transfer has failed.
error ETHTransferFailed();
/// @dev The ERC20 `transferFrom` has failed.
error TransferFromFailed();
/// @dev The ERC20 `transfer` has failed.
error TransferFailed();
/// @dev The ERC20 `approve` has failed.
error ApproveFailed();
/// @dev The ERC20 `totalSupply` query has failed.
error TotalSupplyQueryFailed();
/// @dev The Permit2 operation has failed.
error Permit2Failed();
/// @dev The Permit2 amount must be less than `2**160 - 1`.
error Permit2AmountOverflow();
/// @dev The Permit2 approve operation has failed.
error Permit2ApproveFailed();
/// @dev The Permit2 lockdown operation has failed.
error Permit2LockdownFailed();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;
/// @dev Suggested gas stipend for contract receiving ETH to perform a few
/// storage reads and writes, but low enough to prevent griefing.
uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;
/// @dev The unique EIP-712 domain domain separator for the DAI token contract.
bytes32 internal constant DAI_DOMAIN_SEPARATOR =
0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;
/// @dev The address for the WETH9 contract on Ethereum mainnet.
address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/// @dev The canonical Permit2 address.
/// [Github](https://github.com/Uniswap/permit2)
/// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
//
// The regular variants:
// - Forwards all remaining gas to the target.
// - Reverts if the target reverts.
// - Reverts if the current contract has insufficient balance.
//
// The force variants:
// - Forwards with an optional gas stipend
// (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
// - If the target reverts, or if the gas stipend is exhausted,
// creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
// Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
// - Reverts if the current contract has insufficient balance.
//
// The try variants:
// - Forwards with a mandatory gas stipend.
// - Instead of reverting, returns whether the transfer succeeded.
/// @dev Sends `amount` (in wei) ETH to `to`.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Sends all the ETH in the current contract to `to`.
function safeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer all the ETH and check if it succeeded or not.
if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
if lt(selfbalance(), amount) {
mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
revert(0x1c, 0x04)
}
if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
function forceSafeTransferAllETH(address to) internal {
/// @solidity memory-safe-assembly
assembly {
// forgefmt: disable-next-item
if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
}
}
/// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
function trySafeTransferAllETH(address to, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ERC20 OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for
/// the current contract to manage.
function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function trySafeTransferFrom(address token, address from, address to, uint256 amount)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x60, amount) // Store the `amount` argument.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends all of ERC20 `token` from `from` to `to`.
/// Reverts upon failure.
///
/// The `from` account must have their entire balance approved for the current contract to manage.
function safeTransferAllFrom(address token, address from, address to)
internal
returns (uint256 amount)
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40) // Cache the free memory pointer.
mstore(0x40, to) // Store the `to` argument.
mstore(0x2c, shl(96, from)) // Store the `from` argument.
mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
)
) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x60, 0) // Restore the zero slot to zero.
mstore(0x40, m) // Restore the free memory pointer.
}
}
/// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransfer(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sends all of ERC20 `token` from the current contract to `to`.
/// Reverts upon failure.
function safeTransferAll(address token, address to) internal returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
mstore(0x20, address()) // Store the address of the current contract.
// Read the balance, reverting upon failure.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
)
) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
// Perform the transfer, reverting upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// Reverts upon failure.
function safeApprove(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
/// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
/// then retries the approval again (some tokens, e.g. USDT, requires this).
/// Reverts upon failure.
function safeApproveWithRetry(address token, address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, to) // Store the `to` argument.
mstore(0x34, amount) // Store the `amount` argument.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
// Perform the approval, retrying upon failure.
let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x34, 0) // Store 0 for the `amount`.
mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
mstore(0x34, amount) // Store back the original `amount`.
// Retry the approval, reverting upon failure.
success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
if iszero(and(eq(mload(0x00), 1), success)) {
// Check the `extcodesize` again just in case the token selfdestructs lol.
if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
}
mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
}
}
/// @dev Returns the amount of ERC20 `token` owned by `account`.
/// Returns zero if the `token` does not exist.
function balanceOf(address token, address account) internal view returns (uint256 amount) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x14, account) // Store the `account` argument.
mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
amount :=
mul( // The arguments of `mul` are evaluated from right to left.
mload(0x20),
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x1f), // At least 32 bytes returned.
staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
)
)
}
}
/// @dev Returns the total supply of the `token`.
/// Reverts if the token does not exist or does not implement `totalSupply()`.
function totalSupply(address token) internal view returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, 0x18160ddd) // `totalSupply()`.
if iszero(
and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
) {
mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
revert(0x1c, 0x04)
}
result := mload(0x00)
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
/// If the initial attempt fails, try to use Permit2 to transfer the token.
/// Reverts upon failure.
///
/// The `from` account must have at least `amount` approved for the current contract to manage.
function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
if (!trySafeTransferFrom(token, from, to, amount)) {
permit2TransferFrom(token, from, to, amount);
}
}
/// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
/// Reverts upon failure.
function permit2TransferFrom(address token, address from, address to, uint256 amount)
internal
{
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(add(m, 0x74), shr(96, shl(96, token)))
mstore(add(m, 0x54), amount)
mstore(add(m, 0x34), to)
mstore(add(m, 0x20), shl(96, from))
// `transferFrom(address,address,uint160,address)`.
mstore(m, 0x36c78516000000000000000000000000)
let p := PERMIT2
let exists := eq(chainid(), 1)
if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
if iszero(
and(
call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
)
) {
mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
}
}
}
/// @dev Permit a user to spend a given amount of
/// another user's tokens via native EIP-2612 permit if possible, falling
/// back to Permit2 if native permit fails or is not implemented on the token.
function permit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
bool success;
/// @solidity memory-safe-assembly
assembly {
for {} shl(96, xor(token, WETH9)) {} {
mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
if iszero(
and( // The arguments of `and` are evaluated from right to left.
lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
// Gas stipend to limit gas burn for tokens that don't refund gas when
// an non-existing function is called. 5K should be enough for a SLOAD.
staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
)
) { break }
// After here, we can be sure that token is a contract.
let m := mload(0x40)
mstore(add(m, 0x34), spender)
mstore(add(m, 0x20), shl(96, owner))
mstore(add(m, 0x74), deadline)
if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
mstore(0x14, owner)
mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
mstore(
add(m, 0x94),
lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
)
mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
// `nonces` is already at `add(m, 0x54)`.
// `amount != 0` is already stored at `add(m, 0x94)`.
mstore(add(m, 0xb4), and(0xff, v))
mstore(add(m, 0xd4), r)
mstore(add(m, 0xf4), s)
success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
break
}
mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
mstore(add(m, 0x54), amount)
mstore(add(m, 0x94), and(0xff, v))
mstore(add(m, 0xb4), r)
mstore(add(m, 0xd4), s)
success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
break
}
}
if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
}
/// @dev Simple permit on the Permit2 contract.
function simplePermit2(
address token,
address owner,
address spender,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0x927da105) // `allowance(address,address,address)`.
{
let addressMask := shr(96, not(0))
mstore(add(m, 0x20), and(addressMask, owner))
mstore(add(m, 0x40), and(addressMask, token))
mstore(add(m, 0x60), and(addressMask, spender))
mstore(add(m, 0xc0), and(addressMask, spender))
}
let p := mul(PERMIT2, iszero(shr(160, amount)))
if iszero(
and( // The arguments of `and` are evaluated from right to left.
gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
)
) {
mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
revert(add(0x18, shl(2, iszero(p))), 0x04)
}
mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
// `owner` is already `add(m, 0x20)`.
// `token` is already at `add(m, 0x40)`.
mstore(add(m, 0x60), amount)
mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
// `nonce` is already at `add(m, 0xa0)`.
// `spender` is already at `add(m, 0xc0)`.
mstore(add(m, 0xe0), deadline)
mstore(add(m, 0x100), 0x100) // `signature` offset.
mstore(add(m, 0x120), 0x41) // `signature` length.
mstore(add(m, 0x140), r)
mstore(add(m, 0x160), s)
mstore(add(m, 0x180), shl(248, v))
if iszero( // Revert if token does not have code, or if the call fails.
mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
internal
{
/// @solidity memory-safe-assembly
assembly {
let addressMask := shr(96, not(0))
let m := mload(0x40)
mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
mstore(add(m, 0x20), and(addressMask, token))
mstore(add(m, 0x40), and(addressMask, spender))
mstore(add(m, 0x60), and(addressMask, amount))
mstore(add(m, 0x80), and(0xffffffffffff, expiration))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
revert(0x1c, 0x04)
}
}
}
/// @dev Revokes an approval for `token` and `spender` for `address(this)`.
function permit2Lockdown(address token, address spender) internal {
/// @solidity memory-safe-assembly
assembly {
let m := mload(0x40)
mstore(m, 0xcc53287f) // `Permit2.lockdown`.
mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
mstore(add(m, 0x40), 1) // `approvals.length`.
mstore(add(m, 0x60), shr(96, shl(96, token)))
mstore(add(m, 0x80), shr(96, shl(96, spender)))
if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
revert(0x1c, 0x04)
}
}
}
}
src/erc7683/IERC7683.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity =0.8.24;
/// @title IERC7683
/// @notice Standard type definitions for ERC-7683 compliant settlement contracts
/// @dev See https://github.com/ethereum/ERCs/blob/master/ERCS/erc-7683.md
interface IERC7683 {
/// @notice Signals that an order has been opened
/// @param orderId a unique order identifier within this settlement system
/// @param resolvedOrder resolved order that would be returned by resolve if called instead of Open
event Open(bytes32 indexed orderId, ResolvedCrossChainOrder resolvedOrder);
/// @title GaslessCrossChainOrder CrossChainOrder type
/// @notice Standard order struct to be signed by users, disseminated to fillers, and submitted to origin settler contracts
struct GaslessCrossChainOrder {
/// @dev The contract address that the order is meant to be settled by.
/// Fillers send this order to this contract address on the origin chain
address originSettler;
/// @dev The address of the user who is initiating the swap,
/// whose input tokens will be taken and escrowed
address user;
/// @dev Nonce to be used as replay protection for the order
uint256 nonce;
/// @dev The chainId of the origin chain
uint256 originChainId;
/// @dev The timestamp by which the order must be opened
uint32 openDeadline;
/// @dev The timestamp by which the order must be filled on the destination chain
uint32 fillDeadline;
/// @dev Type identifier for the order data. This is an EIP-712 typehash.
bytes32 orderDataType;
/// @dev Arbitrary implementation-specific data
/// Can be used to define tokens, amounts, destination chains, fees, settlement parameters,
/// or any other order-type specific information
bytes orderData;
}
/// @title OnchainCrossChainOrder CrossChainOrder type
/// @notice Standard order struct for user-opened orders, where the user is the msg.sender.
struct OnchainCrossChainOrder {
/// @dev The timestamp by which the order must be filled on the destination chain
uint32 fillDeadline;
/// @dev Type identifier for the order data. This is an EIP-712 typehash.
bytes32 orderDataType;
/// @dev Arbitrary implementation-specific data
/// Can be used to define tokens, amounts, destination chains, fees, settlement parameters,
/// or any other order-type specific information
bytes orderData;
}
/// @title ResolvedCrossChainOrder type
/// @notice An implementation-generic representation of an order intended for filler consumption
/// @dev Defines all requirements for filling an order by unbundling the implementation-specific orderData.
/// @dev Intended to improve integration generalization by allowing fillers to compute the exact input and output information of any order
struct ResolvedCrossChainOrder {
/// @dev The address of the user who is initiating the transfer
address user;
/// @dev The chainId of the origin chain
uint256 originChainId;
/// @dev The timestamp by which the order must be opened
uint32 openDeadline;
/// @dev The timestamp by which the order must be filled on the destination chain(s)
uint32 fillDeadline;
/// @dev The unique identifier for this order within this settlement system
bytes32 orderId;
/// @dev The max outputs that the filler will send. It's possible the actual amount depends on the state of the destination
/// chain (destination dutch auction, for instance), so these outputs should be considered a cap on filler liabilities.
Output[] maxSpent;
/// @dev The minimum outputs that must to be given to the filler as part of order settlement. Similar to maxSpent, it's possible
/// that special order types may not be able to guarantee the exact amount at open time, so this should be considered
/// a floor on filler receipts.
Output[] minReceived;
/// @dev Each instruction in this array is parameterizes a single leg of the fill. This provides the filler with the information
/// necessary to perform the fill on the destination(s).
FillInstruction[] fillInstructions;
}
/// @notice Tokens that must be receive for a valid order fulfillment
struct Output {
/// @dev The address of the ERC20 token on the destination chain
/// @dev address(0) used as a sentinel for the native token
bytes32 token;
/// @dev The amount of the token to be sent
uint256 amount;
/// @dev The address to receive the output tokens
bytes32 recipient;
/// @dev The destination chain for this output
uint256 chainId;
}
/// @title FillInstruction type
/// @notice Instructions to parameterize each leg of the fill
/// @dev Provides all the origin-generated information required to produce a valid fill leg
struct FillInstruction {
/// @dev The contract address that the order is meant to be settled by
uint64 destinationChainId;
/// @dev The contract address that the order is meant to be filled on
bytes32 destinationSettler;
/// @dev The data generated on the origin chain needed by the destinationSettler to process the fill
bytes originData;
}
}
src/erc7683/IOriginSettler.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity =0.8.24;
import { IERC7683 } from "./IERC7683.sol";
/// @title IOriginSettler
/// @notice Standard interface for settlement contracts on the origin chain
/// @dev See https://github.com/ethereum/ERCs/blob/master/ERCS/erc-7683.md
interface IOriginSettler is IERC7683 {
/// @notice Opens a gasless cross-chain order on behalf of a user.
/// @dev To be called by the filler.
/// @dev This method must emit the Open event
/// @param order The GaslessCrossChainOrder definition
/// @param signature The user's signature over the order
/// @param originFillerData Any filler-defined data required by the settler
// function openFor(GaslessCrossChainOrder calldata order, bytes calldata signature, bytes calldata originFillerData) external;
/// @notice Opens a cross-chain order
/// @dev To be called by the user
/// @dev This method must emit the Open event
/// @param order The OnchainCrossChainOrder definition
function open(OnchainCrossChainOrder calldata order) external payable;
/// @notice Resolves a specific GaslessCrossChainOrder into a generic ResolvedCrossChainOrder
/// @dev Intended to improve standardized integration of various order types and settlement contracts
/// @param order The GaslessCrossChainOrder definition
/// @param originFillerData Any filler-defined data required by the settler
/// @return ResolvedCrossChainOrder hydrated order data including the inputs and outputs of the order
// function resolveFor(GaslessCrossChainOrder calldata order, bytes calldata originFillerData) external view returns (ResolvedCrossChainOrder memory);
/// @notice Resolves a specific OnchainCrossChainOrder into a generic ResolvedCrossChainOrder
/// @dev Intended to improve standardized integration of various order types and settlement contracts
/// @param order The OnchainCrossChainOrder definition
/// @return ResolvedCrossChainOrder hydrated order data including the inputs and outputs of the order
function resolve(OnchainCrossChainOrder calldata order) external view returns (ResolvedCrossChainOrder memory);
}
src/ext/IArbSys.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity =0.8.24;
/**
* @title IArbSys
* @notice Interface for Arbitrum's ArbSys precompile (0x0000000000000000000000000000000000000064)
* @custom:source https://github.com/OffchainLabs/nitro-contracts/blob/main/src/precompiles/ArbSys.sol
*/
interface IArbSys {
/**
* @notice Get Arbitrum block number (distinct from L1 block number; Arbitrum genesis block has block number 0)
* @return block number as int
*/
function arbBlockNumber() external view returns (uint256);
}
src/interfaces/ISolverNetInbox.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity =0.8.24;
import { IOriginSettler } from "../erc7683/IOriginSettler.sol";
interface ISolverNetInbox is IOriginSettler {
// Validation errors
error InvalidOrderTypehash();
error InvalidOrderData();
error InvalidChainId();
error InvalidFillDeadline();
error InvalidMissingCalls();
error InvalidCallTarget();
error InvalidExpenseToken();
error InvalidExpenseAmount();
error InvalidArrayLength();
// Open order errors
error InvalidNativeDeposit();
// Reject order errors
error InvalidReason();
// Order status errors
error OrderNotPending();
error OrderStillValid();
// Order fill errors
error WrongSourceChain();
error WrongFillHash();
// Order claim errors
error OrderNotFilled();
// Pause errors
error IsPaused();
error AllPaused();
error PortalPaused();
/**
* @notice Emitted when an outbox is set.
* @param chainId ID of the chain.
* @param outbox Address of the outbox.
*/
event OutboxSet(uint64 indexed chainId, address indexed outbox);
/**
* @notice Emitted when an order is rejected.
* @param id ID of the order.
* @param by Address of the solver who rejected the order.
* @param reason Reason code for rejecting the order.
*/
event Rejected(bytes32 indexed id, address indexed by, uint8 indexed reason);
/**
* @notice Emitted when an order is cancelled.
* @param id ID of the order.
*/
event Closed(bytes32 indexed id);
/**
* @notice Emitted when an order is filled.
* @param id ID of the order.
* @param fillHash Hash of the fill instructions origin data.
* @param creditedTo Address of the recipient credited the funds by the solver.
*/
event Filled(bytes32 indexed id, bytes32 indexed fillHash, address indexed creditedTo);
/**
* @notice Emitted when an order is claimed.
* @param id ID of the order.
* @param by The solver address that claimed the order.
* @param to The recipient of claimed deposits.
*/
event Claimed(bytes32 indexed id, address indexed by, address indexed to);
/**
* @notice Status of an order.
*/
enum Status {
Invalid,
Pending,
Rejected,
Closed,
Filled,
Claimed
}
/**
* @notice State of an order.
* @param status Latest order status.
* @param rejectReason Reason code for rejecting the order, if rejected.
* @param timestamp Timestamp of the status update.
* @param updatedBy Address for who last updated the order.
*/
struct OrderState {
Status status;
uint8 rejectReason;
uint32 timestamp;
address updatedBy;
}
/**
* @notice Set the outbox addresses for the given chain IDs.
* @param chainIds IDs of the chains.
* @param outboxes Addresses of the outboxes.
*/
function setOutboxes(uint64[] calldata chainIds, address[] calldata outboxes) external;
/**
* @notice Returns the order, its state, and offset with the given ID.
* @param id ID of the order.
*/
function getOrder(bytes32 id)
external
view
returns (ResolvedCrossChainOrder memory order, OrderState memory state, uint248 offset);
/**
* @notice Returns the order ID for the given user and nonce.
* @param user Address of the user.
* @param nonce Nonce of the order.
*/
function getOrderId(address user, uint256 nonce) external view returns (bytes32);
/**
* @notice Returns the next order ID for the given user.
* @param user Address of the user.
*/
function getNextOrderId(address user) external view returns (bytes32);
/**
* @notice Returns the nonce for the given user.
* @param user Address of the user.
*/
function getUserNonce(address user) external view returns (uint256);
/**
* @notice Returns the order offset of the latest order opened at this inbox.
*/
function getLatestOrderOffset() external view returns (uint248);
/**
* @dev Validate the onchain order.
* @param order OnchainCrossChainOrder to validate.
*/
function validate(OnchainCrossChainOrder calldata order) external view returns (bool);
/**
* @notice Reject an open order and refund deposits.
* @dev Only a whitelisted solver can reject.
* @param id ID of the order.
* @param reason Reason code for rejection.
*/
function reject(bytes32 id, uint8 reason) external;
/**
* @notice Close order and refund deposits after fill deadline has elapsed.
* @dev Only order initiator can close.
* @param id ID of the order.
*/
function close(bytes32 id) external;
/**
* @notice Fill an order.
* @dev Only callable by the outbox.
* @param id ID of the order.
* @param fillHash Hash of fill instructions origin data.
* @param creditedTo Address deposits are credited to, provided by the filler.
*/
function markFilled(bytes32 id, bytes32 fillHash, address creditedTo) external;
/**
* @notice Claim deposits for a filled order.
* @param id ID of the order.
* @param to Address to send deposits to.
*/
function claim(bytes32 id, address to) external;
}
src/lib/AddrUtils.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity =0.8.24;
library AddrUtils {
/**
* @dev Convert address to bytes32.
* @param a Address to convert.
*/
function toBytes32(address a) internal pure returns (bytes32) {
return bytes32(uint256(uint160(a)));
}
/**
* @dev Convert bytes32 to address.
* @param b Bytes32 to convert.
*/
function toAddress(bytes32 b) internal pure returns (address) {
return address(uint160(uint256(b)));
}
}
src/lib/SolverNet.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity =0.8.24;
library SolverNet {
/**
* @notice OrderData is the SolverNet's ERC7683 order data encoding, used when opening an order.
* It describes the calls to execute, the expenses required, and the deposit backing the order.
*
* Note that expenses only includes ERC20 expenses, native expenses are inferred from the calls.
* This reduces the order data size, saving gas.
*
* Order expenses (both token expenses and required call values) should be exact. If expenses are underestimated,
* the order will be rejected. If expenses are overestimated, the excess will be refunded to the solver.
*
* Order deposits must cover expenses + solver fees. If they do not, the order will be rejected. To
* determine required deposits, use Omni's solver /quote API, or Omni's SolverNet SDK. (TODO link to docs)
*
* @custom:field owner The address that can close the order. Defaults to msg.sender if zero.
* @custom:field destChainId The chain on which to execute calls.
* @custom:field deposit The deposit paid by the user on the source chain when opening the order.
* @custom:field calls The calls to be executed on the destination chain.
* @custom:field expenses The token expenses required to fill the order, paid by the solver.
*/
struct OrderData {
address owner;
uint64 destChainId;
Deposit deposit;
Call[] calls;
TokenExpense[] expenses;
}
/**
* @notice Order is a convenience struct that fully describes an order.
* @dev It is not written to storage, but rather built on view.
*/
struct Order {
Header header;
Deposit deposit;
Call[] calls;
TokenExpense[] expenses;
}
/**
* @notice Header is an "order header", containing order data not related to deposit, calls, or expenses.
* @dev This struct is used to pack loose order data fields into a single slot.
*/
struct Header {
address owner;
uint64 destChainId;
uint32 fillDeadline;
}
/**
* @notice Deposit describes a deposit (native or ERC20) paid by the user on the source chain when opening an order.
* @custom:field token The address of the token, address(0) if native.
* @custom:field amount The amount of the token deposited.
*/
struct Deposit {
address token;
uint96 amount;
}
/**
* @notice Call describes a call to execute.
* If the call is a native transfer, `target` is the recipient address, and `selector` / `params` are empty.
* @dev Full call data is built from `selector` and `params`: abi.encodePacked(call.selector, call.params).
* @custom:field target The address to execute the call against
* @custom:field selector The function selector to call
* @custom:field value The amount of native token to send with the call
* @custom:field params The call parameters
*/
struct Call {
address target;
bytes4 selector;
uint256 value;
bytes params;
}
/**
* @notice TokenExpense describes an ERC20 expense to be paid by the solver on destination chain when filling an
* order. Native expenses are inferred from the calls, and are not included in the order data.
* @custom:field spender The address that will do token.transferFrom(...) on fill. Required to set allowance.
* @custom:field token The address of the token on the destination chain.
* @custom:field amount The amount of the token to be spent.
*/
struct TokenExpense {
address spender;
address token;
uint96 amount;
}
/**
* @notice FillOriginData is the SolverNet's ERC7683 fill instruction data encoding, used when filling an order.
* @dev The hash(orderId, fillOriginData) is used to prove that a solver properly filled an order.
* @custom:field srcChainId The chain on which the order was opened.
* @custom:field destChainId The chain on which to execute calls.
* @custom:field fillDeadline The deadline by which the order must be filled.
* @custom:field calls The calls to execute on the destination chain.
* @custom:field expenses The token expenses required to fill the order, paid by the solver.
*/
struct FillOriginData {
uint64 srcChainId;
uint64 destChainId;
uint32 fillDeadline;
Call[] calls;
TokenExpense[] expenses;
}
}
src/util/DeployedAt.sol
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity =0.8.24;
import { IArbSys } from "../ext/IArbSys.sol";
/**
* @title DeployedAt
* @notice Provides the block number at which the contract was deployed.
*/
abstract contract DeployedAt {
/**
* @notice Block number at which the contract was deployed.
*/
uint256 public immutable deployedAt;
/**
* @notice Arbitrum's ArbSys precompile (0x0000000000000000000000000000000000000064)
* @dev Used to get Arbitrum block number.
*/
address internal constant ARB_SYS = 0x0000000000000000000000000000000000000064;
constructor() {
// Must get Arbitrum block number from ArbSys precompile, block.number returns L1 block number on Arbitrum.
if (_isContract(ARB_SYS)) {
try IArbSys(ARB_SYS).arbBlockNumber() returns (uint256 arbBlockNumber) {
deployedAt = arbBlockNumber;
} catch {
deployedAt = block.number;
}
} else {
deployedAt = block.number;
}
}
/**
* @dev Returns true if the address is a contract.
* @param addr Address to check.
*/
function _isContract(address addr) internal view returns (bool) {
uint32 size;
assembly {
size := extcodesize(addr)
}
return (size > 0);
}
}
Compiler settingsShow
{
"metadata": {
"bytecodeHash": "ipfs"
},
"libraries": {},
"optimizer": {
"runs": 200,
"enabled": true
},
"evmVersion": "cancun",
"remappings": [
":@openzeppelin/=node_modules/@openzeppelin/",
":core/=../core/",
":ds-test/=node_modules/ds-test/src/",
":forge-std/=node_modules/forge-std/src/",
":solady/=node_modules/solady/",
":src/=src/",
":test/=test/"
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.