| Transaction Hash |
Method
|
Block
|
From
|
|
To
|
||||
|---|---|---|---|---|---|---|---|---|---|
Latest 11 internal transactions
Advanced mode:
| Parent Transaction Hash | Method | Block |
From
|
|
To
|
||
|---|---|---|---|---|---|---|---|
| 0x3d602d80 | 22588762 | 240 days ago | Contract Creation | 0 ETH | |||
| 0x3d602d80 | 22469054 | 256 days ago | Contract Creation | 0 ETH | |||
| 0x3d602d80 | 21516141 | 390 days ago | Contract Creation | 0 ETH | |||
| 0x3d602d80 | 21128762 | 444 days ago | Contract Creation | 0 ETH | |||
| 0x3d602d80 | 20883694 | 478 days ago | Contract Creation | 0 ETH | |||
| 0x3d602d80 | 20769189 | 494 days ago | Contract Creation | 0 ETH | |||
| 0x3d602d80 | 20341435 | 554 days ago | Contract Creation | 0 ETH | |||
| 0x3d602d80 | 20241484 | 568 days ago | Contract Creation | 0 ETH | |||
| 0x3d602d80 | 19730974 | 639 days ago | Contract Creation | 0 ETH | |||
| 0x3d602d80 | 19688192 | 645 days ago | Contract Creation | 0 ETH | |||
| 0x61018060 | 19440822 | 680 days ago | Contract Creation | 0 ETH |
Loading...
Loading
Cross-Chain Transactions
Loading...
Loading
This contract may be a proxy contract. Click on More Options and select Is this a proxy? to confirm and enable the "Read as Proxy" & "Write as Proxy" tabs.
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0x5Fe88494...249AD56ed The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
Stonks
Compiler Version
v0.8.23+commit.f704f362
Optimization Enabled:
Yes with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-FileCopyrightText: 2024 Lido <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.23; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Clones} from "@openzeppelin/contracts/proxy/Clones.sol"; import {Order} from "./Order.sol"; import {AssetRecoverer} from "./AssetRecoverer.sol"; import {IStonks} from "./interfaces/IStonks.sol"; import {IAmountConverter} from "./interfaces/IAmountConverter.sol"; /** * @title Stonks Trading Management Contract * @dev Centralizes the management of CoW Swap trading orders, interfacing with the Order contract. * * Features: * - Stores key trading parameters: token pair, margin, price tolerance and order duration in immutable variables. * - Creates a minimum proxy from the Order contract and passes params for individual trades. * - Provides asset recovery functionality. * * @notice Orchestrates the setup and execution of trades on CoW Swap, utilizing Order contracts for each trade. */ contract Stonks is IStonks, AssetRecoverer { using SafeERC20 for IERC20; uint16 private constant MAX_BASIS_POINTS = 10_000; uint16 private constant BASIS_POINTS_PARAMETERS_LIMIT = 1_000; uint256 private constant MIN_POSSIBLE_BALANCE = 10; uint256 private constant MIN_POSSIBLE_ORDER_DURATION_IN_SECONDS = 1 minutes; uint256 private constant MAX_POSSIBLE_ORDER_DURATION_IN_SECONDS = 1 days; address public immutable AMOUNT_CONVERTER; address public immutable ORDER_SAMPLE; address public immutable TOKEN_FROM; address public immutable TOKEN_TO; uint256 public immutable ORDER_DURATION_IN_SECONDS; uint256 public immutable MARGIN_IN_BASIS_POINTS; uint256 public immutable PRICE_TOLERANCE_IN_BASIS_POINTS; event AmountConverterSet(address amountConverter); event OrderSampleSet(address orderSample); event TokenFromSet(address tokenFrom); event TokenToSet(address tokenTo); event OrderDurationInSecondsSet(uint256 orderDurationInSeconds); event MarginInBasisPointsSet(uint256 marginInBasisPoints); event PriceToleranceInBasisPointsSet(uint256 priceToleranceInBasisPoints); event OrderContractCreated(address indexed orderContract, uint256 minBuyAmount); error InvalidManagerAddress(address manager); error InvalidTokenFromAddress(address tokenFrom); error InvalidTokenToAddress(address tokenTo); error InvalidAmountConverterAddress(address amountConverter); error InvalidOrderSampleAddress(address orderSample); error TokensCannotBeSame(); error InvalidOrderDuration(uint256 min, uint256 max, uint256 received); error MarginOverflowsAllowedLimit(uint256 limit, uint256 received); error PriceToleranceOverflowsAllowedLimit(uint256 limit, uint256 received); error MinimumPossibleBalanceNotMet(uint256 min, uint256 received); error InvalidAmount(uint256 amount); /** * @notice Initializes the Stonks contract with key trading parameters. * @dev Stores essential parameters for trade execution in immutable variables, ensuring consistency and security of trades. */ constructor( address agent_, address manager_, address tokenFrom_, address tokenTo_, address amountConverter_, address orderSample_, uint256 orderDurationInSeconds_, uint256 marginInBasisPoints_, uint256 priceToleranceInBasisPoints_ ) AssetRecoverer(agent_) { if (manager_ == address(0)) revert InvalidManagerAddress(manager_); if (tokenFrom_ == address(0)) revert InvalidTokenFromAddress(tokenFrom_); if (tokenTo_ == address(0)) revert InvalidTokenToAddress(tokenTo_); if (tokenFrom_ == tokenTo_) revert TokensCannotBeSame(); if (amountConverter_ == address(0)) revert InvalidAmountConverterAddress(amountConverter_); if (orderSample_ == address(0)) revert InvalidOrderSampleAddress(orderSample_); if ( orderDurationInSeconds_ > MAX_POSSIBLE_ORDER_DURATION_IN_SECONDS || orderDurationInSeconds_ < MIN_POSSIBLE_ORDER_DURATION_IN_SECONDS ) { revert InvalidOrderDuration( MIN_POSSIBLE_ORDER_DURATION_IN_SECONDS, MAX_POSSIBLE_ORDER_DURATION_IN_SECONDS, orderDurationInSeconds_ ); } if (marginInBasisPoints_ > BASIS_POINTS_PARAMETERS_LIMIT) { revert MarginOverflowsAllowedLimit(BASIS_POINTS_PARAMETERS_LIMIT, marginInBasisPoints_); } if (priceToleranceInBasisPoints_ > BASIS_POINTS_PARAMETERS_LIMIT) { revert PriceToleranceOverflowsAllowedLimit(BASIS_POINTS_PARAMETERS_LIMIT, priceToleranceInBasisPoints_); } manager = manager_; ORDER_SAMPLE = orderSample_; AMOUNT_CONVERTER = amountConverter_; TOKEN_FROM = tokenFrom_; TOKEN_TO = tokenTo_; ORDER_DURATION_IN_SECONDS = orderDurationInSeconds_; MARGIN_IN_BASIS_POINTS = marginInBasisPoints_; PRICE_TOLERANCE_IN_BASIS_POINTS = priceToleranceInBasisPoints_; emit ManagerSet(manager_); emit AmountConverterSet(amountConverter_); emit OrderSampleSet(orderSample_); emit TokenFromSet(tokenFrom_); emit TokenToSet(tokenTo_); emit OrderDurationInSecondsSet(orderDurationInSeconds_); emit MarginInBasisPointsSet(marginInBasisPoints_); emit PriceToleranceInBasisPointsSet(priceToleranceInBasisPoints_); } /** * @notice Initiates a new trading order by creating an Order contract clone with the current token balance. * @dev Transfers the tokenFrom balance to the new Order instance and initializes it with the Stonks' manager settings for execution. * @param minBuyAmount_ Minimum amount of tokenTo to be received as a result of the trade. * @return Address of the newly created Order contract. */ function placeOrder(uint256 minBuyAmount_) external onlyAgentOrManager returns (address) { if (minBuyAmount_ == 0) revert InvalidAmount(minBuyAmount_); uint256 balance = IERC20(TOKEN_FROM).balanceOf(address(this)); // Prevents dust trades to avoid rounding issues for rebasable tokens like stETH. if (balance < MIN_POSSIBLE_BALANCE) revert MinimumPossibleBalanceNotMet(MIN_POSSIBLE_BALANCE, balance); Order orderCopy = Order(Clones.clone(ORDER_SAMPLE)); IERC20(TOKEN_FROM).safeTransfer(address(orderCopy), balance); orderCopy.initialize(minBuyAmount_, manager); emit OrderContractCreated(address(orderCopy), minBuyAmount_); return address(orderCopy); } /** * @notice Estimates output amount for a given trade input amount. * @param amount_ Input token amount for trade. * @dev Uses token amount converter for output estimation. * @return estimatedTradeOutput Estimated trade output amount. * Subtracts the amount that corresponds to the margin parameter from the result obtained from the amount converter. * * | estimatedTradeOutput expectedBuyAmount * | --------------*--------------------------*-----------------> amount * | <-------- margin --------> * * where: * expectedBuyAmount - amount received from the amountConverter based on Chainlink price feed. * margin - % taken from the expectedBuyAmount includes CoW Protocol fees and maximum accepted losses * to handle market volatility. * estimatedTradeOutput - expectedBuyAmount subtracted by the margin that is expected to be result of the trade. */ function estimateTradeOutput(uint256 amount_) public view returns (uint256 estimatedTradeOutput) { if (amount_ == 0) revert InvalidAmount(amount_); uint256 expectedBuyAmount = IAmountConverter(AMOUNT_CONVERTER).getExpectedOut(TOKEN_FROM, TOKEN_TO, amount_); estimatedTradeOutput = (expectedBuyAmount * (MAX_BASIS_POINTS - MARGIN_IN_BASIS_POINTS)) / MAX_BASIS_POINTS; } /** * @notice Estimates trade output based on current input token balance. * @dev Uses current balance for output estimation via `estimateTradeOutput`. * @return Estimated trade output amount. */ function estimateTradeOutputFromCurrentBalance() external view returns (uint256) { uint256 balance = IERC20(TOKEN_FROM).balanceOf(address(this)); return estimateTradeOutput(balance); } /** * @notice Returns trading parameters from Stonks for use in the Order contract. * @dev Facilitates gas efficiency by allowing Order to access existing parameters in Stonks without redundant storage. * @return Tuple of order parameters (tokenFrom, tokenTo, orderDurationInSeconds). */ function getOrderParameters() external view returns (address, address, uint256) { return (TOKEN_FROM, TOKEN_TO, ORDER_DURATION_IN_SECONDS); } /** * @notice Returns price tolerance parameter from Stonks for use in the Order contract. * @dev Facilitates gas efficiency by allowing Order to access existing parameters in Stonks without redundant storage. * @return Price tolerance in basis points. */ function getPriceTolerance() external view returns (uint256) { return PRICE_TOLERANCE_IN_BASIS_POINTS; } }
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC1271 standard signature validation method for
* contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271].
*
* _Available since v4.1._
*/
interface IERC1271 {
/**
* @dev Should return whether the signature provided is valid for the provided data
* @param hash Hash of the data to be signed
* @param signature Signature byte array associated with _data
*/
function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/Clones.sol)
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library Clones {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(0, 0x09, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
/// @solidity memory-safe-assembly
assembly {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create2(0, 0x09, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(add(ptr, 0x38), deployer)
mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
mstore(add(ptr, 0x14), implementation)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
mstore(add(ptr, 0x58), salt)
mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
predicted := keccak256(add(ptr, 0x43), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @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 amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` 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 amount) 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 `amount` 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 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` 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 amount) external returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @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.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @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, it is bubbled up by this
* function (like regular Solidity function calls).
*
* 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.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @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`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) 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(errorMessage);
}
}
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}// SPDX-FileCopyrightText: 2024 Lido <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.23; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {Ownable} from "./Ownable.sol"; /** * @title AssetRecoverer * @dev Abstract contract providing mechanisms for recovering various asset types (ETH, ERC20, ERC721, ERC1155) from a contract. * This contract is designed to allow asset recovery by an authorized agent or a manager. * @notice Assets can be sent only to the agent address. */ abstract contract AssetRecoverer is Ownable { using SafeERC20 for IERC20; event EtherRecovered(address indexed _recipient, uint256 _amount); event ERC20Recovered(address indexed _token, address indexed _recipient, uint256 _amount); event ERC721Recovered(address indexed _token, uint256 _tokenId, address indexed _recipient); event ERC1155Recovered(address indexed _token, uint256 _tokenId, address indexed _recipient, uint256 _amount); /** * @dev Sets the initial agent address. * @param agent_ The address of the Lido DAO treasury. */ constructor(address agent_) Ownable(agent_) {} /** * @dev Allows the agent or manager to recover Ether held by the contract. * Emits an EtherRecovered event upon success. */ function recoverEther() external onlyAgentOrManager { uint256 amount = address(this).balance; (bool success,) = AGENT.call{value: amount}(""); require(success); emit EtherRecovered(AGENT, amount); } /** * @dev Allows the agent or manager to recover ERC20 tokens held by the contract. * @param token_ The address of the ERC20 token to recover. * @param amount_ The amount of the ERC20 token to recover. * Emits an ERC20Recovered event upon success. */ function recoverERC20(address token_, uint256 amount_) public virtual onlyAgentOrManager { IERC20(token_).safeTransfer(AGENT, amount_); emit ERC20Recovered(token_, AGENT, amount_); } /** * @dev Allows the agent or manager to recover ERC721 tokens held by the contract. * @param token_ The address of the ERC721 token to recover. * @param tokenId_ The token ID of the ERC721 token to recover. * Emits an ERC721Recovered event upon success. */ function recoverERC721(address token_, uint256 tokenId_) external onlyAgentOrManager { IERC721(token_).safeTransferFrom(address(this), AGENT, tokenId_); emit ERC721Recovered(token_, tokenId_, AGENT); } /** * @dev Allows the agent or manager to recover ERC1155 tokens held by the contract. * @param token_ The address of the ERC1155 token to recover. * @param tokenId_ The token ID of the ERC1155 token to recover. * Emits an ERC1155Recovered event upon success. */ function recoverERC1155(address token_, uint256 tokenId_) external onlyAgentOrManager { uint256 amount = IERC1155(token_).balanceOf(address(this), tokenId_); IERC1155(token_).safeTransferFrom(address(this), AGENT, tokenId_, amount, ""); emit ERC1155Recovered(token_, tokenId_, AGENT, amount); } }
// SPDX-FileCopyrightText: 2024 Lido <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.23; interface IAmountConverter { function getExpectedOut(address sellToken, address buyToken, uint256 amount) external view returns (uint256); }
// SPDX-FileCopyrightText: 2024 Lido <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.23; interface IStonks { function getOrderParameters() external view returns (address tokenFrom, address tokenTo, uint256 orderDurationInSeconds); function getPriceTolerance() external view returns (uint256); function estimateTradeOutput(uint256 amount) external view returns (uint256); }
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity ^0.8.10;
/// @notice IERC20Metadata is used to support .decimals() method
import {IERC20Metadata as IERC20} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
/// @title Gnosis Protocol v2 Order Library
/// @author Gnosis Developers
/// @notice Copied from https://github.com/cowprotocol/contracts/blob/main/src/contracts/libraries/GPv2Order.sol
library GPv2Order {
/// @dev The complete data for a Gnosis Protocol order. This struct contains
/// all order parameters that are signed for submitting to GP.
struct Data {
IERC20 sellToken;
IERC20 buyToken;
address receiver;
uint256 sellAmount;
uint256 buyAmount;
uint32 validTo;
bytes32 appData;
uint256 feeAmount;
bytes32 kind;
bool partiallyFillable;
bytes32 sellTokenBalance;
bytes32 buyTokenBalance;
}
/// @dev The order EIP-712 type hash for the [`GPv2Order.Data`] struct.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256(
/// "Order(" +
/// "address sellToken," +
/// "address buyToken," +
/// "address receiver," +
/// "uint256 sellAmount," +
/// "uint256 buyAmount," +
/// "uint32 validTo," +
/// "bytes32 appData," +
/// "uint256 feeAmount," +
/// "string kind," +
/// "bool partiallyFillable," +
/// "string sellTokenBalance," +
/// "string buyTokenBalance" +
/// ")"
/// )
/// ```
bytes32 internal constant TYPE_HASH = hex"d5a25ba2e97094ad7d83dc28a6572da797d6b3e7fc6663bd93efb789fc17e489";
/// @dev The marker value for a sell order for computing the order struct
/// hash. This allows the EIP-712 compatible wallets to display a
/// descriptive string for the order kind (instead of 0 or 1).
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("sell")
/// ```
bytes32 internal constant KIND_SELL = hex"f3b277728b3fee749481eb3e0b3b48980dbbab78658fc419025cb16eee346775";
/// @dev The OrderKind marker value for a buy order for computing the order
/// struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("buy")
/// ```
bytes32 internal constant KIND_BUY = hex"6ed88e868af0a1983e3886d5f3e95a2fafbd6c3450bc229e27342283dc429ccc";
/// @dev The TokenBalance marker value for using direct ERC20 balances for
/// computing the order struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("erc20")
/// ```
bytes32 internal constant BALANCE_ERC20 = hex"5a28e9363bb942b639270062aa6bb295f434bcdfc42c97267bf003f272060dc9";
/// @dev The TokenBalance marker value for using Balancer Vault external
/// balances (in order to re-use Vault ERC20 approvals) for computing the
/// order struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("external")
/// ```
bytes32 internal constant BALANCE_EXTERNAL = hex"abee3b73373acd583a130924aad6dc38cfdc44ba0555ba94ce2ff63980ea0632";
/// @dev The TokenBalance marker value for using Balancer Vault internal
/// balances for computing the order struct hash.
///
/// This value is pre-computed from the following expression:
/// ```
/// keccak256("internal")
/// ```
bytes32 internal constant BALANCE_INTERNAL = hex"4ac99ace14ee0a5ef932dc609df0943ab7ac16b7583634612f8dc35a4289a6ce";
/// @dev Marker address used to indicate that the receiver of the trade
/// proceeds should the owner of the order.
///
/// This is chosen to be `address(0)` for gas efficiency as it is expected
/// to be the most common case.
address internal constant RECEIVER_SAME_AS_OWNER = address(0);
/// @dev The byte length of an order unique identifier.
uint256 internal constant UID_LENGTH = 56;
/// @dev Returns the actual receiver for an order. This function checks
/// whether or not the [`receiver`] field uses the marker value to indicate
/// it is the same as the order owner.
///
/// @return receiver The actual receiver of trade proceeds.
function actualReceiver(Data memory order, address owner) internal pure returns (address receiver) {
if (order.receiver == RECEIVER_SAME_AS_OWNER) {
receiver = owner;
} else {
receiver = order.receiver;
}
}
/// @dev Return the EIP-712 signing hash for the specified order.
///
/// @param order The order to compute the EIP-712 signing hash for.
/// @param domainSeparator The EIP-712 domain separator to use.
/// @return orderDigest The 32 byte EIP-712 struct hash.
function hash(Data memory order, bytes32 domainSeparator) internal pure returns (bytes32 orderDigest) {
bytes32 structHash;
// NOTE: Compute the EIP-712 order struct hash in place. As suggested
// in the EIP proposal, noting that the order struct has 12 fields, and
// prefixing the type hash `(1 + 12) * 32 = 416` bytes to hash.
// <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#rationale-for-encodedata>
// solhint-disable-next-line no-inline-assembly
assembly {
let dataStart := sub(order, 32)
let temp := mload(dataStart)
mstore(dataStart, TYPE_HASH)
structHash := keccak256(dataStart, 416)
mstore(dataStart, temp)
}
// NOTE: Now that we have the struct hash, compute the EIP-712 signing
// hash using scratch memory past the free memory pointer. The signing
// hash is computed from `"\x19\x01" || domainSeparator || structHash`.
// <https://docs.soliditylang.org/en/v0.7.6/internals/layout_in_memory.html#layout-in-memory>
// <https://github.com/ethereum/EIPs/blob/master/EIPS/eip-712.md#specification>
// solhint-disable-next-line no-inline-assembly
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, "\x19\x01")
mstore(add(freeMemoryPointer, 2), domainSeparator)
mstore(add(freeMemoryPointer, 34), structHash)
orderDigest := keccak256(freeMemoryPointer, 66)
}
}
/// @dev Packs order UID parameters into the specified memory location. The
/// result is equivalent to `abi.encodePacked(...)` with the difference that
/// it allows re-using the memory for packing the order UID.
///
/// This function reverts if the order UID buffer is not the correct size.
///
/// @param orderUid The buffer pack the order UID parameters into.
/// @param orderDigest The EIP-712 struct digest derived from the order
/// parameters.
/// @param owner The address of the user who owns this order.
/// @param validTo The epoch time at which the order will stop being valid.
function packOrderUidParams(bytes memory orderUid, bytes32 orderDigest, address owner, uint32 validTo)
internal
pure
{
require(orderUid.length == UID_LENGTH, "GPv2: uid buffer overflow");
// NOTE: Write the order UID to the allocated memory buffer. The order
// parameters are written to memory in **reverse order** as memory
// operations write 32-bytes at a time and we want to use a packed
// encoding. This means, for example, that after writing the value of
// `owner` to bytes `20:52`, writing the `orderDigest` to bytes `0:32`
// will **overwrite** bytes `20:32`. This is desirable as addresses are
// only 20 bytes and `20:32` should be `0`s:
//
// | 1111111111222222222233333333334444444444555555
// byte | 01234567890123456789012345678901234567890123456789012345
// -------+---------------------------------------------------------
// field | [.........orderDigest..........][......owner.......][vT]
// -------+---------------------------------------------------------
// mstore | [000000000000000000000000000.vT]
// | [00000000000.......owner.......]
// | [.........orderDigest..........]
//
// Additionally, since Solidity `bytes memory` are length prefixed,
// 32 needs to be added to all the offsets.
//
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(add(orderUid, 56), validTo)
mstore(add(orderUid, 52), owner)
mstore(add(orderUid, 32), orderDigest)
}
}
/// @dev Extracts specific order information from the standardized unique
/// order id of the protocol.
///
/// @param orderUid The unique identifier used to represent an order in
/// the protocol. This uid is the packed concatenation of the order digest,
/// the validTo order parameter and the address of the user who created the
/// order. It is used by the user to interface with the contract directly,
/// and not by calls that are triggered by the solvers.
/// @return orderDigest The EIP-712 signing digest derived from the order
/// parameters.
/// @return owner The address of the user who owns this order.
/// @return validTo The epoch time at which the order will stop being valid.
function extractOrderUidParams(bytes calldata orderUid)
internal
pure
returns (bytes32 orderDigest, address owner, uint32 validTo)
{
require(orderUid.length == UID_LENGTH, "GPv2: invalid uid");
// Use assembly to efficiently decode packed calldata.
// solhint-disable-next-line no-inline-assembly
assembly {
orderDigest := calldataload(orderUid.offset)
owner := shr(96, calldataload(add(orderUid.offset, 32)))
validTo := shr(224, calldataload(add(orderUid.offset, 52)))
}
}
}// SPDX-FileCopyrightText: 2024 Lido <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.23; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {GPv2Order} from "./lib/GPv2Order.sol"; import {AssetRecoverer} from "./AssetRecoverer.sol"; import {IStonks} from "./interfaces/IStonks.sol"; /** * @title CoW Protocol Programmatic Order * @dev Handles the execution of individual trading order for the Stonks contract on CoW Protocol. * * Features: * - Retrieves trade parameters from Stonks contract, ensuring alignment with the overall trading strategy. * - Single-use design: each contract proxy is intended for one-time use, providing fresh settings for each trade. * - Complies with ERC1271 for secure order validation. * - Provides asset recovery functionality. * * @notice Serves as an execution module for CoW Protocol trades, operating under parameters set by the Stonks contract. */ contract Order is IERC1271, AssetRecoverer { using GPv2Order for GPv2Order.Data; using SafeERC20 for IERC20; // bytes4(keccak256("isValidSignature(bytes32,bytes)") bytes4 private constant ERC1271_MAGIC_VALUE = 0x1626ba7e; uint256 private constant MIN_POSSIBLE_BALANCE = 10; uint256 private constant MAX_BASIS_POINTS = 10_000; bytes32 private constant APP_DATA = keccak256("{}"); address public immutable RELAYER; bytes32 public immutable DOMAIN_SEPARATOR; uint256 private sellAmount; uint256 private buyAmount; bytes32 private orderHash; address public stonks; uint32 private validTo; bool private initialized; event RelayerSet(address relayer); event DomainSeparatorSet(bytes32 domainSeparator); event OrderCreated(address indexed order, bytes32 orderHash, GPv2Order.Data orderData); error OrderAlreadyInitialized(); error OrderExpired(uint256 validTo); error InvalidAmountToRecover(uint256 amount); error CannotRecoverTokenFrom(address token); error InvalidOrderHash(bytes32 expected, bytes32 actual); error OrderNotExpired(uint256 validTo, uint256 currentTimestamp); error PriceConditionChanged(uint256 maxAcceptedAmount, uint256 actualAmount); /** * @param agent_ The agent's address with control over the contract. * @param relayer_ The address of the relayer handling orders. * @param domainSeparator_ The EIP-712 domain separator to use. * @dev This constructor sets up necessary parameters and state variables to enable the contract's interaction with the CoW Protocol. * @dev It also marks the contract as initialized to prevent unauthorized re-initialization. */ constructor(address agent_, address relayer_, bytes32 domainSeparator_) AssetRecoverer(agent_) { // Immutable variables are set at contract deployment and remain unchangeable thereafter. // This ensures that even when creating new proxies via a minimal proxy, // these variables retain their initial values assigned at the time of the original contract deployment. RELAYER = relayer_; DOMAIN_SEPARATOR = domainSeparator_; // This variable is stored in the contract's storage and will be overwritten // when a new proxy is created via a minimal proxy. Currently, it is set to true // to prevent any initialization of a transaction on 'sample' by unauthorized entities. initialized = true; emit RelayerSet(relayer_); emit DomainSeparatorSet(domainSeparator_); } /** * @notice Initializes the contract for trading by defining order parameters and approving tokens. * @param minBuyAmount_ The minimum accepted trade outcome. * @param manager_ The manager's address to be set for the contract. * @dev This function calculates the buy amount from ChainLink and manager input, sets the order parameters, and approves tokens for trading. */ function initialize(uint256 minBuyAmount_, address manager_) external { if (initialized) revert OrderAlreadyInitialized(); initialized = true; stonks = msg.sender; manager = manager_; (address tokenFrom, address tokenTo, uint256 orderDurationInSeconds) = IStonks(stonks).getOrderParameters(); validTo = uint32(block.timestamp + orderDurationInSeconds); sellAmount = IERC20(tokenFrom).balanceOf(address(this)); buyAmount = Math.max(IStonks(stonks).estimateTradeOutput(sellAmount), minBuyAmount_); GPv2Order.Data memory order = GPv2Order.Data({ sellToken: IERC20Metadata(tokenFrom), buyToken: IERC20Metadata(tokenTo), receiver: AGENT, sellAmount: sellAmount, buyAmount: buyAmount, validTo: validTo, appData: APP_DATA, // Fee amount is set to 0 for creating limit order // https://docs.cow.fi/tutorials/submit-limit-orders-via-api/general-overview feeAmount: 0, kind: GPv2Order.KIND_SELL, partiallyFillable: false, sellTokenBalance: GPv2Order.BALANCE_ERC20, buyTokenBalance: GPv2Order.BALANCE_ERC20 }); orderHash = order.hash(DOMAIN_SEPARATOR); // Approval is set to the maximum value of uint256 as the contract is intended for single-use only. // This eliminates the need for subsequent approval calls, optimizing for gas efficiency in one-time transactions. IERC20(tokenFrom).forceApprove(RELAYER, type(uint256).max); emit OrderCreated(address(this), orderHash, order); } /** * @notice Validates the order's signature and ensures compliance with price and timing constraints. * @param hash_ The hash of the order for validation. * @return magicValue The magic value of ERC1271. * @dev Checks include: * - Matching the provided hash with the stored order hash. * - Confirming order validity within the specified timeframe (`validTo`). * - Computing and comparing expected purchase amounts with market price (provided by ChainLink). * - Checking that the price tolerance is not exceeded. */ function isValidSignature(bytes32 hash_, bytes calldata) external view returns (bytes4 magicValue) { if (hash_ != orderHash) revert InvalidOrderHash(orderHash, hash_); if (validTo < block.timestamp) revert OrderExpired(validTo); /// The price tolerance mechanism is crucial for ensuring that the order remains valid only within a specific price range. /// This is a safeguard against market volatility and drastic price changes, which could otherwise lead to unfavorable trades. /// If the price deviates beyond the tolerance level, the order is invalidated to protect against executing a trade at an undesirable rate. /// /// | buyAmount maxToleratedAmount currentCalculatedBuyAmount /// | --------------*-----------------------------*-----------------------------*-----------------> amount /// | <-------- tolerance --------> /// | <-------------------- differenceAmount -------------------> /// /// where: /// buyAmount - amount received from the Stonks contract, which is the minimum accepted result amount of the trade. /// tolerance - the maximum accepted deviation of the buyAmount. /// currentCalculatedBuyAmount - the currently calculated purchase amount based on real-time market conditions taken from Stonks contract. /// differenceAmount - the difference between the buyAmount and the currentCalculatedBuyAmount. /// maxToleratedAmount - the maximum tolerated deviation of the purchase amount. Represents the threshold beyond which the order is /// considered invalid due to excessive deviation from the expected purchase amount. uint256 currentCalculatedBuyAmount = IStonks(stonks).estimateTradeOutput(sellAmount); if (currentCalculatedBuyAmount <= buyAmount) return ERC1271_MAGIC_VALUE; uint256 priceToleranceInBasisPoints = IStonks(stonks).getPriceTolerance(); uint256 differenceAmount = currentCalculatedBuyAmount - buyAmount; uint256 maxToleratedAmountDeviation = buyAmount * priceToleranceInBasisPoints / MAX_BASIS_POINTS; if (differenceAmount > maxToleratedAmountDeviation) { revert PriceConditionChanged(buyAmount + maxToleratedAmountDeviation, currentCalculatedBuyAmount); } return ERC1271_MAGIC_VALUE; } /** * @notice Retrieves the details of the placed order. * @return hash_ The hash of the order. * @return tokenFrom_ The address of the token being sold. * @return tokenTo_ The address of the token being bought. * @return sellAmount_ The amount of `tokenFrom_` that is being sold. * @return buyAmount_ The amount of `tokenTo_` that is expected to be bought. * @return validTo_ The timestamp until which the order remains valid. */ function getOrderDetails() external view returns ( bytes32 hash_, address tokenFrom_, address tokenTo_, uint256 sellAmount_, uint256 buyAmount_, uint32 validTo_ ) { (address tokenFrom, address tokenTo,) = IStonks(stonks).getOrderParameters(); return (orderHash, tokenFrom, tokenTo, sellAmount, buyAmount, validTo); } /** * @notice Allows to return tokens if the order has expired. * @dev Can only be called if the order's validity period has passed. */ function recoverTokenFrom() external { if (validTo >= block.timestamp) revert OrderNotExpired(validTo, block.timestamp); (address tokenFrom,,) = IStonks(stonks).getOrderParameters(); uint256 balance = IERC20(tokenFrom).balanceOf(address(this)); // Prevents dust transfers to avoid rounding issues for rebasable tokens like stETH. if (balance < MIN_POSSIBLE_BALANCE) revert InvalidAmountToRecover(balance); IERC20(tokenFrom).safeTransfer(stonks, balance); } /** * @notice Facilitates the recovery of ERC20 tokens from the contract, except for the token involved in the order. * @param token_ The address of the token to recover. * @param amount_ The amount of the token to recover. * @dev Can only be called by the agent or manager of the contract. This is a safety feature to prevent accidental token loss. */ function recoverERC20(address token_, uint256 amount_) public override onlyAgentOrManager { (address tokenFrom,,) = IStonks(stonks).getOrderParameters(); if (token_ == tokenFrom) revert CannotRecoverTokenFrom(tokenFrom); AssetRecoverer.recoverERC20(token_, amount_); } }
// SPDX-FileCopyrightText: 2024 Lido <[email protected]> // SPDX-License-Identifier: MIT pragma solidity 0.8.23; /** * @title Ownable * * @dev Provides basic access control mechanism where two accounts (agent and manager) can be granted access to specific functions. * The agent is set during contract deployment and cannot be changed. The manager can be set by the agent. */ contract Ownable { address public immutable AGENT; address public manager; event ManagerSet(address manager); event AgentSet(address agent); error InvalidAgentAddress(address agent_); error NotAgentOrManager(address sender); error NotAgent(address sender); /** * @dev Modifier to restrict function access from the agent. */ modifier onlyAgent() { if (msg.sender != AGENT) revert NotAgent(msg.sender); _; } /** * @dev Modifier to restrict function access from either the agent or the manager. */ modifier onlyAgentOrManager() { if (msg.sender != AGENT && msg.sender != manager) revert NotAgentOrManager(msg.sender); _; } /** * @dev Initializes the contract setting the agent. * @param agent_ The address of the agent. */ constructor(address agent_) { if (agent_ == address(0)) revert InvalidAgentAddress(agent_); AGENT = agent_; emit AgentSet(agent_); } /** * @dev Sets the manager address. * @param manager_ The address of the new manager. */ function setManager(address manager_) external onlyAgent { manager = manager_; emit ManagerSet(manager_); } }
{
"optimizer": {
"enabled": true,
"runs": 200
},
"evmVersion": "paris",
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"agent_","type":"address"},{"internalType":"address","name":"manager_","type":"address"},{"internalType":"address","name":"tokenFrom_","type":"address"},{"internalType":"address","name":"tokenTo_","type":"address"},{"internalType":"address","name":"amountConverter_","type":"address"},{"internalType":"address","name":"orderSample_","type":"address"},{"internalType":"uint256","name":"orderDurationInSeconds_","type":"uint256"},{"internalType":"uint256","name":"marginInBasisPoints_","type":"uint256"},{"internalType":"uint256","name":"priceToleranceInBasisPoints_","type":"uint256"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[{"internalType":"address","name":"agent_","type":"address"}],"name":"InvalidAgentAddress","type":"error"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"InvalidAmount","type":"error"},{"inputs":[{"internalType":"address","name":"amountConverter","type":"address"}],"name":"InvalidAmountConverterAddress","type":"error"},{"inputs":[{"internalType":"address","name":"manager","type":"address"}],"name":"InvalidManagerAddress","type":"error"},{"inputs":[{"internalType":"uint256","name":"min","type":"uint256"},{"internalType":"uint256","name":"max","type":"uint256"},{"internalType":"uint256","name":"received","type":"uint256"}],"name":"InvalidOrderDuration","type":"error"},{"inputs":[{"internalType":"address","name":"orderSample","type":"address"}],"name":"InvalidOrderSampleAddress","type":"error"},{"inputs":[{"internalType":"address","name":"tokenFrom","type":"address"}],"name":"InvalidTokenFromAddress","type":"error"},{"inputs":[{"internalType":"address","name":"tokenTo","type":"address"}],"name":"InvalidTokenToAddress","type":"error"},{"inputs":[{"internalType":"uint256","name":"limit","type":"uint256"},{"internalType":"uint256","name":"received","type":"uint256"}],"name":"MarginOverflowsAllowedLimit","type":"error"},{"inputs":[{"internalType":"uint256","name":"min","type":"uint256"},{"internalType":"uint256","name":"received","type":"uint256"}],"name":"MinimumPossibleBalanceNotMet","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"NotAgent","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"NotAgentOrManager","type":"error"},{"inputs":[{"internalType":"uint256","name":"limit","type":"uint256"},{"internalType":"uint256","name":"received","type":"uint256"}],"name":"PriceToleranceOverflowsAllowedLimit","type":"error"},{"inputs":[],"name":"TokensCannotBeSame","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"agent","type":"address"}],"name":"AgentSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"amountConverter","type":"address"}],"name":"AmountConverterSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_token","type":"address"},{"indexed":false,"internalType":"uint256","name":"_tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"_recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"ERC1155Recovered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_token","type":"address"},{"indexed":true,"internalType":"address","name":"_recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"ERC20Recovered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_token","type":"address"},{"indexed":false,"internalType":"uint256","name":"_tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"_recipient","type":"address"}],"name":"ERC721Recovered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"_recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"_amount","type":"uint256"}],"name":"EtherRecovered","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"manager","type":"address"}],"name":"ManagerSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"marginInBasisPoints","type":"uint256"}],"name":"MarginInBasisPointsSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"orderContract","type":"address"},{"indexed":false,"internalType":"uint256","name":"minBuyAmount","type":"uint256"}],"name":"OrderContractCreated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"orderDurationInSeconds","type":"uint256"}],"name":"OrderDurationInSecondsSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"orderSample","type":"address"}],"name":"OrderSampleSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint256","name":"priceToleranceInBasisPoints","type":"uint256"}],"name":"PriceToleranceInBasisPointsSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"tokenFrom","type":"address"}],"name":"TokenFromSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"tokenTo","type":"address"}],"name":"TokenToSet","type":"event"},{"inputs":[],"name":"AGENT","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"AMOUNT_CONVERTER","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MARGIN_IN_BASIS_POINTS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ORDER_DURATION_IN_SECONDS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"ORDER_SAMPLE","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PRICE_TOLERANCE_IN_BASIS_POINTS","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TOKEN_FROM","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"TOKEN_TO","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"estimateTradeOutput","outputs":[{"internalType":"uint256","name":"estimatedTradeOutput","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"estimateTradeOutputFromCurrentBalance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getOrderParameters","outputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getPriceTolerance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"minBuyAmount_","type":"uint256"}],"name":"placeOrder","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token_","type":"address"},{"internalType":"uint256","name":"tokenId_","type":"uint256"}],"name":"recoverERC1155","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token_","type":"address"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"recoverERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token_","type":"address"},{"internalType":"uint256","name":"tokenId_","type":"uint256"}],"name":"recoverERC721","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"recoverEther","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"manager_","type":"address"}],"name":"setManager","outputs":[],"stateMutability":"nonpayable","type":"function"}]Contract Creation Code
0x6101806040523480156200001257600080fd5b50604051620019c8380380620019c88339810160408190526200003591620004bf565b88806001600160a01b0381166200006f57604051636a15cc3160e01b81526001600160a01b03821660048201526024015b60405180910390fd5b6001600160a01b03811660808190526040519081527fe3162ce634ee4c6e39c868aa130f44228244e7469c577a852dd02e9fd9cb59c39060200160405180910390a150506001600160a01b038816620000e75760405163025e481f60e51b81526001600160a01b038916600482015260240162000066565b6001600160a01b0387166200011a57604051627fcf7960e61b81526001600160a01b038816600482015260240162000066565b6001600160a01b0386166200014e57604051635a7a234960e01b81526001600160a01b038716600482015260240162000066565b856001600160a01b0316876001600160a01b03160362000181576040516340ccdec360e11b815260040160405180910390fd5b6001600160a01b038516620001b45760405162aad6f760e71b81526001600160a01b038616600482015260240162000066565b6001600160a01b038416620001e857604051630b73f99760e01b81526001600160a01b038516600482015260240162000066565b62015180831180620001fa5750603c83105b156200022d57604051630e4a36cb60e21b8152603c60048201526201518060248201526044810184905260640162000066565b6103e88211156200025d57604051634ad128f360e01b81526103e860048201526024810183905260440162000066565b6103e88111156200028d5760405163bcb1876f60e01b81526103e860048201526024810182905260440162000066565b600080546001600160a01b0319166001600160a01b038a811691821790925585821660c05286821660a05288821660e052908716610100526101208490526101408390526101608290526040519081527f60a0f5b9f9e81e98216071b85826681c796256fe3d1354ecb675580fba64fa699060200160405180910390a16040516001600160a01b03861681527f63a73c130bebaad8801cdfdf4eecc43f1dcf2b507a609a5bc665c8451c4ca41b9060200160405180910390a16040516001600160a01b03851681527f18ead8355efb59c6402c03d9f7a3aadc3e56d48479a7db9244825e3d149b07089060200160405180910390a16040516001600160a01b03881681527f2fb86b49b4aa824bcacbf4ff2191826c227bac873f9b7cfcdeec728064c3e0a29060200160405180910390a16040516001600160a01b03871681527f60123f2b6b34d48a324d65ede4be211a3b8b8877421e3051ac0d655dba6391019060200160405180910390a16040518381527f42002ddce64ec2be80e88c3bd0084d9c1d60e2cb6fe942c013f8c0ee3373443c9060200160405180910390a16040518281527f39ff8269a6bdfbe3351909418e694ced3961809b803dd94afd73c76915d238459060200160405180910390a16040518181527f97e9376632ae25d4f7d428b1e3ef529c80ca17896f0d5830ec48f18287ba23579060200160405180910390a15050505050505050506200055f565b80516001600160a01b0381168114620004ba57600080fd5b919050565b60008060008060008060008060006101208a8c031215620004df57600080fd5b620004ea8a620004a2565b9850620004fa60208b01620004a2565b97506200050a60408b01620004a2565b96506200051a60608b01620004a2565b95506200052a60808b01620004a2565b94506200053a60a08b01620004a2565b935060c08a0151925060e08a015191506101008a015190509295985092959850929598565b60805160a05160c05160e0516101005161012051610140516101605161134d6200067b6000396000818161026201526103550152600081816102970152610d5d0152600081816101800152610391015260008181610159015281816101b80152610cb4015260008181610134015281816101f7015281816109fc01528181610ad701528181610c8c0152610dbf01526000818161031e0152610aa40152600081816102d10152610ce6015260008181610231015281816103d901528181610449015281816104b9015281816105290152818161060f015281816106a90152818161070b01528181610781015281816107ee01528181610868015281816108d0015281816108f7015281816109670152610bbb015261134d6000f3fe608060405234801561001057600080fd5b50600436106101215760003560e01c806368495ae0116100ad578063d0a07a7211610071578063d0a07a7214610353578063d0ebdbe714610379578063d2dfeba41461038c578063ebfb8e0d146103b3578063f0c2684b146103c657600080fd5b806368495ae0146102cc578063819d4cc6146102f35780638980f11f146103065780639d70be0214610319578063ba2255f41461034057600080fd5b80634f86473d116100f45780634f86473d1461022c57806352d8bfc214610253578063554d0b0f1461025d5780635588b4eb146102925780635c654ad9146102b957600080fd5b80630bac03931461012657806325802d1f146101b35780633224c271146101f2578063481c6a7514610219575b600080fd5b604080516001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811682527f00000000000000000000000000000000000000000000000000000000000000001660208201527f0000000000000000000000000000000000000000000000000000000000000000918101919091526060015b60405180910390f35b6101da7f000000000000000000000000000000000000000000000000000000000000000081565b6040516001600160a01b0390911681526020016101aa565b6101da7f000000000000000000000000000000000000000000000000000000000000000081565b6000546101da906001600160a01b031681565b6101da7f000000000000000000000000000000000000000000000000000000000000000081565b61025b6103ce565b005b6102847f000000000000000000000000000000000000000000000000000000000000000081565b6040519081526020016101aa565b6102847f000000000000000000000000000000000000000000000000000000000000000081565b61025b6102c73660046111a3565b61051e565b6101da7f000000000000000000000000000000000000000000000000000000000000000081565b61025b6103013660046111a3565b610700565b61025b6103143660046111a3565b61085d565b6101da7f000000000000000000000000000000000000000000000000000000000000000081565b6101da61034e3660046111cd565b61095a565b7f0000000000000000000000000000000000000000000000000000000000000000610284565b61025b6103873660046111e6565b610bb0565b6102847f000000000000000000000000000000000000000000000000000000000000000081565b6102846103c13660046111cd565b610c4f565b610284610d9d565b336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480159061041257506000546001600160a01b03163314155b1561043757604051634480485b60e01b81523360048201526024015b60405180910390fd5b60405147906000906001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000169083908381818185875af1925050503d80600081146104a4576040519150601f19603f3d011682016040523d82523d6000602084013e6104a9565b606091505b50509050806104b757600080fd5b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03167f8e274e42262a7f013b700b35c2b4629ccce1702f8fe83f8dfb7eacbb26a4382c8360405161051291815260200190565b60405180910390a25050565b336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480159061056257506000546001600160a01b03163314155b1561058257604051634480485b60e01b815233600482015260240161042e565b604051627eeac760e11b8152306004820152602481018290526000906001600160a01b0384169062fdd58e90604401602060405180830381865afa1580156105ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105f29190611201565b604051637921219560e11b81523060048201526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166024830152604482018590526064820183905260a06084830152600060a48301529192509084169063f242432a9060c401600060405180830381600087803b15801561067b57600080fd5b505af115801561068f573d6000803e3d6000fd5b505060408051858152602081018590526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081169450871692507f5cf02e753b3eb0f4bee4460a72817d8e5e3c75cd4d65c1d0b06dca88b8032936910160405180910390a3505050565b336001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000161480159061074457506000546001600160a01b03163314155b1561076457604051634480485b60e01b815233600482015260240161042e565b604051632142170760e11b81523060048201526001600160a01b037f000000000000000000000000000000000000000000000000000000000000000081166024830152604482018390528316906342842e0e90606401600060405180830381600087803b1580156107d457600080fd5b505af11580156107e8573d6000803e3d6000fd5b505050507f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316826001600160a01b03167f8166bf75d2ff2fa3c8f3c44410540bf42e9a5359b48409e8d660291dc9f788c88360405161085191815260200190565b60405180910390a35050565b336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016148015906108a157506000546001600160a01b03163314155b156108c157604051634480485b60e01b815233600482015260240161042e565b6108f56001600160a01b0383167f000000000000000000000000000000000000000000000000000000000000000083610e3b565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316826001600160a01b03167faca8fb252cde442184e5f10e0f2e6e4029e8cd7717cae63559079610702436aa8360405161085191815260200190565b6000336001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016148015906109a057506000546001600160a01b03163314155b156109c057604051634480485b60e01b815233600482015260240161042e565b816000036109e457604051633728b83d60e01b81526004810183905260240161042e565b6040516370a0823160e01b81523060048201526000907f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316906370a0823190602401602060405180830381865afa158015610a4b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a6f9190611201565b9050600a811015610a9d5760405163f3bd53eb60e01b8152600a60048201526024810182905260440161042e565b6000610ac87f0000000000000000000000000000000000000000000000000000000000000000610e92565b9050610afe6001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000168284610e3b565b60005460405163da35a26f60e01b8152600481018690526001600160a01b0391821660248201529082169063da35a26f90604401600060405180830381600087803b158015610b4c57600080fd5b505af1158015610b60573d6000803e3d6000fd5b50505050806001600160a01b03167f96a6d5477fba36522dca4102be8b3785435baf902ef6c4edebcb99850630c75f85604051610b9f91815260200190565b60405180910390a29150505b919050565b336001600160a01b037f00000000000000000000000000000000000000000000000000000000000000001614610bfb576040516352f49c9560e01b815233600482015260240161042e565b600080546001600160a01b0319166001600160a01b0383169081179091556040519081527f60a0f5b9f9e81e98216071b85826681c796256fe3d1354ecb675580fba64fa699060200160405180910390a150565b600081600003610c7557604051633728b83d60e01b81526004810183905260240161042e565b60405163089941cf60e01b81526001600160a01b037f0000000000000000000000000000000000000000000000000000000000000000811660048301527f000000000000000000000000000000000000000000000000000000000000000081166024830152604482018490526000917f00000000000000000000000000000000000000000000000000000000000000009091169063089941cf90606401602060405180830381865afa158015610d2f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d539190611201565b9050612710610d827f000000000000000000000000000000000000000000000000000000000000000082611230565b610d8c9083611249565b610d969190611260565b9392505050565b6040516370a0823160e01b815230600482015260009081906001600160a01b037f000000000000000000000000000000000000000000000000000000000000000016906370a0823190602401602060405180830381865afa158015610e06573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e2a9190611201565b9050610e3581610c4f565b91505090565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610e8d908490610f27565b505050565b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008260601b60e81c176000526e5af43d82803e903d91602b57fd5bf38260781b17602052603760096000f090506001600160a01b038116610bab5760405162461bcd60e51b8152602060048201526016602482015275115490cc4c4d8dce8818dc99585d194819985a5b195960521b604482015260640161042e565b6000610f7c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610ffc9092919063ffffffff16565b9050805160001480610f9d575080806020019051810190610f9d9190611282565b610e8d5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161042e565b606061100b8484600085611013565b949350505050565b6060824710156110745760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161042e565b600080866001600160a01b0316858760405161109091906112c8565b60006040518083038185875af1925050503d80600081146110cd576040519150601f19603f3d011682016040523d82523d6000602084013e6110d2565b606091505b50915091506110e3878383876110ee565b979650505050505050565b6060831561115d578251600003611156576001600160a01b0385163b6111565760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161042e565b508161100b565b61100b83838151156111725781518083602001fd5b8060405162461bcd60e51b815260040161042e91906112e4565b80356001600160a01b0381168114610bab57600080fd5b600080604083850312156111b657600080fd5b6111bf8361118c565b946020939093013593505050565b6000602082840312156111df57600080fd5b5035919050565b6000602082840312156111f857600080fd5b610d968261118c565b60006020828403121561121357600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b818103818111156112435761124361121a565b92915050565b80820281158282048414176112435761124361121a565b60008261127d57634e487b7160e01b600052601260045260246000fd5b500490565b60006020828403121561129457600080fd5b81518015158114610d9657600080fd5b60005b838110156112bf5781810151838201526020016112a7565b50506000910152565b600082516112da8184602087016112a4565b9190910192915050565b60208152600082518060208401526113038160408501602087016112a4565b601f01601f1916919091016040019291505056fea264697066735822122096e3702fd8a77ec38af60f5e628a45a6d226d268a09a14ac7c12bc4d447b824e64736f6c634300081700330000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c000000000000000000000000a02fc823cce0d016bd7e17ac684c9abab2d6d647000000000000000000000000ae7ab96520de3a18e5e111b5eaab095312d7fe840000000000000000000000006b175474e89094c44da98b954eedeac495271d0f00000000000000000000000012cc60eea45f705f069b43095fbf2fb3c7f874c10000000000000000000000002cb20c0223a159dd861c76eceb419c6030a4c9c20000000000000000000000000000000000000000000000000000000000000708000000000000000000000000000000000000000000000000000000000000006e0000000000000000000000000000000000000000000000000000000000000226
Deployed Bytecode
0x608060405234801561001057600080fd5b50600436106101215760003560e01c806368495ae0116100ad578063d0a07a7211610071578063d0a07a7214610353578063d0ebdbe714610379578063d2dfeba41461038c578063ebfb8e0d146103b3578063f0c2684b146103c657600080fd5b806368495ae0146102cc578063819d4cc6146102f35780638980f11f146103065780639d70be0214610319578063ba2255f41461034057600080fd5b80634f86473d116100f45780634f86473d1461022c57806352d8bfc214610253578063554d0b0f1461025d5780635588b4eb146102925780635c654ad9146102b957600080fd5b80630bac03931461012657806325802d1f146101b35780633224c271146101f2578063481c6a7514610219575b600080fd5b604080516001600160a01b037f000000000000000000000000ae7ab96520de3a18e5e111b5eaab095312d7fe84811682527f0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f1660208201527f0000000000000000000000000000000000000000000000000000000000000708918101919091526060015b60405180910390f35b6101da7f0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f81565b6040516001600160a01b0390911681526020016101aa565b6101da7f000000000000000000000000ae7ab96520de3a18e5e111b5eaab095312d7fe8481565b6000546101da906001600160a01b031681565b6101da7f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c81565b61025b6103ce565b005b6102847f000000000000000000000000000000000000000000000000000000000000022681565b6040519081526020016101aa565b6102847f000000000000000000000000000000000000000000000000000000000000006e81565b61025b6102c73660046111a3565b61051e565b6101da7f00000000000000000000000012cc60eea45f705f069b43095fbf2fb3c7f874c181565b61025b6103013660046111a3565b610700565b61025b6103143660046111a3565b61085d565b6101da7f0000000000000000000000002cb20c0223a159dd861c76eceb419c6030a4c9c281565b6101da61034e3660046111cd565b61095a565b7f0000000000000000000000000000000000000000000000000000000000000226610284565b61025b6103873660046111e6565b610bb0565b6102847f000000000000000000000000000000000000000000000000000000000000070881565b6102846103c13660046111cd565b610c4f565b610284610d9d565b336001600160a01b037f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c161480159061041257506000546001600160a01b03163314155b1561043757604051634480485b60e01b81523360048201526024015b60405180910390fd5b60405147906000906001600160a01b037f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c169083908381818185875af1925050503d80600081146104a4576040519150601f19603f3d011682016040523d82523d6000602084013e6104a9565b606091505b50509050806104b757600080fd5b7f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c6001600160a01b03167f8e274e42262a7f013b700b35c2b4629ccce1702f8fe83f8dfb7eacbb26a4382c8360405161051291815260200190565b60405180910390a25050565b336001600160a01b037f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c161480159061056257506000546001600160a01b03163314155b1561058257604051634480485b60e01b815233600482015260240161042e565b604051627eeac760e11b8152306004820152602481018290526000906001600160a01b0384169062fdd58e90604401602060405180830381865afa1580156105ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906105f29190611201565b604051637921219560e11b81523060048201526001600160a01b037f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c81166024830152604482018590526064820183905260a06084830152600060a48301529192509084169063f242432a9060c401600060405180830381600087803b15801561067b57600080fd5b505af115801561068f573d6000803e3d6000fd5b505060408051858152602081018590526001600160a01b037f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c81169450871692507f5cf02e753b3eb0f4bee4460a72817d8e5e3c75cd4d65c1d0b06dca88b8032936910160405180910390a3505050565b336001600160a01b037f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c161480159061074457506000546001600160a01b03163314155b1561076457604051634480485b60e01b815233600482015260240161042e565b604051632142170760e11b81523060048201526001600160a01b037f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c81166024830152604482018390528316906342842e0e90606401600060405180830381600087803b1580156107d457600080fd5b505af11580156107e8573d6000803e3d6000fd5b505050507f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c6001600160a01b0316826001600160a01b03167f8166bf75d2ff2fa3c8f3c44410540bf42e9a5359b48409e8d660291dc9f788c88360405161085191815260200190565b60405180910390a35050565b336001600160a01b037f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c16148015906108a157506000546001600160a01b03163314155b156108c157604051634480485b60e01b815233600482015260240161042e565b6108f56001600160a01b0383167f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c83610e3b565b7f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c6001600160a01b0316826001600160a01b03167faca8fb252cde442184e5f10e0f2e6e4029e8cd7717cae63559079610702436aa8360405161085191815260200190565b6000336001600160a01b037f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c16148015906109a057506000546001600160a01b03163314155b156109c057604051634480485b60e01b815233600482015260240161042e565b816000036109e457604051633728b83d60e01b81526004810183905260240161042e565b6040516370a0823160e01b81523060048201526000907f000000000000000000000000ae7ab96520de3a18e5e111b5eaab095312d7fe846001600160a01b0316906370a0823190602401602060405180830381865afa158015610a4b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a6f9190611201565b9050600a811015610a9d5760405163f3bd53eb60e01b8152600a60048201526024810182905260440161042e565b6000610ac87f0000000000000000000000002cb20c0223a159dd861c76eceb419c6030a4c9c2610e92565b9050610afe6001600160a01b037f000000000000000000000000ae7ab96520de3a18e5e111b5eaab095312d7fe84168284610e3b565b60005460405163da35a26f60e01b8152600481018690526001600160a01b0391821660248201529082169063da35a26f90604401600060405180830381600087803b158015610b4c57600080fd5b505af1158015610b60573d6000803e3d6000fd5b50505050806001600160a01b03167f96a6d5477fba36522dca4102be8b3785435baf902ef6c4edebcb99850630c75f85604051610b9f91815260200190565b60405180910390a29150505b919050565b336001600160a01b037f0000000000000000000000003e40d73eb977dc6a537af587d48316fee66e9c8c1614610bfb576040516352f49c9560e01b815233600482015260240161042e565b600080546001600160a01b0319166001600160a01b0383169081179091556040519081527f60a0f5b9f9e81e98216071b85826681c796256fe3d1354ecb675580fba64fa699060200160405180910390a150565b600081600003610c7557604051633728b83d60e01b81526004810183905260240161042e565b60405163089941cf60e01b81526001600160a01b037f000000000000000000000000ae7ab96520de3a18e5e111b5eaab095312d7fe84811660048301527f0000000000000000000000006b175474e89094c44da98b954eedeac495271d0f81166024830152604482018490526000917f00000000000000000000000012cc60eea45f705f069b43095fbf2fb3c7f874c19091169063089941cf90606401602060405180830381865afa158015610d2f573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d539190611201565b9050612710610d827f000000000000000000000000000000000000000000000000000000000000006e82611230565b610d8c9083611249565b610d969190611260565b9392505050565b6040516370a0823160e01b815230600482015260009081906001600160a01b037f000000000000000000000000ae7ab96520de3a18e5e111b5eaab095312d7fe8416906370a0823190602401602060405180830381865afa158015610e06573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e2a9190611201565b9050610e3581610c4f565b91505090565b604080516001600160a01b038416602482015260448082018490528251808303909101815260649091019091526020810180516001600160e01b031663a9059cbb60e01b179052610e8d908490610f27565b505050565b6000763d602d80600a3d3981f3363d3d373d3d3d363d730000008260601b60e81c176000526e5af43d82803e903d91602b57fd5bf38260781b17602052603760096000f090506001600160a01b038116610bab5760405162461bcd60e51b8152602060048201526016602482015275115490cc4c4d8dce8818dc99585d194819985a5b195960521b604482015260640161042e565b6000610f7c826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316610ffc9092919063ffffffff16565b9050805160001480610f9d575080806020019051810190610f9d9190611282565b610e8d5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b606482015260840161042e565b606061100b8484600085611013565b949350505050565b6060824710156110745760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b606482015260840161042e565b600080866001600160a01b0316858760405161109091906112c8565b60006040518083038185875af1925050503d80600081146110cd576040519150601f19603f3d011682016040523d82523d6000602084013e6110d2565b606091505b50915091506110e3878383876110ee565b979650505050505050565b6060831561115d578251600003611156576001600160a01b0385163b6111565760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161042e565b508161100b565b61100b83838151156111725781518083602001fd5b8060405162461bcd60e51b815260040161042e91906112e4565b80356001600160a01b0381168114610bab57600080fd5b600080604083850312156111b657600080fd5b6111bf8361118c565b946020939093013593505050565b6000602082840312156111df57600080fd5b5035919050565b6000602082840312156111f857600080fd5b610d968261118c565b60006020828403121561121357600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b818103818111156112435761124361121a565b92915050565b80820281158282048414176112435761124361121a565b60008261127d57634e487b7160e01b600052601260045260246000fd5b500490565b60006020828403121561129457600080fd5b81518015158114610d9657600080fd5b60005b838110156112bf5781810151838201526020016112a7565b50506000910152565b600082516112da8184602087016112a4565b9190910192915050565b60208152600082518060208401526113038160408501602087016112a4565b601f01601f1916919091016040019291505056fea264697066735822122096e3702fd8a77ec38af60f5e628a45a6d226d268a09a14ac7c12bc4d447b824e64736f6c63430008170033
Loading...
Loading
Loading...
Loading
Net Worth in USD
$0.00
Net Worth in ETH
0
Multichain Portfolio | 35 Chains
| Chain | Token | Portfolio % | Price | Amount | Value |
|---|
Loading...
Loading
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.