Verified contractPartialBUSL-1.1
Account
Address0x726aaac210593e03e85810a42a5c8d49c7cf6027
- Balance
0 ETH
- Transactions
2
- Compiler
solc 0.8.22
- Same code
1 more contract
Details
- Compiler
- solc 0.8.22+commit.4fc1097e
- Language
- solidity
- Optimization
- Yes, 1,000,000 runs
- EVM version
- paris
- License
- BUSL-1.1
- Match
- Partialcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,455,753
- Creation transaction
- 0x28dcc89711…57aa919203
- Libraries
- contracts/marginAccount/Account.sol:CommandExecutor0x2d2f…daa35d
38 files
- contracts/marginAccount/Account.solmain11.69 KB
- @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol8.91 KB
- @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol1.18 KB
- @openzeppelin/contracts/token/ERC20/IERC20.sol2.78 KB
- @openzeppelin/contracts/utils/Address.sol6.26 KB
- @openzeppelin/contracts/utils/introspection/IERC165.sol869 B
- contracts/base/StateMachine.sol5.89 KB
- contracts/base/auth/OwnableAssignable.sol1.25 KB
- contracts/base/auth/OwnableReadonly.sol860 B
- contracts/dispatcher/libraries/EnvelopeRunner.sol3.31 KB
- contracts/dispatcher/libraries/PackageRunner.sol947 B
- contracts/interfaces/base/CommonErrors.sol1.21 KB
- contracts/interfaces/base/IERC165Extended.sol1.18 KB
- contracts/interfaces/common/IInitializable.sol127 B
- contracts/interfaces/compiler/Command.sol606 B
- contracts/interfaces/compiler/IJitCompiler.sol7.82 KB
- contracts/interfaces/compiler/Script.sol2.06 KB
- contracts/interfaces/compiler/adapters/IDecreasePositionEvaluator.sol1.44 KB
- contracts/interfaces/compiler/adapters/IExchangeEvaluator.sol1.51 KB
- contracts/interfaces/compiler/adapters/IIncreasePositionEvaluator.sol1.46 KB
- contracts/interfaces/compiler/adapters/PositionDescriptor.sol503 B
- contracts/interfaces/compliance/Asset.sol407 B
- contracts/interfaces/compliance/IWhitelistingControllerAgreement.sol4.37 KB
- contracts/interfaces/dispatcher/Envelope.sol1.51 KB
- contracts/interfaces/dispatcher/IDispatcher.sol6.94 KB
- contracts/interfaces/dispatcher/Package.sol904 B
- contracts/interfaces/liquidator/ILiquidator.sol1.76 KB
- contracts/interfaces/marginAccount/IAccount.sol6.34 KB
- contracts/interfaces/marginAccount/IAccountStateMachine.sol318 B
- contracts/libraries/Address.sol1.18 KB
- contracts/libraries/AssetLibrary.sol1.57 KB
- contracts/libraries/CalldataLibrary.sol649 B
- contracts/libraries/CommandLibrary.sol2.6 KB
- contracts/libraries/SafeCall.sol1.24 KB
- contracts/marginAccount/base/CommandSafeExecutor.sol2.55 KB
- solady/src/utils/LibBit.sol6.67 KB
- solady/src/utils/LibString.sol46.58 KB
- solady/src/utils/SafeTransferLib.sol16.43 KB
contracts/marginAccount/Account.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {
ERC165Upgradeable
} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";
import {ArrayMustNotBeEmpty, UnauthorizedAccount} from "contracts/interfaces/base/CommonErrors.sol";
import {IJitCompiler} from "contracts/interfaces/compiler/IJitCompiler.sol";
import {LEGACY_DISPATCHER_INTERFACE_ID} from "contracts/interfaces/dispatcher/IDispatcher.sol";
import {ILiquidator} from "contracts/interfaces/liquidator/ILiquidator.sol";
import {
Asset,
IAccount,
LEGACY_ACCOUNT_INTERFACE_ID,
Script
} from "contracts/interfaces/marginAccount/IAccount.sol";
import {OwnableAssignable} from "contracts/base/auth/OwnableAssignable.sol";
import {State, StateMachine} from "contracts/base/StateMachine.sol";
import {Address} from "contracts/libraries/Address.sol";
import {Command, CommandExecutor} from "contracts/libraries/CommandLibrary.sol";
import {
CommandSafeExecutor,
IERC165Extended,
UnsupportedInterface
} from "./base/CommandSafeExecutor.sol";
contract Account is
IAccount,
Initializable,
ERC165Upgradeable,
OwnableAssignable,
StateMachine,
CommandSafeExecutor
{
using SafeTransferLib for address;
using CommandExecutor for Command[];
using Address for address;
struct Storage {
address agreement;
Asset leverage;
uint256 stateSwitchTime;
}
// keccak256("Margin Account storage slot V1");
bytes32 private constant STORAGE_SLOT =
0x519f3f99a0c1f1fb9111c45187b72642177afca1331d79be42ec8d4962b43f22;
address internal immutable dispatcher;
address internal immutable liquidator;
IJitCompiler internal immutable compiler;
/* solhint-disable immutable-vars-naming */
State internal immutable STATE_CLOSED = newStateFromId(0);
State internal immutable STATE_REGISTERED = newStateFromId(1);
State internal immutable STATE_OPENED = newStateFromId(2);
State internal immutable STATE_SUSPENDED = newStateFromId(3);
/* solhint-enable immutable-vars-naming */
// keccak256("Margin Account BlockGuard.lastBlock")
bytes32 internal constant STORAGE_SLOT_LAST_BLOCK =
0x50d7cfcc7a000ee091816fd09deb7636042e33504ea29e7fd064edcc26f57f48;
/**
* @notice Prevents repeated transactions within the same block.
* @dev This modifier blocks multiple calls in a single block to prevent double sandwiching attacks,
* where an attacker exploits multiple transactions in rapid succession to manipulate asset prices.
*/
modifier blockGuard() {
uint256 lastBlock;
assembly {
lastBlock := sload(STORAGE_SLOT_LAST_BLOCK)
}
if (lastBlock == block.number) revert ReentrantTransactionInSameBlock();
lastBlock = block.number;
assembly {
sstore(STORAGE_SLOT_LAST_BLOCK, lastBlock)
}
_;
}
modifier onlyDispatcher() {
if (msg.sender != dispatcher) revert UnauthorizedAccount(msg.sender);
_;
}
modifier onlyLiquidator() {
if (msg.sender != liquidator) revert UnauthorizedAccount(msg.sender);
_;
}
constructor(
address dispatcher_,
address liquidator_,
address compliance_,
address compiler_
) CommandSafeExecutor(compliance_) {
if (
!IERC165Extended(dispatcher_).supportsInterfaceExtended(LEGACY_DISPATCHER_INTERFACE_ID)
) {
revert UnsupportedInterface(dispatcher_);
}
if (
!IERC165Extended(liquidator_).supportsInterfaceExtended(type(ILiquidator).interfaceId)
) {
revert UnsupportedInterface(liquidator_);
}
if (!IERC165Extended(compiler_).supportsInterfaceExtended(type(IJitCompiler).interfaceId)) {
revert UnsupportedInterface(compiler_);
}
dispatcher = dispatcher_;
liquidator = liquidator_;
compiler = IJitCompiler(compiler_);
}
receive() external payable override {}
function initialize() external override reinitializer(3) {
if (!transitionExists(STATE_UNDEFINED, STATE_REGISTERED)) {
// X -> REGISTERED
createTransition(STATE_UNDEFINED, STATE_REGISTERED, this.registerAccount);
createTransition(STATE_CLOSED, STATE_REGISTERED, this.registerAccount);
// X -> OPENED
createTransition(STATE_REGISTERED, STATE_OPENED, this.openAccount);
// X -> SUSPENDED
createTransition(STATE_OPENED, STATE_SUSPENDED, this.suspendAccount);
// X -> CLOSED
createTransition(STATE_SUSPENDED, STATE_CLOSED, this.closeAccount);
}
// X -> CLOSED (cancellation of a registration that was never allocated)
if (!transitionExists(STATE_REGISTERED, STATE_CLOSED)) {
createTransition(STATE_REGISTERED, STATE_CLOSED, this.closeAccount);
}
}
function register(
address _user,
address _agreement,
Asset[] calldata _collaterals,
Asset calldata _leverage
) external override onlyDispatcher onlyState(STATE_UNDEFINED | STATE_CLOSED) {
for (uint256 i; i < _collaterals.length; i++) {
_collaterals[i].enforceReceived();
}
changeState(STATE_REGISTERED, abi.encode(_user, _agreement, _collaterals, _leverage));
}
function supply() external override onlyDispatcher onlyState(STATE_REGISTERED) {
_storage().leverage.receiveFrom(msg.sender);
changeState(STATE_OPENED);
}
/// @dev Invariant: only OPENED accounts are closeable, SUSPENDED means mid-liquidation,
/// recoverable only by the liquidator.
function close(
address[] calldata tokens,
address recipient
) external override onlyDispatcher onlyState(STATE_OPENED) {
changeState(STATE_SUSPENDED);
// Native ETH cannot service the ERC20 debt, so it is returned straight to the owner;
// ERC20 balances are swept to the recipient (dispatcher) for repayment and refund.
for (uint256 i; i < tokens.length; i++) {
if (tokens[i].isEth()) {
uint256 ethBalance = address(this).balance;
if (ethBalance > 0) _owner().forceSafeTransferETH(ethBalance);
} else {
uint256 balance = tokens[i].balanceOf(address(this));
if (balance > 0) tokens[i].safeTransfer(recipient, balance);
}
}
changeState(STATE_CLOSED);
}
/// @dev Registration moved collateral in but took no debt so there is nothing to settle: the
/// balances go straight to the owner and the account is recycled. ETH is force-sent.
function cancel(
address[] calldata tokens
) external override onlyDispatcher onlyState(STATE_REGISTERED) {
address recipient = _owner();
for (uint256 i; i < tokens.length; i++) {
if (tokens[i].isEth()) {
uint256 ethBalance = address(this).balance;
if (ethBalance > 0) recipient.forceSafeTransferETH(ethBalance);
} else {
uint256 balance = tokens[i].balanceOf(address(this));
if (balance > 0) tokens[i].safeTransfer(recipient, balance);
}
}
changeState(STATE_CLOSED);
}
function liquidate(
Script[] calldata liquidationStrategy
)
external
override
onlyLiquidator
onlyState(STATE_OPENED | STATE_SUSPENDED)
returns (bool success)
{
return _runScript(liquidationStrategy);
}
function withdraw(
address token,
address recipient,
uint256 amount
) external override onlyLiquidator {
token.safeTransfer(recipient, amount);
}
function execute(
Command calldata cmd
) external override onlyOwner onlyState(STATE_OPENED) blockGuard {
CommandSafeExecutor.validateAndExecute(cmd);
}
// State Machine Transitions
// NOTE: You MUST NOT change names of these functions because it
// will break state machine setup in all proxies. To change the
// name you must increment version of this contract and call
// reinitializer(nextVersion) for all proxies.
function registerAccount(bytes calldata args) external override transition {
Storage storage $ = _storage();
_beforeStateSwitch($);
(address user, address _agreement, Asset[] memory collateral, Asset memory _leverage) = abi
.decode(args, (address, address, Asset[], Asset));
_assignOwner(user);
$.agreement = _agreement;
$.leverage = _leverage;
emit AccountRegistered(user, _agreement, collateral, _leverage);
}
function openAccount(bytes calldata) external override transition {
Storage storage $ = _storage();
_beforeStateSwitch($);
emit AccountOpened(_owner());
}
function suspendAccount(bytes calldata) external override transition {
_beforeStateSwitch(_storage());
emit AccountSuspended(_owner());
}
function closeAccount(bytes calldata) external override transition {
Storage storage $ = _storage();
_beforeStateSwitch($);
address previousOwner = _owner();
_unassignOwner();
delete $.leverage;
emit AccountClosed(previousOwner);
}
function stateInfo() external view override returns (State, uint256) {
return (currentState(), _storage().stateSwitchTime);
}
function allocationInfo()
external
view
override
returns (State, uint256, address, address, uint256)
{
Storage storage $ = _storage();
return (currentState(), $.stateSwitchTime, _owner(), $.leverage.token, $.leverage.amount);
}
function agreement() external view override returns (address) {
return _storage().agreement;
}
function leverage() external view override returns (address, uint256) {
Storage storage $ = _storage();
return ($.leverage.token, $.leverage.amount);
}
function owner() external view override returns (address) {
return _owner();
}
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
// @dev Also advertise the legacy id so the on-chain AccountFactory beacon accepts this on upgrade.
return
interfaceId == type(IAccount).interfaceId || interfaceId == LEGACY_ACCOUNT_INTERFACE_ID;
}
function _beforeStateSwitch(Storage storage $) private {
/* solhint-disable-next-line not-rely-on-time */
$.stateSwitchTime = block.timestamp;
}
function _runScript(Script[] calldata script) private returns (bool success) {
uint256 length = script.length;
if (length == 0) revert ArrayMustNotBeEmpty();
if (currentState() == STATE_OPENED) changeState(STATE_SUSPENDED);
for (uint256 i; i < length; i++) {
Command[] memory cmds = compiler.compile(script[i]);
/* solhint-disable-next-line no-empty-blocks */
try cmds.execute() {} catch {
return success = false;
}
}
changeState(STATE_CLOSED);
return success = true;
}
function _storage() private pure returns (Storage storage $) {
assembly {
$.slot := STORAGE_SLOT
}
}
}
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
@openzeppelin/contracts/token/ERC20/IERC20.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
@openzeppelin/contracts/utils/Address.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
@openzeppelin/contracts/utils/introspection/IERC165.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
contracts/base/StateMachine.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {LibBit} from "solady/src/utils/LibBit.sol";
type State is uint256;
using {and as &, neq as !=, eq as ==, or as |, includes, isInitialized, isValid} for State global;
function and(State self, State value) pure returns (State) {
return State.wrap(State.unwrap(self) & State.unwrap(value));
}
function neq(State self, State value) pure returns (bool) {
return State.unwrap(self) != State.unwrap(value);
}
function eq(State self, State value) pure returns (bool) {
return State.unwrap(self) == State.unwrap(value);
}
function or(State self, State value) pure returns (State) {
return State.wrap(State.unwrap(self) | State.unwrap(value));
}
function includes(State bitmap, State state) pure returns (bool) {
return State.unwrap(bitmap) & State.unwrap(state) != 0;
}
function isInitialized(State self) pure returns (bool answer_) {
return State.unwrap(self) != 0;
}
function isValid(State self) pure returns (bool) {
// most significant bit is reserved for the undefined state
uint256 mask = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
return LibBit.isPo2(State.unwrap(self) & mask);
}
abstract contract StateMachine {
struct StateStorage {
State currentState;
mapping(bytes32 transitionId => function(bytes memory) external transition) transitions;
}
// Undefined state cannot be zero because it will break bitmap comparison math in `onlyState`
/* solhint-disable-next-line immutable-vars-naming */
State internal immutable STATE_UNDEFINED = _newStateFromIdUnchecked(STATE_UNDEFINED_ID);
uint8 private constant STATE_UNDEFINED_ID = type(uint8).max;
// keccak256("StateMachine storage slot V2");
bytes32 private constant STORAGE_SLOT_STATE_MACHINE =
0xde4001bbdfdfed078acd4ae5c1023679bf2e3e2982cfd37f7c839d62304fe30d;
event StateChanged(State from, State to);
error TransitionAlreadyExists(State from, State to);
error TransitionDoesNotExist(State from, State to);
error UnexpectedState(State expectedStatesBitmap, State currentState);
// If transition function exists on current contract
// then it must be called only from the current contract.
error HostedTransitionMustBeCalledFromSelf();
// A valid state must be in form of 2^n, where n ∈ {x | x ∈ uint8, x < STATE_UNDEFINED_ID}.
error InvalidState(State);
error IdIsReservedForUndefinedState(uint256);
modifier onlyState(State _expectedStatesBitmap) {
State state = _currentState(_stateStorage());
if (!_expectedStatesBitmap.includes(state))
revert UnexpectedState(_expectedStatesBitmap, state);
_;
}
modifier transition() {
if (msg.sender != address(this)) revert HostedTransitionMustBeCalledFromSelf();
_;
}
function createTransition(
State _from,
State _to,
function(bytes memory) external _transition
) internal {
bytes32 id = _getTransitionId(_from, _to);
if (_isTransitionExists(id)) revert TransitionAlreadyExists(_from, _to);
_stateStorage().transitions[id] = _transition;
}
function changeState(State _newState) internal {
changeState(_newState, "");
}
function changeState(State _newState, bytes memory _transitionArgs) internal {
if (!_newState.isValid()) revert InvalidState(_newState);
StateStorage storage $ = _stateStorage();
State state = _currentState($);
bytes32 id = _getTransitionId(state, _newState);
if (!_isTransitionExists(id)) revert TransitionDoesNotExist(state, _newState);
emit StateChanged(state, _newState);
$.currentState = _newState;
$.transitions[id](_transitionArgs);
}
function transitionExists(State _from, State _to) internal view returns (bool) {
return _isTransitionExists(_getTransitionId(_from, _to));
}
function currentState() internal view returns (State currentState_) {
return _currentState(_stateStorage());
}
function newStateFromId(uint8 _stateId) internal pure returns (State) {
if (_stateId == STATE_UNDEFINED_ID) revert IdIsReservedForUndefinedState(_stateId);
return _newStateFromIdUnchecked(_stateId);
}
function _currentState(StateStorage storage $) private view returns (State state) {
state = $.currentState;
// We substitute 0 with STATE_UNDEFINED here in order to avoid storage
// initialization with default value to save gas
if (!state.isInitialized()) state = STATE_UNDEFINED;
}
function _isTransitionExists(bytes32 _transitionId) private view returns (bool exists_) {
mapping(bytes32 => function(bytes memory) external) storage map = _stateStorage()
.transitions;
assembly {
// we won't use this memory location after keccak so it's safe to use 0x00 and 0x20
mstore(0x00, _transitionId)
mstore(0x20, map.slot)
let position := keccak256(0x00, 64)
// callback = map[_transition]
let callback := sload(position)
// exists_ = callback != null
exists_ := iszero(iszero(callback))
}
}
function _getTransitionId(State _from, State _to) private view returns (bytes32) {
if (_from != STATE_UNDEFINED && !_from.isValid()) revert InvalidState(_from);
if (!_to.isValid()) revert InvalidState(_to);
return keccak256(abi.encodePacked(_from, _to));
}
function _newStateFromIdUnchecked(uint8 _stateId) private pure returns (State) {
return State.wrap(1 << _stateId);
}
function _stateStorage() private pure returns (StateStorage storage $) {
assembly {
$.slot := STORAGE_SLOT_STATE_MACHINE
}
}
}
contracts/base/auth/OwnableAssignable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Address} from "contracts/libraries/Address.sol";
import {OwnableReadonly} from "./OwnableReadonly.sol";
abstract contract OwnableAssignable is OwnableReadonly {
using Address for bytes32;
bytes32 private constant OWNER = keccak256("OwnableAssignable owner slot V1");
event OwnerHasBeenAssigned(address indexed previousOwner, address indexed newOwner);
event OwnerHasBeenUnassigned(address indexed previousOwner);
error NewOwnerMustBeNonZeroAddress();
error OwnerDoesNotExist();
function _assignOwner(address _newOwner) internal returns (address previousOwner_) {
if (_newOwner == address(0)) revert NewOwnerMustBeNonZeroAddress();
previousOwner_ = _owner();
_ownerSlot().set(_newOwner);
emit OwnerHasBeenAssigned(previousOwner_, _newOwner);
}
function _unassignOwner() internal returns (address previousOwner_) {
if ((previousOwner_ = _owner()) == address(0)) revert OwnerDoesNotExist();
_ownerSlot().set(address(0));
emit OwnerHasBeenUnassigned(previousOwner_);
}
function _ownerSlot() internal pure virtual override returns (bytes32) {
return OWNER;
}
}
contracts/base/auth/OwnableReadonly.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {UnauthorizedAccount} from "contracts/interfaces/base/CommonErrors.sol";
import {Address} from "contracts/libraries/Address.sol";
/**
* @dev We intentionally do not expose "owner()" publicly
* due to possible conflicts with "OwnershipFacet"
* https://github.com/mudgen/diamond-3-hardhat/blob/main/contracts/facets/OwnershipFacet.sol
*/
abstract contract OwnableReadonly {
using Address for bytes32;
modifier onlyOwner() {
enforceIsContractOwner();
_;
}
function _owner() internal view returns (address) {
return _ownerSlot().get();
}
function _ownerSlot() internal pure virtual returns (bytes32);
function enforceIsContractOwner() private view {
if (msg.sender != _owner()) revert UnauthorizedAccount(msg.sender);
}
}
contracts/dispatcher/libraries/EnvelopeRunner.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {IJitCompiler, Script} from "contracts/interfaces/compiler/IJitCompiler.sol";
import {CrossChainActionIsForbidden, Envelope} from "contracts/interfaces/dispatcher/Envelope.sol";
import {Command, CommandExecutor} from "contracts/libraries/CommandLibrary.sol";
library EnvelopeRunner {
using CommandExecutor for Command[];
/**
* @dev This error should never happen, it is needed
* for preventing underestimation on "eth_estimateGas".
*/
error OutOfGas();
function run(
Envelope[] calldata self,
address jitCompiler,
bytes32 chainNameHash
) internal returns (uint256 numberOfFailures) {
for (uint256 i; i < self.length; i++) {
numberOfFailures += self[i].run(jitCompiler, chainNameHash) ? 0 : 1;
}
}
function run(
Envelope calldata self,
address jitCompiler,
bytes32 chainNameHash
) internal returns (bool success) {
IJitCompiler compiler = IJitCompiler(jitCompiler);
if (!self.isChainEq(chainNameHash)) {
revert CrossChainActionIsForbidden();
}
for (uint256 i; i < self.content.length; i++) {
if (!run(compiler, self.content[i])) return success = false;
}
return success = true;
}
function isChainEq(Envelope calldata self, bytes32 chainNameHash) internal pure returns (bool) {
return keccak256(bytes(self.route.destination)) == chainNameHash;
}
function run(IJitCompiler compiler, Script calldata script) private returns (bool success) {
Command[] memory cmds = compiler.compile(script);
if (script.canFail) {
uint256 gasBefore = gasleft();
/* solhint-disable-next-line no-empty-blocks */
try cmds.execute() {} catch {
// NOTE: Since we allow silent fail here, this revert is
// required to prevent the underestimation of gas in the
// context of EIP-150. The "all but one 64th" rule, along
// with the way most clients estimate gas, may produce an
// out-of-gas error at the callee contract but success at
// the caller contract. For example, if we have a single
// instruction to execute, and after executing this
// instruction, the remaining work will consume 5000 gas,
// the instruction will only receive at most 5000*63 gas.
// Therefore, if the actual requirements are higher, it
// will fail at the random opcode. The remaining work
// will be finished (since we still have at least 5000*1
// gas), and overall transaction success will be achieved,
// making the gas estimator happy.
//
// The proportion for comparing the gasleft (to check that
// the call has not consumed all the gas passed) is in practice
// 1 to 16-32, but we take twice as much just in case.
if (gasleft() < gasBefore / 8) revert OutOfGas();
return false;
}
} else {
cmds.execute();
}
return true;
}
}
contracts/dispatcher/libraries/PackageRunner.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Package} from "contracts/interfaces/dispatcher/Package.sol";
import {Command, SafeCall} from "contracts/libraries/SafeCall.sol";
import {CrossChainActionIsForbidden, Envelope, EnvelopeRunner} from "./EnvelopeRunner.sol";
library PackageRunner {
using SafeCall for Command[];
using EnvelopeRunner for Envelope[];
function run(
Package calldata self,
address compiler,
bytes32 chainNameHash
) internal returns (uint256 numberOfFailures) {
if (self.action.isChainEq(chainNameHash)) {
bool actionSuccess = self.action.run(compiler, chainNameHash);
if (actionSuccess) {
numberOfFailures += self.onComplete.run(compiler, chainNameHash);
} else {
numberOfFailures++;
}
} else {
revert CrossChainActionIsForbidden();
}
}
}
contracts/interfaces/base/CommonErrors.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/**
* @notice An error indicating that the amount for the specified token is zero.
* @param token The address of the token with a zero amount.
*/
error AmountMustNotBeZero(address token);
/**
* @notice An error indicating that an address must not be zero.
*/
error AddressMustNotBeZero();
/**
* @notice An error indicating that an array must not be empty.
*/
error ArrayMustNotBeEmpty();
/**
* @notice An error indicating that an string must not be empty.
*/
error StringMustNotBeEmpty();
/**
* @notice An error indicating storage is already up to date and doesn't need further processing.
* @dev This error is thrown when attempting to update an entity(s) that is(are) already up to date.
*/
error AlreadyUpToDate();
/**
* @notice An error indicating that an action is unauthorized for the specified account.
* @param account The address of the unauthorized account.
*/
error UnauthorizedAccount(address account);
/**
* @notice An error indicating that the min amount out must not be zero.
*/
error MinAmountOutMustNotBeZero();
/**
* @notice An error indicating that the threshold exceeds the maximum allowed value.
*/
contracts/interfaces/base/IERC165Extended.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/* solhint-disable no-unused-import */
import {
IERC165
} from "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
/* solhint-enable no-unused-import */
/**
* @notice An error indicating that an address does not support the expected interface
* @param implementation The address that does not implement the required interface
*/
error UnsupportedInterface(address implementation);
/**
* @dev Extended interface of the ERC165 standard to ensure compatibility
* with Diamond facets as defined in EIP-2535.
*
* This interface extends the basic ERC165 mechanism to provide additional
* flexibility for querying supported interfaces, which can then be
* dynamically resolved by one of facets in a Diamond.
*/
interface IERC165Extended {
/**
* @notice Checks if the given interface ID is supported by the contract.
* @param interfaceId The ID of the interface to query.
* @return isSupported Boolean value indicating whether the interface is supported.
*/
function supportsInterfaceExtended(bytes4 interfaceId) external pure returns (bool isSupported);
}
contracts/interfaces/common/IInitializable.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
interface IInitializable {
function initialize() external;
}
contracts/interfaces/compiler/Command.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {CommandLibrary} from "contracts/libraries/CommandLibrary.sol";
/**
* @title Command
* @notice Contains arguments for a low-level call.
* @dev This struct allows deferring the call's execution, suspending it by passing it to another function or contract.
* @dev `target` The address to be called.
* @dev `value` Value to send in the call.
* @dev `payload` Encoded call with function selector and arguments.
*/
struct Command {
address target;
uint256 value;
bytes payload;
}
using CommandLibrary for Command global;
contracts/interfaces/compiler/IJitCompiler.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {IERC165Extended} from "contracts/interfaces/base/IERC165Extended.sol";
import {IDecreasePositionEvaluator} from "./adapters/IDecreasePositionEvaluator.sol";
import {IExchangeEvaluator} from "./adapters/IExchangeEvaluator.sol";
import {IIncreasePositionEvaluator} from "./adapters/IIncreasePositionEvaluator.sol";
import {Command} from "./Command.sol";
import {Script} from "./Script.sol";
/**
* @title IJitCompiler
* @notice Compiles a script or an instruction into an array of [Commands](/interfaces/compiler/Command.sol/struct.Command.html) using protocol evaluator matching `protocol` field in the underlying instruction.
*/
interface IJitCompiler is IERC165Extended {
/**
* @notice Instruction designed to increase:
* 1. Caller's magnitude of the position determined by the [PositionDescriptor](../adapters/PositionDescriptor.sol/struct.PositionDescriptor.html).
* 2. Callee's balance of token(s).
* @notice and decrease:
* 1. Caller's balance of token(s).
* 2. (*Optional*) callee's supply of the position determined by the [PositionDescriptor](../adapters/PositionDescriptor.sol/struct.PositionDescriptor.html).
* @dev This instruction will be evaluated in [IncreasePositionEvaluator](../adapters/IIncreasePositionEvaluator.sol/interface.IIncreasePositionEvaluator.html).
* @dev `protocol` The name of the underlying protocol where instruction should be evaluated. For example: `curvefi`, `oneinchv5`
* @dev `request` The [`IncreasePositionRequest`](../adapters/IIncreasePositionEvaluator.sol/interface.IIncreasePositionEvaluator.html#increasepositionrequest) containing all information required for instruction evaluation.
*/
struct IncreasePositionInstruction {
string protocol;
IIncreasePositionEvaluator.IncreasePositionRequest request;
}
/**
* @notice Instruction designed to increase:
* 1. Caller's balance of token(s).
* 2. (*Optional*) callee's supply of the position determined by the [PositionDescriptor](../adapters/PositionDescriptor.sol/struct.PositionDescriptor.html).
* @notice and decrease:
* 1. Caller's magnitude of the position determined by the [PositionDescriptor](../adapters/PositionDescriptor.sol/struct.PositionDescriptor.html).
* 2. Callee's balance of token(s).
* @dev This instruction will be evaluated in [DecreasePositionEvaluator](../adapters/IDecreasePositionEvaluator.sol/interface.IDecreasePositionEvaluator.html).
* @dev `protocol` The name of the underlying protocol where instruction should be evaluated. For example: `curvefi`, `oneinchv5`
* @dev `request` The [`DecreasePositionRequest`](../adapters/IDecreasePositionEvaluator.sol/interface.IDecreasePositionEvaluator.html#decreasepositionrequest) containing all information required for instruction evaluation.
*/
struct DecreasePositionInstruction {
string protocol;
IDecreasePositionEvaluator.DecreasePositionRequest request;
}
/**
* @notice Instruction designed to increase:
* 1. (*Optional*) caller's balance of output token.
* 2. Callee's balance of input token.
* @notice and decrease:
* 1. Caller's balance of input token.
* 2. (*Optional*) callee's balance of output token.
* @dev This instruction will be evaluated in [ExchangeEvaluator](../adapters/IExchangeEvaluator.sol/interface.IExchangeEvaluator.html).
* @dev `protocol` The name of the underlying protocol where instruction should be evaluated. For example: `curvefi`, `oneinchv5`
* @dev `request` The [`ExchangeRequest`](../adapters/IExchangeEvaluator.sol/interface.IExchangeEvaluator.html#exchangerequest) containing all information required for instruction evaluation.
*/
struct ExchangeInstruction {
string protocol;
IExchangeEvaluator.ExchangeRequest request;
}
/**
* @notice Instruction designed to increase:
* 1. (*Optional*) caller's balance of output token.
* 2. Callee's balance of input token.
* @notice and decrease:
* 1. Caller's balance of input token.
* 2. (*Optional*) callee's balance of output token.
* @dev This instruction will be evaluated in [ExchangeEvaluator](../adapters/IExchangeEvaluator.sol/interface.IExchangeEvaluator.html).
* @dev **Important note:** this instruction has an identical structure to [ExchangeInstruction](#exchangeinstruction), but differs from it in that [ExchangeInstruction](#exchangeinstruction) is static and [ExchangeAllInstruction](#exchangeallinstruction) is dynamic. This means that the `amountIn` field will be set at runtime by the compiler to the caller's balance by the input token.
* @dev `protocol` The name of the underlying protocol where instruction should be evaluated. For example: `curvefi`, `oneinchv5`
* @dev `request` The [`ExchangeRequest`](../adapters/IExchangeEvaluator.sol/interface.IExchangeEvaluator.html#exchangerequest) containing all information required for instruction evaluation. The `amountIn` field will be set at runtime by the compiler to the caller's balance by the input token.
*/
struct ExchangeAllInstruction {
string protocol;
IExchangeEvaluator.ExchangeRequest request;
}
/**
* @notice Compiles a [Script](../Script.sol/struct.Script.html).
* @dev **Important note:** don't put two instructions to the same script if one depend on the other because content of the script will be compiled at once meaning that balance changes will be applied only after the compilation of the entire script. If you have two instructions and one depends on the other, put them into different scripts.
* @param script Script to compile
* @return An array of [`Commands`](../Command.sol/struct.Command.html) to execute the instruction.
*/
function compile(Script calldata script) external returns (Command[] memory);
/**
* @notice Compiles an increase position instruction.
* @param instruction The [`IncreasePositionInstruction`](#increasepositioninstruction) struct.
* @return An array of [`Commands`](../Command.sol/struct.Command.html) to execute the instruction.
*/
function compileIncreasePositionInstruction(
IncreasePositionInstruction calldata instruction
) external returns (Command[] memory);
/**
* @notice Compiles a decrease position instruction.
* @param instruction The [`DecreasePositionInstruction`](#decreasepositioninstruction) struct.
* @return An array of [`Commands`](../Command.sol/struct.Command.html) to execute the instruction.
*/
function compileDecreasePositionInstruction(
DecreasePositionInstruction calldata instruction
) external returns (Command[] memory);
/**
* @notice Compiles an exchange instruction.
* @param instruction The [`ExchangeInstruction`](#exchangeinstruction) struct.
* @return An array of [`Commands`](../Command.sol/struct.Command.html) to execute the instruction.
*/
function compileExchangeInstruction(
ExchangeInstruction calldata instruction
) external returns (Command[] memory);
/**
* @notice Sets the `amountIn` field to the balance of the caller by the input token and compiles an underlying exchange instruction.
* @dev `amountIn` will be overridden with the balance of the caller by the input token.
* @param instruction The [`ExchangeAllInstruction`](#exchangeallinstruction) struct.
* @return An array of [`Commands`](../Command.sol/struct.Command.html) to execute the instruction.
*/
function compileExchangeAllInstruction(
ExchangeAllInstruction calldata instruction
) external returns (Command[] memory);
}
contracts/interfaces/compiler/Script.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {IJitCompiler} from "./IJitCompiler.sol";
/**
* @title Script
* @notice A structure defining a script with various instructions for a JIT compiler.
* @notice The [JIT compiler](../IJitCompiler.sol/interface.IJitCompiler.html)
* will compile it the following way:
* 1. Flatten content's instructions arrays into a single-dimensional array: `flattened =
* [...increasePositionInstructions, ...decreasePositionInstructions,
...exchangeInstructions, ...exchangeAllInstructions]`.
* 2. Execute `flattened[PC]` where `PC = sequence[i]` where `i` is the
* index of current loop iteration, starting from `i = 0`.
* 3. Increment current loop iteration index: `i = i + 1`.
* 4. If `i < length(flattened)` go to step 2.
*
* @dev `canFail` Determines whether the script can silently fail. If true
* transaction will not be reverted but execution will be terminated.
* @dev `sequence` Auto-incrementing read-only program counter. Determines the
* order of execution of the instruction within the script.
* @dev `increasePositionInstructions` An array of
* [`IncreasePositionInstructions`](../IJitCompiler.sol/interface.IJitCompiler.html#increasepositioninstruction).
* @dev `decreasePositionInstructions` An array of
* [`DecreasePositionInstructions`](../IJitCompiler.sol/interface.IJitCompiler.html#decreasepositioninstruction).
* @dev `exchangeInstructions` An array of
* [`ExchangeInstructions`](../IJitCompiler.sol/interface.IJitCompiler.html#exchangeinstruction).
* @dev `exchangeAllInstructions` An array of
* [`ExchangeAllInstructions`](../IJitCompiler.sol/interface.IJitCompiler.html#exchangeallinstruction).
*/
struct Script {
bool canFail;
uint256[] sequence;
IJitCompiler.IncreasePositionInstruction[] increasePositionInstructions;
IJitCompiler.DecreasePositionInstruction[] decreasePositionInstructions;
IJitCompiler.ExchangeInstruction[] exchangeInstructions;
IJitCompiler.ExchangeAllInstruction[] exchangeAllInstructions;
}
contracts/interfaces/compiler/adapters/IDecreasePositionEvaluator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Asset} from "contracts/libraries/AssetLibrary.sol";
import {Command} from "../Command.sol";
import {PositionDescriptor} from "./PositionDescriptor.sol";
interface IDecreasePositionEvaluator {
/**
* @notice Request structure for decreasing a position.
* @dev `descriptor`: The [`PositionDescriptor`](/interfaces/compiler/adapters/PositionDescriptor.sol/struct.PositionDescriptor.html)
* struct.
* @dev `liquidity`: Abstract amount that can be interpreted differently in different protocols (e.g., amount of LP tokens to burn).
* @dev `minOutput`: [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) array with minimum amounts that must be retrieved from the position.
*/
struct DecreasePositionRequest {
PositionDescriptor descriptor;
uint256 liquidity;
Asset[] minOutput;
}
/**
* @notice Evaluate a decrease position request.
* @param _operator Address which initiated the request
* @param _request The [`DecreasePositionRequest`](#decreasepositionrequest) struct containing decrease position details.
* @return cmds_ An array of [`Command`](../../Command.sol/struct.Command.html) to execute the request.
*/
function evaluate(
address _operator,
DecreasePositionRequest calldata _request
) external returns (Command[] memory cmds_);
}
contracts/interfaces/compiler/adapters/IExchangeEvaluator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Command} from "../Command.sol";
/**
* @title IExchangeEvaluator
* @notice Interface for compiling commands for token exchanges for different protocols.
*/
interface IExchangeEvaluator {
/**
* @notice Structure for an exchange token request.
* @dev `path`: Encoded path of tokens to follow in the exchange, including pool identifiers.
* 20 bytes(tokenA) + 4 byte(poolId_A_B) + 20 bytes(tokenB) + ...
* ... + 4 byte(poolId_N-1_N) + 20 bytes(tokenN).
* @dev `extraData`: Additional data specific to a particular protocol, such as the response from a 1Inch Exchange API.
* @dev `amountIn`: The amount of tokenA to spend.
* @dev `minAmountOut`: The minimum amount of tokenN to receive.
* @dev `recipient`: The recipient of tokenN.
*/
struct ExchangeRequest {
bytes path;
bytes extraData;
uint256 amountIn;
uint256 minAmountOut;
address recipient;
}
/**
* @notice Constructs an exchange token request.
* @param _operator Address which initiated the request
* @param _request The [`ExchangeRequest`](#exchangerequest) struct containing exchange token details.
* @return cmds_ An array of [`Command`](../../Command.sol/struct.Command.html) to execute the request.
*/
function evaluate(
address _operator,
ExchangeRequest calldata _request
) external view returns (Command[] memory cmds_);
}
contracts/interfaces/compiler/adapters/IIncreasePositionEvaluator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Asset} from "contracts/libraries/AssetLibrary.sol";
import {Command} from "../Command.sol";
import {PositionDescriptor} from "./PositionDescriptor.sol";
interface IIncreasePositionEvaluator {
/**
* @notice Structure for an increase position request.
* @dev `descriptor`: The [`PositionDescriptor`](/interfaces/compiler/adapters/PositionDescriptor.sol/struct.PositionDescriptor.html)
* struct.
* @dev `input`: An array of [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) representing the token-amounts that will be added to the position.
* @dev `minLiquidityOut`: An abstract amount that can be interpreted differently in different protocols (e.g., minimum amount of LP tokens to receive).
*/
struct IncreasePositionRequest {
PositionDescriptor descriptor;
Asset[] input;
uint256 minLiquidityOut;
}
/**
* @notice Evaluate a increase position request.
* @param _operator Address which initiated the request
* @param _request The [`IncreasePositionRequest`](#increasepositionrequest) struct containing increase position details.
* @return cmds_ An array of [`Command`](../../Command.sol/struct.Command.html) to execute the request.
*/
function evaluate(
address _operator,
IncreasePositionRequest calldata _request
) external returns (Command[] memory cmds_);
}
contracts/interfaces/compiler/adapters/PositionDescriptor.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
// TODO CRYPTO-145: Possibly move into appropriate interface?
/**
* @notice Used to determine the required position for an operation.
* @dev `poolId`: An identifier that is unique within a single protocol.
* @dev `extraData`: Additional data used to specify the position, for example
* this is used in OneInchV5Evaluator to pass swap tx generated via 1inch API.
*/
struct PositionDescriptor {
uint256 poolId;
bytes extraData;
}
contracts/interfaces/compliance/Asset.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {AssetLibrary} from "contracts/libraries/AssetLibrary.sol";
/**
* @title Asset
* @dev Represents an asset with its token address and the amount.
* @param token The address of the asset's token.
* @param amount The amount of the asset.
*/
struct Asset {
address token;
uint256 amount;
}
using AssetLibrary for Asset global;
contracts/interfaces/compliance/IWhitelistingControllerAgreement.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
/**
* @title IWhitelistingControllerAgreement
* @notice Interface for managing whitelisting of tokens and operators for Agreements.
*/
interface IWhitelistingControllerAgreement {
/**
* @notice Emitted when a new token is added for a specific tenant.
* @param tenant The address of the tenant to whom the token is added.
* @param token The address of the token that has been added.
*/
event TokenAdded(address tenant, address token);
/**
* @notice Emitted when a new operator is added for a specific tenant.
* @param tenant The address of the tenant to whom the operator is added.
* @param operator The address of the operator that has been added.
*/
event OperatorAdded(address tenant, address operator);
/**
* @notice Adds a list of tokens to the specified tenant.
* @param tenant The address of the tenant to which the tokens will be added.
* @param tokens An array of addresses representing the tokens to be added.
* @dev This function can be used to update the list of supported tokens for a given tenant.
*/
function addTokens(address tenant, address[] calldata tokens) external;
/**
* @notice Adds a list of operators to the specified tenant.
* @param tenant The address of the tenant to which the operators will be added.
* @param operators An array of addresses representing the operators to be added.
* @dev This function updates the list of authorized operators for a given tenant.
*/
function addOperators(address tenant, address[] calldata operators) external;
/**
* @notice Returns the address of the agreement factory contract.
* @return The address of the agreement factory.
* @dev The agreement factory is used to create and manage agreements.
*/
function agreementFactory() external view returns (address);
/**
* @notice Returns the address of the agreement V2 factory contract.
* @return The address of the agreement V2 factory.
* @dev The agreement V2 factory is used to create and manage agreements V2.
*/
function agreementV2Factory() external view returns (address);
/**
* @notice Checks if a specific token is supported for a given tenant.
* @param tenant The address of the tenant whose supported tokens are being queried.
* @param token The address of the token to check for support.
* @return A boolean indicating whether the token is supported by the tenant.
* @dev This function will return `true` if the token is supported, and `false` otherwise.
*/
function getTokenSupport(address tenant, address token) external view returns (bool);
/**
* @notice Retrieves a list of tokens supported by a specific tenant.
* @param tenant The address of the tenant whose supported tokens are being queried.
* @return An array of token addresses supported by the specified tenant.
* @dev This function returns an array containing the addresses of tokens that the tenant supports.
* It is a view function and does not modify the contract state.
*/
function getTokens(address tenant) external view returns (address[] memory);
/**
* @notice Checks if a specific operator is supported by a given tenant.
* @param tenant The address of the tenant whose supported operators are being queried.
* @param operator The address of the operator to check for support.
* @return A boolean value indicating whether the operator is supported by the tenant.
* @dev This function returns `true` if the operator is supported by the specified tenant, and `false` otherwise.
* It is a view function and does not modify the contract state.
*/
function getOperatorSupport(address tenant, address operator) external view returns (bool);
/**
* @notice Retrieves the list of operators associated with a specific tenant.
* @param tenant The address of the tenant whose operators are being queried.
* @return A dynamically-sized array of addresses representing the operators associated with the tenant.
* @dev This function is a view function and does not modify the contract state.
*/
function getOperators(address tenant) external view returns (address[] memory);
}
contracts/interfaces/dispatcher/Envelope.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Script} from "contracts/interfaces/compiler/Script.sol";
import {EnvelopeRunner} from "contracts/dispatcher/libraries/EnvelopeRunner.sol";
/**
* @title Route
* @notice Part of the [envelope](/interfaces/dispatcher/Envelope.sol/struct.Envelope.html)
* @notice At **routing** level we define `protocol` name where **content**
* should be executed as well as through which `protocol` **content** should
* be delivered to the target ledger if chain did not matched.
* @dev The `protocol` through which **content** should be delivered.
* @dev The `destination` chain of the **content**.
*/
struct Route {
string protocol;
string destination;
}
/**
* @title Envelope
* @notice Part of the [syntax tree](/interfaces/dispatcher/index.html#syntax-tree-for-allocation--liquidation)
* @notice Along with **routing** this struct holds **content** containing
* [scripts](/interfaces/compiler/Script.sol/struct.Script.html)
* with actual business logic.
* @dev The [route](/interfaces/dispatcher/Envelope.sol/struct.Route.html) of the **content**
* @dev The `content` field holds an array of [`Scripts`](/interfaces/compiler/Script.sol/struct.Script.html)
* that should be executed at the `route.destination`.
*/
struct Envelope {
Route route;
Script[] content;
}
using EnvelopeRunner for Envelope global;
/**
* @dev Error indicating that cross-chain actions are forbidden.
*/
error CrossChainActionIsForbidden();
contracts/interfaces/dispatcher/IDispatcher.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Asset} from "contracts/libraries/AssetLibrary.sol";
import {IERC165Extended} from "../base/IERC165Extended.sol";
// EIP-165 id of the currently-deployed Dispatcher. Dependents validate this id so they accept the
// on-chain Dispatcher before it is upgraded.
bytes4 constant LEGACY_DISPATCHER_INTERFACE_ID = 0x130927ef;
/**
* @title Dispatcher
* @notice The facade for communication between margin engine backend and margin engine smart contracts module.
* @notice This contract is responsible for handling [account registration](#registermarginaccount), [leverage allocation](#submitplan), [account close](#tryclosemarginaccount) and [account liquidation](#tryclosemarginaccount).
*/
interface IDispatcher is IERC165Extended {
/**
* @notice Error thrown when account closure fails due to outstanding debt
* @param account The account address
* @param agreement The agreement address
*/
error DebtNotRepaid(address account, address agreement);
/**
* @notice Error thrown when dispatcher has insufficient swept leverage to repay account debt.
* @param account The account address.
* @param agreement The agreement address.
* @param required The total repayment amount required, including pending interest.
* @param available The leverage balance swept to dispatcher and available for repayment.
*/
error InsufficientLeverageForRepayment(
address account,
address agreement,
uint256 required,
uint256 available
);
/**
* @notice Error thrown when a non-zero protocol fee is charged but no treasury is configured.
* @param compliance The compliance contract whose treasury is unset.
*/
error TreasuryNotSet(address compliance);
/**
* @notice The leverage amount cannot be recorded without truncation.
* @dev `account`: The account being allocated.
* @dev `amount`: The leverage amount registered for the account.
* @dev `limit`: The largest amount an Agreement can record.
*/
error LeverageAmountTooLarge(address account, uint256 amount, uint256 limit);
/**
* @notice Registers a new margin account and transfers collateral from the caller to this account.
* @param agreement The address of the agreement associated with the margin account.
* @param collateral An array of [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) representing the collateral to be transferred to the new margin account.
* @param leverage An [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) representing the leverage associated with the margin account.
* @return account The address of the newly registered margin account.
* @dev The function will revert if any of the following conditions are not met:
* - leverage or any collateral tokens amount is zero
* - The leverage token is not registered in agreement or not approved for transfer to this contract.
* - The collateral tokens are not registered in agreement or not approved for transfer to this contract.
*
* Emits:
* - `AccountBorrowed` from the [AccountFactory](../interfaces/marginAccount/IAccountFactory.sol) interface.
* - `AccountDeployed` from the [AccountFactory](../interfaces/marginAccount/IAccountFactory.sol) interface if the object pool is empty.
*
* The newly registered margin account will also emit `AccountRegistered` as defined in the [Account](../interfaces/marginAccount/IAccount.sol) interface.
*/
function registerAccount(
address agreement,
Asset[] calldata collateral,
Asset calldata leverage
) external returns (address account);
/**
* @notice Borrows leverage from the agreement registered in the margin account and opens it.
* @param account The registered margin account to allocate leverage for.
*/
function allocateAccount(address payable account) external;
/**
* @notice Closes margin account by sweeping specified tokens, repaying debt and accrued
* interest, transferring the protocol fee to the treasury and returning leftovers to the owner.
* @dev The protocol fee is computed off-chain and supplied by the caller. It is denominated in
* the leverage token and is included in the funds the account must hold to be closeable.
* @param account The margin account to close.
* @param tokens The list of ERC20 tokens expected to be swept from the margin account.
* @param protocolFee The protocol fee (in the leverage token) to transfer to the treasury.
*/
function closeAccount(
address payable account,
address[] calldata tokens,
uint256 protocolFee
) external;
/**
* @notice Cancels a registered account that was never allocated and returns its collateral.
* @dev Only callable by an address with the
* [ARKIS_RISK_OPERATOR_ROLE](#arkis_risk_operator_role).
* The account must be in the REGISTERED state and carries no debt so the listed balances are
* returned to its owner and the account goes back to the factory.
* @param account The account to cancel.
* @param tokens The list of token balances to return to the owner.
*/
function cancelAccount(address payable account, address[] calldata tokens) external;
/**
* @notice Supplies registered margin account with leverage.
* @dev Will revert if either account already opened, [invalid leverage token supplied](/interfaces/dispatcher/IDispatcher.sol/interface.IDispatcher.html#invalidleveragesupplied) or too much supplied
* @param leverage Full or partial amount of leverage to supply.
*/
function supplyAccount(address payable account, Asset calldata leverage) external;
/**
* @notice Returns the role identifier for the Arkis Risk Operator.
* @dev This role manages permissions related to Arkis Risk Operator's functions.
* It allows the address holding this role to:
* - Control the state of agreements and margin accounts.
* - Trigger automatic and manual liquidations initiated by the Arkis Risk Operator.
* - Respond to collected approvals according to predefined policies.
* @return A bytes32 value representing the ARKIS_RISK_OPERATOR_ROLE.
*/
/* solhint-disable-next-line func-name-mixedcase */
function ARKIS_RISK_OPERATOR_ROLE() external view returns (bytes32);
/**
* @notice Returns the role identifier for the Margin Account Supplier.
* @dev This role is used to manage permissions to supply Margin Accounts, in Dispatcher Module in this context.
* @return A bytes32 value representing the MARGIN_ACCOUNT_SUPPLIER_ROLE.
*/
/* solhint-disable-next-line func-name-mixedcase */
function MARGIN_ACCOUNT_SUPPLIER_ROLE() external view returns (bytes32);
}
contracts/interfaces/dispatcher/Package.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {PackageRunner} from "contracts/dispatcher/libraries/PackageRunner.sol";
import {Envelope} from "./Envelope.sol";
/**
* @title Package
* @notice Part of the [syntax tree](/interfaces/dispatcher/index.html#syntax-tree-for-allocation--liquidation)
* @notice **Automation** part of the syntax tree which defines an `action` with attached to it callback `onComplete`.
* The callback will only be run if action succeeded.
* @dev The `action` field represents the primary action in the [`Envelope`](../Envelope.sol/struct.Envelope.html) struct to be executed.
* @dev The `onComplete` array is composed of [`Envelope`](../Envelope.sol/struct.Envelope.html) structs that will be executed after the primary action completes.
*/
struct Package {
Envelope action;
Envelope[] onComplete;
}
using PackageRunner for Package global;
contracts/interfaces/liquidator/ILiquidator.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {IERC165Extended} from "../base/IERC165Extended.sol";
import {Package} from "../dispatcher/Package.sol";
interface ILiquidator is IERC165Extended {
/**
* @notice Error thrown when account liquidation fails due to outstanding debt
* @param account The account address
* @param agreement The agreement address
*/
error DebtNotRepaid(address account, address agreement);
/**
* @notice Switches margin account to the `suspended` state and
* tries to execute provided plan's action on the account. Can be called
* multiple times if the account's closing was not successful
* @dev Will not revert if action execution on margin account failed
* therefore all the changes from successful scripts will be applied
* after transaction. Account will remain in the suspended state and
* will wait till successful closing.
* @param liquidationPlan `action` will be executed on the account and
* `onComplete` callback will be run on this contract (if `action` succeeded).
*/
function liquidateAccount(
address payable account,
Package calldata liquidationPlan
) external returns (bool success);
/**
* @notice Returns the role identifier for the Arkis Liquidation Operator.
* @dev This role manages permissions related to Arkis Liquidation's functions.
* It allows the address holding this role to:
* - Liquidate unhealthy margin accounts
* @return A bytes32 value representing the ARKIS_LIQUIDATION_OPERATOR_ROLE.
*/
/* solhint-disable-next-line func-name-mixedcase */
function ARKIS_LIQUIDATION_OPERATOR_ROLE() external view returns (bytes32);
}
contracts/interfaces/marginAccount/IAccount.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {IInitializable} from "contracts/interfaces/common/IInitializable.sol";
import {IAccountStateMachine} from "contracts/interfaces/marginAccount/IAccountStateMachine.sol";
import {State} from "contracts/base/StateMachine.sol";
import {Asset} from "contracts/libraries/AssetLibrary.sol";
import {Command} from "../compiler/Command.sol";
import {Script} from "../compiler/Script.sol";
// EIP-165 id of the currently-deployed Account. The on-chain AccountFactory still validates this id so the
// current Account advertises it to pass the beacon upgrade.
bytes4 constant LEGACY_ACCOUNT_INTERFACE_ID = 0xc3c54689;
interface IAccount is IInitializable, IAccountStateMachine {
event AccountRegistered(address owner, address agreement, Asset[] collateral, Asset leverage);
event AccountOpened(address owner);
event AccountSuspended(address owner);
event AccountClosed(address previousOwner);
/**
* @notice Thrown when a function is called more than once within the same block.
* @dev This error is used by the `blockGuard` modifier to prevent repeated transactions within a single block,
* mitigating the risks of double sandwiching attacks, where multiple front-running and back-running attacks
* are performed in the same block to manipulate prices and extract profits.
*/
error ReentrantTransactionInSameBlock();
/**
* @notice Receive Ether and log the transaction.
* @dev This function is called when the margin account receives Ether without a specific function call.
*/
receive() external payable;
/**
* @notice Registers a margin account, transitioning it to the registered state.
* @param user The address that will be assigned as the owner of the margin account.
* @param agreement The address of the agreement associated with the margin account.
* @param collateral An array of [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) representing the collateral that must be transferred to the margin account before this function is called.
* @param requestedLeverage An [`Asset`](/interfaces/compliance/Asset.sol/struct.Asset.html) representing the leverage to be supplied to the margin account to transition its state to "opened."
* @dev The function will revert if:
* - The assets transferred before the call are insufficient.
* - The margin account is in an invalid state.
*
* Emits:
* - `AccountRegistered` event indicating the margin account has been successfully registered.
*/
function register(
address user,
address agreement,
Asset[] calldata collateral,
Asset calldata requestedLeverage
) external;
/**
* @notice This method opens margin account by receiving requested leverage.
* @dev Reverts if account is in an invalid state or sender is not a dispatcher.
*/
function supply() external;
/**
* @notice Closes margin account by sweeping specified token balances to recipient.
* @dev Performs OPENED -> SUSPENDED -> CLOSED state transition.
* @param tokens The list of token balances to sweep from the account.
* @param recipient The recipient of swept token balances.
*/
function close(address[] calldata tokens, address recipient) external;
/**
* @notice Cancels a registered account that was never allocated, returning its collateral.
* @dev Performs REGISTERED -> CLOSED state transition. Registration takes no debt so the
* balances go straight to the owner. Without this an abandoned registration is stranded.
* @param tokens The list of token balances to return to the owner.
*/
function cancel(address[] calldata tokens) external;
/**
* @notice Immediately switches the account to the suspended state and
* tries to execute provided scripts
* @dev Reverts if either script's compilation failed in [compiler](/interfaces/compiler/index.html)
* or account's state cannot be switched to the suspended state
* @param liquidationStrategy An array of [`Script`](/interfaces/compiler/Script.sol/struct.Script.html) representing the strategy to liquidate the account.
* If all scripts are executed successfully,
* @return success Whether the account was switched to the closed state
*/
function liquidate(Script[] calldata liquidationStrategy) external returns (bool success);
function withdraw(address token, address recipient, uint256 amount) external;
/**
* @notice Allows margin account's owner to execute any low level call
* @dev Reverts if either validation failed, call failed or account
* is in an invalid state
* @param cmd Parameters of the call: target, value and payload.
* All the parameters will be validated in validation hub before execution.
* All the approvals will performed automatically, owner does not need to
* do it manually
*/
function execute(Command calldata cmd) external;
/**
* @notice Leverage asset allocated (or being allocated) to the account
*/
function leverage() external view returns (address, uint256);
/**
* @return currentState In which state the state machine is running now
* @return switchTimestamp Time, when state was switched to the underlying state
*/
function stateInfo() external view returns (State currentState, uint256 switchTimestamp);
function allocationInfo()
external
view
returns (
State currentState,
uint256 stateSwitchTimestamp,
address owner,
address leverageToken,
uint256 leverageAmount
);
/**
* @notice Returns the address of the current agreement contract.
* @return The address of the agreement contract.
* @dev This function provides the address of the contract responsible for managing agreements. It is useful for interacting with or querying details related to the agreement.
*/
function agreement() external view returns (address);
/**
* @notice Returns the owner of the margin account.
* @return The address of the the margin account owner.
*/
function owner() external view returns (address);
}
contracts/interfaces/marginAccount/IAccountStateMachine.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
interface IAccountStateMachine {
function registerAccount(bytes calldata _args) external;
function openAccount(bytes calldata) external;
function suspendAccount(bytes calldata) external;
function closeAccount(bytes calldata) external;
}
contracts/libraries/Address.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
library Address {
address internal constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function set(bytes32 _slot, address _value) internal {
assembly {
sstore(_slot, _value)
}
}
function get(bytes32 _slot) internal view returns (address result_) {
assembly {
result_ := sload(_slot)
}
}
function isEth(address _token) internal pure returns (bool) {
return _token == ETH || _token == address(0);
}
function sort(address _a, address _b) internal pure returns (address, address) {
return _a < _b ? (_a, _b) : (_b, _a);
}
function sort(address[4] memory _array) internal pure returns (address[4] memory _sorted) {
// Sorting network for the array of length 4
(_sorted[0], _sorted[1]) = sort(_array[0], _array[1]);
(_sorted[2], _sorted[3]) = sort(_array[2], _array[3]);
(_sorted[0], _sorted[2]) = sort(_sorted[0], _sorted[2]);
(_sorted[1], _sorted[3]) = sort(_sorted[1], _sorted[3]);
(_sorted[1], _sorted[2]) = sort(_sorted[1], _sorted[2]);
}
}
contracts/libraries/AssetLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol";
import {AmountMustNotBeZero} from "contracts/interfaces/base/CommonErrors.sol";
import {Asset} from "contracts/interfaces/compliance/Asset.sol";
import {Address} from "./Address.sol";
library AssetLibrary {
using SafeTransferLib for address;
using Address for address;
error NotEnoughReceived(address token, uint256 expected, uint256 received);
function forward(Asset calldata self, address _to) internal {
if (self.amount == 0) revert AmountMustNotBeZero(self.token);
if (self.token.isEth()) _to.safeTransferETH(self.amount);
else self.token.safeTransferFrom(msg.sender, _to, self.amount);
}
function approve(Asset calldata self, address to) internal {
self.token.safeApprove(to, self.amount);
}
function receiveFrom(Asset storage self, address from) internal {
self.token.safeTransferFrom(from, address(this), self.amount);
}
function receiveFrom(Asset calldata self, address from) internal {
self.token.safeTransferFrom(from, address(this), self.amount);
}
function enforceReceived(Asset calldata self) internal view {
if (self.amount == 0) revert AmountMustNotBeZero(self.token);
uint256 balance = self.token.isEth()
? address(this).balance
: self.token.balanceOf(address(this));
if (balance < self.amount) revert NotEnoughReceived(self.token, self.amount, balance);
}
}
contracts/libraries/CalldataLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
library CalldataLibrary {
uint256 private constant WORD_LENGTH = 32;
function appendWord(
bytes memory _payload,
address _word
) internal pure returns (bytes memory result_) {
result_ = bytes.concat(_payload, bytes12(0), bytes20(_word));
}
function extractLastWordAsAddress(bytes calldata _payload) internal pure returns (address) {
uint256 start = _payload.length - WORD_LENGTH;
uint256 end = start + WORD_LENGTH;
bytes32 word = bytes32(_payload[start:end]);
return address(uint160(uint256(word)));
}
}
contracts/libraries/CommandLibrary.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {Command} from "contracts/interfaces/compiler/Command.sol";
import {SafeCall} from "contracts/libraries/SafeCall.sol";
/**
* @notice Utility to convert often-used methods into a Command object
*/
library CommandPresets {
function approve(
address _token,
address _to,
uint256 _amount
) internal pure returns (Command[] memory result_) {
result_ = new Command[](2);
result_[0] = Command(_token, 0, abi.encodeCall(IERC20.approve, (_to, 0)));
result_[1] = Command(_token, 0, abi.encodeCall(IERC20.approve, (_to, _amount)));
}
function transfer(
address _token,
address _to,
uint256 _amount
) internal pure returns (Command memory cmd_) {
cmd_.target = _token;
cmd_.payload = abi.encodeCall(IERC20.transfer, (_to, _amount));
}
}
library CommandExecutor {
using SafeCall for Command[];
function execute(Command[] calldata _cmds) external {
_cmds.safeCallAll();
}
}
library CommandLibrary {
using CommandLibrary for Command[];
function last(Command[] memory _self) internal pure returns (Command memory) {
return _self[_self.length - 1];
}
function asArray(Command memory _self) internal pure returns (Command[] memory result_) {
result_ = new Command[](1);
result_[0] = _self;
}
function append(
Command[] memory _self,
Command[] memory _cmds
) internal pure returns (Command[] memory result_) {
result_ = new Command[](_self.length + _cmds.length);
uint256 i;
for (; i < _self.length; i++) {
result_[i] = _self[i];
}
for (; i < result_.length; i++) {
result_[i] = _cmds[i - _self.length];
}
}
function push(
Command[] memory _self,
Command memory _cmd
) internal pure returns (Command[] memory result_) {
result_ = new Command[](_self.length + 1);
for (uint256 i; i < _self.length; i++) {
result_[i] = _self[i];
}
result_[_self.length] = _cmd;
}
function populateWithApprove(
Command memory _self,
address _token,
uint256 _amount
) internal pure returns (Command[] memory result_) {
if (_amount != 0) {
result_ = CommandPresets.approve(_token, _self.target, _amount).push(_self);
} else {
result_ = _self.asArray();
}
}
}
contracts/libraries/SafeCall.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {Address} from "@openzeppelin/contracts/utils/Address.sol";
import {Command} from "contracts/interfaces/compiler/Command.sol";
/**
* @notice Safe methods performing a low-level calls that revert
* if the call was not successful
*/
library SafeCall {
using Address for address;
function safeCallAll(Command[] memory _cmds) internal {
for (uint256 i; i < _cmds.length; i++) {
safeCall(_cmds[i]);
}
}
function safeCall(Command memory _cmd) internal returns (bytes memory result_) {
result_ = safeCall(_cmd.target, _cmd.value, _cmd.payload);
}
function safeCall(address _target, bytes memory _data) internal returns (bytes memory result_) {
result_ = safeCall(_target, 0, _data);
}
function safeCall(
address _target,
uint256 _value,
bytes memory _data
) internal returns (bytes memory result_) {
result_ = _target.functionCallWithValue(_data, _value);
}
function safeDelegateCall(
address _target,
bytes memory _data
) internal returns (bytes memory result_) {
result_ = _target.functionDelegateCall(_data);
}
}
contracts/marginAccount/base/CommandSafeExecutor.sol
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.22;
import {LibString} from "solady/src/utils/LibString.sol";
import {IERC165Extended, UnsupportedInterface} from "contracts/interfaces/base/IERC165Extended.sol";
import {Command} from "contracts/interfaces/compiler/Command.sol";
import {
IWhitelistingControllerAgreement
} from "contracts/interfaces/compliance/IWhitelistingControllerAgreement.sol";
import {CalldataLibrary} from "contracts/libraries/CalldataLibrary.sol";
import {SafeCall} from "contracts/libraries/SafeCall.sol";
contract CommandSafeExecutor {
using LibString for address;
using CalldataLibrary for bytes;
using SafeCall for Command;
using SafeCall for Command[];
address internal immutable _compliance;
string private constant EMPTY_DATA_SIG_PREFIX = "emptyDataForOperator";
constructor(address compliance_) {
if (
!IERC165Extended(compliance_).supportsInterfaceExtended(
// @dev Validate the stable parent interface, not the full IWhitelistingController, so a
// not-yet-upgraded on-chain compliance still passes during a deferred-cut release.
type(IWhitelistingControllerAgreement).interfaceId
)
) {
revert UnsupportedInterface(compliance_);
}
_compliance = compliance_;
}
function validateAndExecute(Command calldata _cmd) internal {
Command[] memory cmdsToExecute = abi.decode(validate(_cmd), (Command[]));
cmdsToExecute.safeCallAll();
}
function validate(Command calldata _cmd) private returns (bytes memory result_) {
Command memory cmdToValidate = Command({
target: _compliance,
value: _cmd.value,
payload: constructPayloadWithOperator(_cmd)
});
return cmdToValidate.safeCall();
}
function constructPayloadWithOperator(
Command calldata _cmd
) private pure returns (bytes memory) {
address operator = _cmd.target;
bytes memory payload = _cmd.payload.length > 0
? _cmd.payload
: constructPayloadForFallback(operator.toHexString());
return payload.appendWord(operator);
}
function constructPayloadForFallback(
string memory _operator
) private pure returns (bytes memory) {
string memory signature = string.concat(EMPTY_DATA_SIG_PREFIX, _operator, "()");
bytes4 selector = bytes4(keccak256(bytes(signature)));
return abi.encodePacked(selector);
}
}
solady/src/utils/LibBit.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for bit twiddling and boolean operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBit.sol)
/// @author Inspired by (https://graphics.stanford.edu/~seander/bithacks.html)
library LibBit {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BIT TWIDDLING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Find last set.
/// Returns the index of the most significant bit of `x`,
/// counting from the least significant bit position.
/// If `x` is zero, returns 256.
/// Equivalent to `log2(x)`, but without reverting for the zero case.
function fls(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(8, iszero(x))
r := or(r, shl(7, lt(0xffffffffffffffffffffffffffffffff, x)))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
// For the remaining 32 bits, use a De Bruijn lookup.
x := shr(r, x)
x := or(x, shr(1, x))
x := or(x, shr(2, x))
x := or(x, shr(4, x))
x := or(x, shr(8, x))
x := or(x, shr(16, x))
// forgefmt: disable-next-item
r := or(r, byte(shr(251, mul(x, shl(224, 0x07c4acdd))),
0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f))
}
}
/// @dev Count leading zeros.
/// Returns the number of zeros preceding the most significant one bit.
/// If `x` is zero, returns 256.
function clz(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
let t := add(iszero(x), 255)
r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
// For the remaining 32 bits, use a De Bruijn lookup.
x := shr(r, x)
x := or(x, shr(1, x))
x := or(x, shr(2, x))
x := or(x, shr(4, x))
x := or(x, shr(8, x))
x := or(x, shr(16, x))
// forgefmt: disable-next-item
r := sub(t, or(r, byte(shr(251, mul(x, shl(224, 0x07c4acdd))),
0x0009010a0d15021d0b0e10121619031e080c141c0f111807131b17061a05041f)))
}
}
/// @dev Find first set.
/// Returns the index of the least significant bit of `x`,
/// counting from the least significant bit position.
/// If `x` is zero, returns 256.
/// Equivalent to `ctz` (count trailing zeros), which gives
/// the number of zeros following the least significant one bit.
function ffs(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
r := shl(8, iszero(x))
// Isolate the least significant bit.
x := and(x, add(not(x), 1))
r := or(r, shl(7, lt(0xffffffffffffffffffffffffffffffff, x)))
r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x))))
r := or(r, shl(5, lt(0xffffffff, shr(r, x))))
// For the remaining 32 bits, use a De Bruijn lookup.
// forgefmt: disable-next-item
r := or(r, byte(shr(251, mul(shr(r, x), shl(224, 0x077cb531))),
0x00011c021d0e18031e16140f191104081f1b0d17151310071a0c12060b050a09))
}
}
/// @dev Returns the number of set bits in `x`.
function popCount(uint256 x) internal pure returns (uint256 c) {
/// @solidity memory-safe-assembly
assembly {
let max := not(0)
let isMax := eq(x, max)
x := sub(x, and(shr(1, x), div(max, 3)))
x := add(and(x, div(max, 5)), and(shr(2, x), div(max, 5)))
x := and(add(x, shr(4, x)), div(max, 17))
c := or(shl(8, isMax), shr(248, mul(x, div(max, 255))))
}
}
/// @dev Returns whether `x` is a power of 2.
function isPo2(uint256 x) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to `x && !(x & (x - 1))`.
result := iszero(add(and(x, sub(x, 1)), iszero(x)))
}
}
/// @dev Returns `x` reversed at the bit level.
function reverseBits(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
// Computing masks on-the-fly reduces bytecode size by about 500 bytes.
let m := not(0)
r := x
for { let s := 128 } 1 {} {
m := xor(m, shl(s, m))
r := or(and(shr(s, r), m), and(shl(s, r), not(m)))
s := shr(1, s)
if iszero(s) { break }
}
}
}
/// @dev Returns `x` reversed at the byte level.
function reverseBytes(uint256 x) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
// Computing masks on-the-fly reduces bytecode size by about 200 bytes.
let m := not(0)
r := x
for { let s := 128 } 1 {} {
m := xor(m, shl(s, m))
r := or(and(shr(s, r), m), and(shl(s, r), not(m)))
s := shr(1, s)
if eq(s, 4) { break }
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BOOLEAN OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns `x & y`.
function and(bool x, bool y) internal pure returns (bool z) {
/// @solidity memory-safe-assembly
assembly {
z := and(x, y)
}
}
/// @dev Returns `x | y`.
function or(bool x, bool y) internal pure returns (bool z) {
/// @solidity memory-safe-assembly
assembly {
z := or(x, y)
}
}
/// @dev Returns a non-zero number if `b` is true, else 0.
/// If `b` is from plain Solidity, the non-zero number will be 1.
function toUint(bool b) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
z := b
}
}
}
solady/src/utils/LibString.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @notice Library for converting numbers into strings and other string operations.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibString.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibString.sol)
library LibString {
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CUSTOM ERRORS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The `length` of the output is too small to contain all the hex digits.
error HexLengthInsufficient();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* CONSTANTS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev The constant returned when the `search` is not found in the string.
uint256 internal constant NOT_FOUND = type(uint256).max;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* DECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the base 10 decimal representation of `value`.
function toString(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// The maximum value of a uint256 contains 78 digits (1 byte per digit), but
// we allocate 0xa0 bytes to keep the free memory pointer 32-byte word aligned.
// We will need 1 word for the trailing zeros padding, 1 word for the length,
// and 3 words for a maximum of 78 digits.
str := add(mload(0x40), 0x80)
// Update the free memory pointer to allocate.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end of the memory to calculate the length later.
let end := str
let w := not(0) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 1)`.
// Write the character to the pointer.
// The ASCII index of the '0' character is 48.
mstore8(str, add(48, mod(temp, 10)))
// Keep dividing `temp` until zero.
temp := div(temp, 10)
if iszero(temp) { break }
}
let length := sub(end, str)
// Move the pointer 32 bytes leftwards to make room for the length.
str := sub(str, 0x20)
// Store the length.
mstore(str, length)
}
}
/// @dev Returns the base 10 decimal representation of `value`.
function toString(int256 value) internal pure returns (string memory str) {
if (value >= 0) {
return toString(uint256(value));
}
unchecked {
str = toString(uint256(-value));
}
/// @solidity memory-safe-assembly
assembly {
// We still have some spare memory space on the left,
// as we have allocated 3 words (96 bytes) for up to 78 digits.
let length := mload(str) // Load the string length.
mstore(str, 0x2d) // Store the '-' character.
str := sub(str, 1) // Move back the string pointer by a byte.
mstore(str, add(length, 1)) // Update the string length.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* HEXADECIMAL OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `length` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `length * 2 + 2` bytes.
/// Reverts if `length` is too small for the output to contain all the digits.
function toHexString(uint256 value, uint256 length) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value, length);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`,
/// left-padded to an input length of `length` bytes.
/// The output is prefixed with "0x" encoded using 2 hexadecimal digits per byte,
/// giving a total length of `length * 2` bytes.
/// Reverts if `length` is too small for the output to contain all the digits.
function toHexStringNoPrefix(uint256 value, uint256 length)
internal
pure
returns (string memory str)
{
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, `length * 2` bytes
// for the digits, 0x02 bytes for the prefix, and 0x20 bytes for the length.
// We add 0x20 to the total and round down to a multiple of 0x20.
// (0x20 + 0x20 + 0x02 + 0x20) = 0x62.
str := add(mload(0x40), and(add(shl(1, length), 0x42), not(0x1f)))
// Allocate the memory.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end to calculate the length later.
let end := str
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let start := sub(str, add(length, length))
let w := not(1) // Tsk.
let temp := value
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for {} 1 {} {
str := add(str, w) // `sub(str, 2)`.
mstore8(add(str, 1), mload(and(temp, 15)))
mstore8(str, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(xor(str, start)) { break }
}
if temp {
// Store the function selector of `HexLengthInsufficient()`.
mstore(0x00, 0x2194895a)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Compute the string's length.
let strLength := sub(end, str)
// Move the pointer and write the length.
str := sub(str, 0x20)
mstore(str, strLength)
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2 + 2` bytes.
function toHexString(uint256 value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
/// As address are 20 bytes long, the output will left-padded to have
/// a length of `20 * 2` bytes.
function toHexStringNoPrefix(uint256 value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x40 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x40) is 0xa0.
str := add(mload(0x40), 0x80)
// Allocate the memory.
mstore(0x40, add(str, 0x20))
// Zeroize the slot after the string.
mstore(str, 0)
// Cache the end to calculate the length later.
let end := str
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let w := not(1) // Tsk.
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let temp := value } 1 {} {
str := add(str, w) // `sub(str, 2)`.
mstore8(add(str, 1), mload(and(temp, 15)))
mstore8(str, mload(and(shr(4, temp), 15)))
temp := shr(8, temp)
if iszero(temp) { break }
}
// Compute the string's length.
let strLength := sub(end, str)
// Move the pointer and write the length.
str := sub(str, 0x20)
mstore(str, strLength)
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x", encoded using 2 hexadecimal digits per byte,
/// and the alphabets are capitalized conditionally according to
/// https://eips.ethereum.org/EIPS/eip-55
function toHexStringChecksummed(address value) internal pure returns (string memory str) {
str = toHexString(value);
/// @solidity memory-safe-assembly
assembly {
let mask := shl(6, div(not(0), 255)) // `0b010000000100000000 ...`
let o := add(str, 0x22)
let hashed := and(keccak256(o, 40), mul(34, mask)) // `0b10001000 ... `
let t := shl(240, 136) // `0b10001000 << 240`
for { let i := 0 } 1 {} {
mstore(add(i, i), mul(t, byte(i, hashed)))
i := add(i, 1)
if eq(i, 20) { break }
}
mstore(o, xor(mload(o), shr(1, and(mload(0x00), and(mload(o), mask)))))
o := add(o, 0x20)
mstore(o, xor(mload(o), shr(1, and(mload(0x20), and(mload(o), mask)))))
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is prefixed with "0x" and encoded using 2 hexadecimal digits per byte.
function toHexString(address value) internal pure returns (string memory str) {
str = toHexStringNoPrefix(value);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hexadecimal representation of `value`.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(address value) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
str := mload(0x40)
// Allocate the memory.
// We need 0x20 bytes for the trailing zeros padding, 0x20 bytes for the length,
// 0x02 bytes for the prefix, and 0x28 bytes for the digits.
// The next multiple of 0x20 above (0x20 + 0x20 + 0x02 + 0x28) is 0x80.
mstore(0x40, add(str, 0x80))
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
str := add(str, 2)
mstore(str, 40)
let o := add(str, 0x20)
mstore(add(o, 40), 0)
value := shl(96, value)
// We write the string from rightmost digit to leftmost digit.
// The following is essentially a do-while loop that also handles the zero case.
for { let i := 0 } 1 {} {
let p := add(o, add(i, i))
let temp := byte(i, value)
mstore8(add(p, 1), mload(and(temp, 15)))
mstore8(p, mload(shr(4, temp)))
i := add(i, 1)
if eq(i, 20) { break }
}
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexString(bytes memory raw) internal pure returns (string memory str) {
str = toHexStringNoPrefix(raw);
/// @solidity memory-safe-assembly
assembly {
let strLength := add(mload(str), 2) // Compute the length.
mstore(str, 0x3078) // Write the "0x" prefix.
str := sub(str, 2) // Move the pointer.
mstore(str, strLength) // Write the length.
}
}
/// @dev Returns the hex encoded string from the raw bytes.
/// The output is encoded using 2 hexadecimal digits per byte.
function toHexStringNoPrefix(bytes memory raw) internal pure returns (string memory str) {
/// @solidity memory-safe-assembly
assembly {
let length := mload(raw)
str := add(mload(0x40), 2) // Skip 2 bytes for the optional prefix.
mstore(str, add(length, length)) // Store the length of the output.
// Store "0123456789abcdef" in scratch space.
mstore(0x0f, 0x30313233343536373839616263646566)
let o := add(str, 0x20)
let end := add(raw, length)
for {} iszero(eq(raw, end)) {} {
raw := add(raw, 1)
mstore8(add(o, 1), mload(and(mload(raw), 15)))
mstore8(o, mload(and(shr(4, mload(raw)), 15)))
o := add(o, 2)
}
mstore(o, 0) // Zeroize the slot after the string.
mstore(0x40, add(o, 0x20)) // Allocate the memory.
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* RUNE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Returns the number of UTF characters in the string.
function runeCount(string memory s) internal pure returns (uint256 result) {
/// @solidity memory-safe-assembly
assembly {
if mload(s) {
mstore(0x00, div(not(0), 255))
mstore(0x20, 0x0202020202020202020202020202020202020202020202020303030304040506)
let o := add(s, 0x20)
let end := add(o, mload(s))
for { result := 1 } 1 { result := add(result, 1) } {
o := add(o, byte(0, mload(shr(250, mload(o)))))
if iszero(lt(o, end)) { break }
}
}
}
}
/// @dev Returns if this string is a 7-bit ASCII string.
/// (i.e. all characters codes are in [0..127])
function is7BitASCII(string memory s) internal pure returns (bool result) {
/// @solidity memory-safe-assembly
assembly {
let mask := shl(7, div(not(0), 255))
result := 1
let n := mload(s)
if n {
let o := add(s, 0x20)
let end := add(o, n)
let last := mload(end)
mstore(end, 0)
for {} 1 {} {
if and(mask, mload(o)) {
result := 0
break
}
o := add(o, 0x20)
if iszero(lt(o, end)) { break }
}
mstore(end, last)
}
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* BYTE STRING OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
// For performance and bytecode compactness, all indices of the following operations
// are byte (ASCII) offsets, not UTF character offsets.
/// @dev Returns `subject` all occurrences of `search` replaced with `replacement`.
function replace(string memory subject, string memory search, string memory replacement)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
let replacementLength := mload(replacement)
subject := add(subject, 0x20)
search := add(search, 0x20)
replacement := add(replacement, 0x20)
result := add(mload(0x40), 0x20)
let subjectEnd := add(subject, subjectLength)
if iszero(gt(searchLength, subjectLength)) {
let subjectSearchEnd := add(sub(subjectEnd, searchLength), 1)
let h := 0
if iszero(lt(searchLength, 0x20)) { h := keccak256(search, searchLength) }
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(search)
for {} 1 {} {
let t := mload(subject)
// Whether the first `searchLength % 32` bytes of
// `subject` and `search` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(subject, searchLength), h)) {
mstore(result, t)
result := add(result, 1)
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
// Copy the `replacement` one word at a time.
for { let o := 0 } 1 {} {
mstore(add(result, o), mload(add(replacement, o)))
o := add(o, 0x20)
if iszero(lt(o, replacementLength)) { break }
}
result := add(result, replacementLength)
subject := add(subject, searchLength)
if searchLength {
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
mstore(result, t)
result := add(result, 1)
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
}
}
let resultRemainder := result
result := add(mload(0x40), 0x20)
let k := add(sub(resultRemainder, result), sub(subjectEnd, subject))
// Copy the rest of the string one word at a time.
for {} lt(subject, subjectEnd) {} {
mstore(resultRemainder, mload(subject))
resultRemainder := add(resultRemainder, 0x20)
subject := add(subject, 0x20)
}
result := sub(result, 0x20)
let last := add(add(result, 0x20), k) // Zeroize the slot after the string.
mstore(last, 0)
mstore(0x40, add(last, 0x20)) // Allocate the memory.
mstore(result, k) // Store the length.
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from left to right, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function indexOf(string memory subject, string memory search, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for { let subjectLength := mload(subject) } 1 {} {
if iszero(mload(search)) {
if iszero(gt(from, subjectLength)) {
result := from
break
}
result := subjectLength
break
}
let searchLength := mload(search)
let subjectStart := add(subject, 0x20)
result := not(0) // Initialize to `NOT_FOUND`.
subject := add(subjectStart, from)
let end := add(sub(add(subjectStart, subjectLength), searchLength), 1)
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(add(search, 0x20))
if iszero(and(lt(subject, end), lt(from, subjectLength))) { break }
if iszero(lt(searchLength, 0x20)) {
for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
if eq(keccak256(subject, searchLength), h) {
result := sub(subject, subjectStart)
break
}
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
for {} 1 {} {
if iszero(shr(m, xor(mload(subject), s))) {
result := sub(subject, subjectStart)
break
}
subject := add(subject, 1)
if iszero(lt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from left to right.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function indexOf(string memory subject, string memory search)
internal
pure
returns (uint256 result)
{
result = indexOf(subject, search, 0);
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from right to left, starting from `from`.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function lastIndexOf(string memory subject, string memory search, uint256 from)
internal
pure
returns (uint256 result)
{
/// @solidity memory-safe-assembly
assembly {
for {} 1 {} {
result := not(0) // Initialize to `NOT_FOUND`.
let searchLength := mload(search)
if gt(searchLength, mload(subject)) { break }
let w := result
let fromMax := sub(mload(subject), searchLength)
if iszero(gt(fromMax, from)) { from := fromMax }
let end := add(add(subject, 0x20), w)
subject := add(add(subject, 0x20), from)
if iszero(gt(subject, end)) { break }
// As this function is not too often used,
// we shall simply use keccak256 for smaller bytecode size.
for { let h := keccak256(add(search, 0x20), searchLength) } 1 {} {
if eq(keccak256(subject, searchLength), h) {
result := sub(subject, add(end, 1))
break
}
subject := add(subject, w) // `sub(subject, 1)`.
if iszero(gt(subject, end)) { break }
}
break
}
}
}
/// @dev Returns the byte index of the first location of `search` in `subject`,
/// searching from right to left.
/// Returns `NOT_FOUND` (i.e. `type(uint256).max`) if the `search` is not found.
function lastIndexOf(string memory subject, string memory search)
internal
pure
returns (uint256 result)
{
result = lastIndexOf(subject, search, uint256(int256(-1)));
}
/// @dev Returns whether `subject` starts with `search`.
function startsWith(string memory subject, string memory search)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLength := mload(search)
// Just using keccak256 directly is actually cheaper.
// forgefmt: disable-next-item
result := and(
iszero(gt(searchLength, mload(subject))),
eq(
keccak256(add(subject, 0x20), searchLength),
keccak256(add(search, 0x20), searchLength)
)
)
}
}
/// @dev Returns whether `subject` ends with `search`.
function endsWith(string memory subject, string memory search)
internal
pure
returns (bool result)
{
/// @solidity memory-safe-assembly
assembly {
let searchLength := mload(search)
let subjectLength := mload(subject)
// Whether `search` is not longer than `subject`.
let withinRange := iszero(gt(searchLength, subjectLength))
// Just using keccak256 directly is actually cheaper.
// forgefmt: disable-next-item
result := and(
withinRange,
eq(
keccak256(
// `subject + 0x20 + max(subjectLength - searchLength, 0)`.
add(add(subject, 0x20), mul(withinRange, sub(subjectLength, searchLength))),
searchLength
),
keccak256(add(search, 0x20), searchLength)
)
)
}
}
/// @dev Returns `subject` repeated `times`.
function repeat(string memory subject, uint256 times)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
if iszero(or(iszero(times), iszero(subjectLength))) {
subject := add(subject, 0x20)
result := mload(0x40)
let output := add(result, 0x20)
for {} 1 {} {
// Copy the `subject` one word at a time.
for { let o := 0 } 1 {} {
mstore(add(output, o), mload(add(subject, o)))
o := add(o, 0x20)
if iszero(lt(o, subjectLength)) { break }
}
output := add(output, subjectLength)
times := sub(times, 1)
if iszero(times) { break }
}
mstore(output, 0) // Zeroize the slot after the string.
let resultLength := sub(output, add(result, 0x20))
mstore(result, resultLength) // Store the length.
// Allocate the memory.
mstore(0x40, add(result, add(resultLength, 0x20)))
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to `end` (exclusive).
/// `start` and `end` are byte offsets.
function slice(string memory subject, uint256 start, uint256 end)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
if iszero(gt(subjectLength, end)) { end := subjectLength }
if iszero(gt(subjectLength, start)) { start := subjectLength }
if lt(start, end) {
result := mload(0x40)
let resultLength := sub(end, start)
mstore(result, resultLength)
subject := add(subject, start)
let w := not(0x1f)
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(resultLength, 0x1f), w) } 1 {} {
mstore(add(result, o), mload(add(subject, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Zeroize the slot after the string.
mstore(add(add(result, 0x20), resultLength), 0)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, add(result, and(add(resultLength, 0x3f), w)))
}
}
}
/// @dev Returns a copy of `subject` sliced from `start` to the end of the string.
/// `start` is a byte offset.
function slice(string memory subject, uint256 start)
internal
pure
returns (string memory result)
{
result = slice(subject, start, uint256(int256(-1)));
}
/// @dev Returns all the indices of `search` in `subject`.
/// The indices are byte offsets.
function indicesOf(string memory subject, string memory search)
internal
pure
returns (uint256[] memory result)
{
/// @solidity memory-safe-assembly
assembly {
let subjectLength := mload(subject)
let searchLength := mload(search)
if iszero(gt(searchLength, subjectLength)) {
subject := add(subject, 0x20)
search := add(search, 0x20)
result := add(mload(0x40), 0x20)
let subjectStart := subject
let subjectSearchEnd := add(sub(add(subject, subjectLength), searchLength), 1)
let h := 0
if iszero(lt(searchLength, 0x20)) { h := keccak256(search, searchLength) }
let m := shl(3, sub(0x20, and(searchLength, 0x1f)))
let s := mload(search)
for {} 1 {} {
let t := mload(subject)
// Whether the first `searchLength % 32` bytes of
// `subject` and `search` matches.
if iszero(shr(m, xor(t, s))) {
if h {
if iszero(eq(keccak256(subject, searchLength), h)) {
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
// Append to `result`.
mstore(result, sub(subject, subjectStart))
result := add(result, 0x20)
// Advance `subject` by `searchLength`.
subject := add(subject, searchLength)
if searchLength {
if iszero(lt(subject, subjectSearchEnd)) { break }
continue
}
}
subject := add(subject, 1)
if iszero(lt(subject, subjectSearchEnd)) { break }
}
let resultEnd := result
// Assign `result` to the free memory pointer.
result := mload(0x40)
// Store the length of `result`.
mstore(result, shr(5, sub(resultEnd, add(result, 0x20))))
// Allocate memory for result.
// We allocate one more word, so this array can be recycled for {split}.
mstore(0x40, add(resultEnd, 0x20))
}
}
}
/// @dev Returns a arrays of strings based on the `delimiter` inside of the `subject` string.
function split(string memory subject, string memory delimiter)
internal
pure
returns (string[] memory result)
{
uint256[] memory indices = indicesOf(subject, delimiter);
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
let indexPtr := add(indices, 0x20)
let indicesEnd := add(indexPtr, shl(5, add(mload(indices), 1)))
mstore(add(indicesEnd, w), mload(subject))
mstore(indices, add(mload(indices), 1))
let prevIndex := 0
for {} 1 {} {
let index := mload(indexPtr)
mstore(indexPtr, 0x60)
if iszero(eq(index, prevIndex)) {
let element := mload(0x40)
let elementLength := sub(index, prevIndex)
mstore(element, elementLength)
// Copy the `subject` one word at a time, backwards.
for { let o := and(add(elementLength, 0x1f), w) } 1 {} {
mstore(add(element, o), mload(add(add(subject, prevIndex), o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
// Zeroize the slot after the string.
mstore(add(add(element, 0x20), elementLength), 0)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, add(element, and(add(elementLength, 0x3f), w)))
// Store the `element` into the array.
mstore(indexPtr, element)
}
prevIndex := add(index, mload(delimiter))
indexPtr := add(indexPtr, 0x20)
if iszero(lt(indexPtr, indicesEnd)) { break }
}
result := indices
if iszero(mload(delimiter)) {
result := add(indices, 0x20)
mstore(result, sub(mload(indices), 2))
}
}
}
/// @dev Returns a concatenated string of `a` and `b`.
/// Cheaper than `string.concat()` and does not de-align the free memory pointer.
function concat(string memory a, string memory b)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let w := not(0x1f)
result := mload(0x40)
let aLength := mload(a)
// Copy `a` one word at a time, backwards.
for { let o := and(add(mload(a), 0x20), w) } 1 {} {
mstore(add(result, o), mload(add(a, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let bLength := mload(b)
let output := add(result, mload(a))
// Copy `b` one word at a time, backwards.
for { let o := and(add(bLength, 0x20), w) } 1 {} {
mstore(add(output, o), mload(add(b, o)))
o := add(o, w) // `sub(o, 0x20)`.
if iszero(o) { break }
}
let totalLength := add(aLength, bLength)
let last := add(add(result, 0x20), totalLength)
// Zeroize the slot after the string.
mstore(last, 0)
// Stores the length.
mstore(result, totalLength)
// Allocate memory for the length and the bytes,
// rounded up to a multiple of 32.
mstore(0x40, and(add(last, 0x1f), w))
}
}
/// @dev Returns a copy of the string in either lowercase or UPPERCASE.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function toCase(string memory subject, bool toUpper)
internal
pure
returns (string memory result)
{
/// @solidity memory-safe-assembly
assembly {
let length := mload(subject)
if length {
result := add(mload(0x40), 0x20)
subject := add(subject, 1)
let flags := shl(add(70, shl(5, toUpper)), 0x3ffffff)
let w := not(0)
for { let o := length } 1 {} {
o := add(o, w)
let b := and(0xff, mload(add(subject, o)))
mstore8(add(result, o), xor(b, and(shr(b, flags), 0x20)))
if iszero(o) { break }
}
result := mload(0x40)
mstore(result, length) // Store the length.
let last := add(add(result, 0x20), length)
mstore(last, 0) // Zeroize the slot after the string.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
}
/// @dev Returns a lowercased copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function lower(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, false);
}
/// @dev Returns an UPPERCASED copy of the string.
/// WARNING! This function is only compatible with 7-bit ASCII strings.
function upper(string memory subject) internal pure returns (string memory result) {
result = toCase(subject, true);
}
/// @dev Escapes the string to be used within HTML tags.
function escapeHTML(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
for {
let end := add(s, mload(s))
result := add(mload(0x40), 0x20)
// Store the bytes of the packed offsets and strides into the scratch space.
// `packed = (stride << 5) | offset`. Max offset is 20. Max stride is 6.
mstore(0x1f, 0x900094)
mstore(0x08, 0xc0000000a6ab)
// Store ""&'<>" into the scratch space.
mstore(0x00, shl(64, 0x2671756f743b26616d703b262333393b266c743b2667743b))
} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
// Not in `["\"","'","&","<",">"]`.
if iszero(and(shl(c, 1), 0x500000c400000000)) {
mstore8(result, c)
result := add(result, 1)
continue
}
let t := shr(248, mload(c))
mstore(result, mload(and(t, 0x1f)))
result := add(result, shr(5, t))
}
let last := result
mstore(last, 0) // Zeroize the slot after the string.
result := mload(0x40)
mstore(result, sub(last, add(result, 0x20))) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
/// @dev Escapes the string to be used within double-quotes in a JSON.
function escapeJSON(string memory s) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
for {
let end := add(s, mload(s))
result := add(mload(0x40), 0x20)
// Store "\\u0000" in scratch space.
// Store "0123456789abcdef" in scratch space.
// Also, store `{0x08:"b", 0x09:"t", 0x0a:"n", 0x0c:"f", 0x0d:"r"}`.
// into the scratch space.
mstore(0x15, 0x5c75303030303031323334353637383961626364656662746e006672)
// Bitmask for detecting `["\"","\\"]`.
let e := or(shl(0x22, 1), shl(0x5c, 1))
} iszero(eq(s, end)) {} {
s := add(s, 1)
let c := and(mload(s), 0xff)
if iszero(lt(c, 0x20)) {
if iszero(and(shl(c, 1), e)) {
// Not in `["\"","\\"]`.
mstore8(result, c)
result := add(result, 1)
continue
}
mstore8(result, 0x5c) // "\\".
mstore8(add(result, 1), c)
result := add(result, 2)
continue
}
if iszero(and(shl(c, 1), 0x3700)) {
// Not in `["\b","\t","\n","\f","\d"]`.
mstore8(0x1d, mload(shr(4, c))) // Hex value.
mstore8(0x1e, mload(and(c, 15))) // Hex value.
mstore(result, mload(0x19)) // "\\u00XX".
result := add(result, 6)
continue
}
mstore8(result, 0x5c) // "\\".
mstore8(add(result, 1), mload(add(c, 8)))
result := add(result, 2)
}
let last := result
mstore(last, 0) // Zeroize the slot after the string.
result := mload(0x40)
mstore(result, sub(last, add(result, 0x20))) // Store the length.
mstore(0x40, add(last, 0x20)) // Allocate the memory.
}
}
/// @dev Returns whether `a` equals `b`.
function eq(string memory a, string memory b) internal pure returns (bool result) {
assembly {
result := eq(keccak256(add(a, 0x20), mload(a)), keccak256(add(b, 0x20), mload(b)))
}
}
/// @dev Packs a single string with its length into a single word.
/// Returns `bytes32(0)` if the length is zero or greater than 31.
function packOne(string memory a) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
// We don't need to zero right pad the string,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes.
mload(add(a, 0x1f)),
// `length != 0 && length < 32`. Abuses underflow.
// Assumes that the length is valid and within the block gas limit.
lt(sub(mload(a), 1), 0x1f)
)
}
}
/// @dev Unpacks a string packed using {packOne}.
/// Returns the empty string if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packOne}, the output behaviour is undefined.
function unpackOne(bytes32 packed) internal pure returns (string memory result) {
/// @solidity memory-safe-assembly
assembly {
// Grab the free memory pointer.
result := mload(0x40)
// Allocate 2 words (1 for the length, 1 for the bytes).
mstore(0x40, add(result, 0x40))
// Zeroize the length slot.
mstore(result, 0)
// Store the length and bytes.
mstore(add(result, 0x1f), packed)
// Right pad with zeroes.
mstore(add(add(result, 0x20), mload(result)), 0)
}
}
/// @dev Packs two strings with their lengths into a single word.
/// Returns `bytes32(0)` if combined length is zero or greater than 30.
function packTwo(string memory a, string memory b) internal pure returns (bytes32 result) {
/// @solidity memory-safe-assembly
assembly {
let aLength := mload(a)
// We don't need to zero right pad the strings,
// since this is our own custom non-standard packing scheme.
result :=
mul(
// Load the length and the bytes of `a` and `b`.
or(
shl(shl(3, sub(0x1f, aLength)), mload(add(a, aLength))),
mload(sub(add(b, 0x1e), aLength))
),
// `totalLength != 0 && totalLength < 31`. Abuses underflow.
// Assumes that the lengths are valid and within the block gas limit.
lt(sub(add(aLength, mload(b)), 1), 0x1e)
)
}
}
/// @dev Unpacks strings packed using {packTwo}.
/// Returns the empty strings if `packed` is `bytes32(0)`.
/// If `packed` is not an output of {packTwo}, the output behaviour is undefined.
function unpackTwo(bytes32 packed)
internal
pure
returns (string memory resultA, string memory resultB)
{
/// @solidity memory-safe-assembly
assembly {
// Grab the free memory pointer.
resultA := mload(0x40)
resultB := add(resultA, 0x40)
// Allocate 2 words for each string (1 for the length, 1 for the byte). Total 4 words.
mstore(0x40, add(resultB, 0x40))
// Zeroize the length slots.
mstore(resultA, 0)
mstore(resultB, 0)
// Store the lengths and bytes.
mstore(add(resultA, 0x1f), packed)
mstore(add(resultB, 0x1f), mload(add(add(resultA, 0x20), mload(resultA))))
// Right pad with zeroes.
mstore(add(add(resultA, 0x20), mload(resultA)), 0)
mstore(add(add(resultB, 0x20), mload(resultB)), 0)
}
}
/// @dev Directly returns `a` without copying.
function directReturn(string memory a) internal pure {
assembly {
// Assumes that the string does not start from the scratch space.
let retStart := sub(a, 0x20)
let retSize := add(mload(a), 0x40)
// Right pad with zeroes. Just in case the string is produced
// by a method that doesn't zero right pad.
mstore(add(retStart, retSize), 0)
// Store the return offset.
mstore(retStart, 0x20)
// End the transaction, returning the string.
return(retStart, retSize)
}
}
}
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)
/// @dev Caution! This library won't check that a token has code, responsibility is delegated to the caller.
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();
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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.
/// Multiply by a small constant (e.g. 2), if needed.
uint256 internal constant _GAS_STIPEND_NO_GRIEF = 100000;
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* ETH OPERATIONS */
/*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/
/// @dev Sends `amount` (in wei) ETH to `to`.
/// Reverts upon failure.
function safeTransferETH(address to, uint256 amount) internal {
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and check if it succeeded or not.
if iszero(call(gas(), to, amount, 0, 0, 0, 0)) {
// Store the function selector of `ETHTransferFailed()`.
mstore(0x00, 0xb12d13eb)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
/// The `gasStipend` can be set to a low enough value to prevent
/// storage writes or gas griefing.
///
/// If sending via the normal procedure fails, force sends the ETH by
/// creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.
///
/// Reverts if the current contract has insufficient balance.
function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
/// @solidity memory-safe-assembly
assembly {
// If insufficient balance, revert.
if lt(selfbalance(), amount) {
// Store the function selector of `ETHTransferFailed()`.
mstore(0x00, 0xb12d13eb)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Transfer the ETH and check if it succeeded or not.
if iszero(call(gasStipend, to, amount, 0, 0, 0, 0)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
// We can directly use `SELFDESTRUCT` in the contract creation.
// Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758
if iszero(create(amount, 0x0b, 0x16)) {
// For better gas estimation.
if iszero(gt(gas(), 1000000)) { revert(0, 0) }
}
}
}
}
/// @dev Force sends `amount` (in wei) ETH to `to`, with a gas stipend
/// equal to `_GAS_STIPEND_NO_GRIEF`. This gas stipend is a reasonable default
/// for 99% of cases and can be overriden with the three-argument version of this
/// function if necessary.
///
/// If sending via the normal procedure fails, force sends the ETH by
/// creating a temporary contract which uses `SELFDESTRUCT` to force send the ETH.
///
/// Reverts if the current contract has insufficient balance.
function forceSafeTransferETH(address to, uint256 amount) internal {
// Manually inlined because the compiler doesn't inline functions with branches.
/// @solidity memory-safe-assembly
assembly {
// If insufficient balance, revert.
if lt(selfbalance(), amount) {
// Store the function selector of `ETHTransferFailed()`.
mstore(0x00, 0xb12d13eb)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Transfer the ETH and check if it succeeded or not.
if iszero(call(_GAS_STIPEND_NO_GRIEF, to, amount, 0, 0, 0, 0)) {
mstore(0x00, to) // Store the address in scratch space.
mstore8(0x0b, 0x73) // Opcode `PUSH20`.
mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
// We can directly use `SELFDESTRUCT` in the contract creation.
// Compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758
if iszero(create(amount, 0x0b, 0x16)) {
// For better gas estimation.
if iszero(gt(gas(), 1000000)) { revert(0, 0) }
}
}
}
}
/// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
/// The `gasStipend` can be set to a low enough value to prevent
/// storage writes or gas griefing.
///
/// Simply use `gasleft()` for `gasStipend` if you don't need a gas stipend.
///
/// Note: Does NOT revert upon failure.
/// Returns whether the transfer of ETH is successful instead.
function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
internal
returns (bool success)
{
/// @solidity memory-safe-assembly
assembly {
// Transfer the ETH and check if it succeeded or not.
success := call(gasStipend, to, amount, 0, 0, 0, 0)
}
}
/*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
/* 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.
// Store the function selector of `transferFrom(address,address,uint256)`.
mstore(0x0c, 0x23b872dd000000000000000000000000)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(eq(mload(0x00), 1), iszero(returndatasize())),
call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
)
) {
// Store the function selector of `TransferFromFailed()`.
mstore(0x00, 0x7939f424)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
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 at least `amount` 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.
// Store the function selector of `balanceOf(address)`.
mstore(0x0c, 0x70a08231000000000000000000000000)
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)
)
) {
// Store the function selector of `TransferFromFailed()`.
mstore(0x00, 0x7939f424)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Store the function selector of `transferFrom(address,address,uint256)`.
mstore(0x00, 0x23b872dd)
// The `amount` argument is already written to the memory word at 0x6c.
amount := mload(0x60)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(eq(mload(0x00), 1), iszero(returndatasize())),
call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
)
) {
// Store the function selector of `TransferFromFailed()`.
mstore(0x00, 0x7939f424)
// Revert with (offset, size).
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.
// Store the function selector of `transfer(address,uint256)`.
mstore(0x00, 0xa9059cbb000000000000000000000000)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(eq(mload(0x00), 1), iszero(returndatasize())),
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
// Store the function selector of `TransferFailed()`.
mstore(0x00, 0x90b8ec18)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Restore the part of the free memory pointer that was overwritten.
mstore(0x34, 0)
}
}
/// @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.
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)
)
) {
// Store the function selector of `TransferFailed()`.
mstore(0x00, 0x90b8ec18)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
mstore(0x14, to) // Store the `to` argument.
// The `amount` argument is already written to the memory word at 0x34.
amount := mload(0x34)
// Store the function selector of `transfer(address,uint256)`.
mstore(0x00, 0xa9059cbb000000000000000000000000)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(eq(mload(0x00), 1), iszero(returndatasize())),
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
// Store the function selector of `TransferFailed()`.
mstore(0x00, 0x90b8ec18)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Restore the part of the free memory pointer that was overwritten.
mstore(0x34, 0)
}
}
/// @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.
// Store the function selector of `approve(address,uint256)`.
mstore(0x00, 0x095ea7b3000000000000000000000000)
if iszero(
and( // The arguments of `and` are evaluated from right to left.
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(eq(mload(0x00), 1), iszero(returndatasize())),
call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
)
) {
// Store the function selector of `ApproveFailed()`.
mstore(0x00, 0x3e3f8f73)
// Revert with (offset, size).
revert(0x1c, 0x04)
}
// Restore the part of the free memory pointer that was overwritten.
mstore(0x34, 0)
}
}
/// @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.
// Store the function selector of `balanceOf(address)`.
mstore(0x00, 0x70a08231000000000000000000000000)
amount :=
mul(
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)
)
)
}
}
}
Compiler settingsShow
{
"viaIR": false,
"metadata": {
"useLiteralContent": true
},
"libraries": {
"contracts/marginAccount/Account.sol": {
"CommandExecutor": "0x2d2f07e00b18034dccc8211079b8e05ca2daa35d"
}
},
"optimizer": {
"runs": 1000000,
"details": {
"yulDetails": {
"optimizerSteps": "u"
}
},
"enabled": true
},
"evmVersion": "paris"
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.