Overview
ETH Balance
ETH Value
$0.00More Info
Private Name Tags
ContractCreator
TokenTracker
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Latest 1 internal transaction
Parent Transaction Hash | Block | From | To | |||
---|---|---|---|---|---|---|
9127506 | 226 days ago | Contract Creation | 0 ETH |
Loading...
Loading
Similar Match Source Code This contract matches the deployed Bytecode of the Source Code for Contract 0x50c67343...Dac276FCc The constructor portion of the code might be different and could alter the actual behaviour of the contract
Contract Name:
SPumpToken
Compiler Version
v0.8.25+commit.b61c2a91
Optimization Enabled:
Yes with 200 runs
Other Settings:
paris EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.25; import {ERC20} from "solmate/src/tokens/ERC20.sol"; import {SPumpFoundry} from "./SPumpFoundry.sol"; error NotSPumpFoundry(); error Forbidden(); /// @title The SPump protocol ERC20 token template. /// @author strobie <@0xstrobe> /// @notice Until graduation, the token allowance is restricted to only the SPumpFoundry, and transfers to certain external entities are not /// allowed (eg. Uniswap pairs). This makes sure the token is transferable but not tradable before graduation. contract SPumpToken is ERC20 { struct Metadata { SPumpToken token; string name; string symbol; string description; string extended; address creator; bool isGraduated; uint256 mcap; } string public description; string public extended; SPumpFoundry public immutable sPumpFoundry; address public immutable creator; address[] public holders; mapping(address => bool) public isHolder; /// @notice Locked before graduation to restrict trading to SPumpFoundry bool public isUnrestricted = false; constructor( string memory _name, string memory _symbol, uint8 _decimals, uint256 _supply, string memory _description, string memory _extended, address _sPumpFoundry, address _creator ) ERC20(_name, _symbol, _decimals) { description = _description; extended = _extended; sPumpFoundry = SPumpFoundry(_sPumpFoundry); creator = _creator; _mint(msg.sender, _supply); _addHolder(msg.sender); } function _addHolder(address holder) private { if (!isHolder[holder]) { holders.push(holder); isHolder[holder] = true; } } function getMetadata() public view returns (Metadata memory) { SPumpFoundry.Pool memory pool = sPumpFoundry.getPool(this); return Metadata( SPumpToken(address(this)), this.name(), this.symbol(), description, extended, creator, isGraduated(), pool.lastMcapInEth ); } function isGraduated() public view returns (bool) { SPumpFoundry.Pool memory pool = sPumpFoundry.getPool(this); return pool.headmaster != address(0); } function setIsUnrestricted(bool _isUnrestricted) public { if (msg.sender != address(sPumpFoundry)) revert NotSPumpFoundry(); isUnrestricted = _isUnrestricted; } function transfer( address to, uint256 amount ) public override returns (bool) { if (!isUnrestricted) { bool isPregradRestricted = sPumpFoundry .externalEntities_() .isPregradRestricted(address(this), address(to)); if (isPregradRestricted) revert Forbidden(); } _addHolder(to); return super.transfer(to, amount); } function transferFrom( address from, address to, uint256 amount ) public override returns (bool) { if (!isUnrestricted) { bool isPregradRestricted = sPumpFoundry .externalEntities_() .isPregradRestricted(address(this), address(to)); if (isPregradRestricted) revert Forbidden(); } // Pre-approve SPumpFoundry for improved UX if (allowance[from][address(sPumpFoundry)] != type(uint256).max) { allowance[from][address(sPumpFoundry)] = type(uint256).max; } _addHolder(to); return super.transferFrom(from, to, amount); } function approve( address spender, uint256 amount ) public override returns (bool) { if (!isUnrestricted) revert Forbidden(); return super.approve(spender, amount); } function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public override { if (!isUnrestricted) revert Forbidden(); super.permit(owner, spender, value, deadline, v, r, s); } /// Get all addresses who have ever held the token with their balances /// @return The holders and their balances /// @notice Some holders may have a zero balance function getHoldersWithBalance( uint256 offset, uint256 limit ) public view returns (address[] memory, uint256[] memory) { uint256 length = holders.length; if (offset >= length) { return (new address[](0), new uint256[](0)); } uint256 end = offset + limit; if (end > length) { end = length; } address[] memory resultAddresses = new address[](end - offset); uint256[] memory resultBalances = new uint256[](end - offset); for (uint256 i = offset; i < end; i++) { address holder = holders[i]; resultAddresses[i - offset] = holder; resultBalances[i - offset] = balanceOf[holder]; } return (resultAddresses, resultBalances); } /// Get all addresses who have ever held the token /// @return The holders /// @notice Some holders may have a zero balance function getHolders( uint256 offset, uint256 limit ) public view returns (address[] memory) { uint256 length = holders.length; if (offset >= length) { return new address[](0); } uint256 end = offset + limit; if (end > length) { end = length; } address[] memory result = new address[](end - offset); for (uint256 i = offset; i < end; i++) { result[i - offset] = holders[i]; } return result; } /// Get the number of all addresses who have ever held the token /// @return The number of holders /// @notice Some holders may have a zero balance function getHoldersLength() public view returns (uint256) { return holders.length; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.20; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Storage of the initializable contract. * * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions * when using with upgradeable contracts. * * @custom:storage-location erc7201:openzeppelin.storage.Initializable */ struct InitializableStorage { /** * @dev Indicates that the contract has been initialized. */ uint64 _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool _initializing; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00; /** * @dev The contract is already initialized. */ error InvalidInitialization(); /** * @dev The contract is not initializing. */ error NotInitializing(); /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint64 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in * production. * * Emits an {Initialized} event. */ modifier initializer() { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); // Cache values to avoid duplicated sloads bool isTopLevelCall = !$._initializing; uint64 initialized = $._initialized; // Allowed calls: // - initialSetup: the contract is not in the initializing state and no previous version was // initialized // - construction: the contract is initialized at version 1 (no reininitialization) and the // current contract is just being deployed bool initialSetup = initialized == 0 && isTopLevelCall; bool construction = initialized == 1 && address(this).code.length == 0; if (!initialSetup && !construction) { revert InvalidInitialization(); } $._initialized = 1; if (isTopLevelCall) { $._initializing = true; } _; if (isTopLevelCall) { $._initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint64 version) { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing || $._initialized >= version) { revert InvalidInitialization(); } $._initialized = version; $._initializing = true; _; $._initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { _checkInitializing(); _; } /** * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}. */ function _checkInitializing() internal view virtual { if (!_isInitializing()) { revert NotInitializing(); } } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing) { revert InvalidInitialization(); } if ($._initialized != type(uint64).max) { $._initialized = type(uint64).max; emit Initialized(type(uint64).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint64) { return _getInitializableStorage()._initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _getInitializableStorage()._initializing; } /** * @dev Returns a pointer to the storage namespace. */ // solhint-disable-next-line var-name-mixedcase function _getInitializableStorage() private pure returns (InitializableStorage storage $) { assembly { $.slot := INITIALIZABLE_STORAGE } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = 2; /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard struct ReentrancyGuardStorage { uint256 _status; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00; function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) { assembly { $.slot := ReentrancyGuardStorageLocation } } /** * @dev Unauthorized reentrant call. */ error ReentrancyGuardReentrantCall(); function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); $._status = NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); // On the first call to nonReentrant, _status will be NOT_ENTERED if ($._status == ENTERED) { revert ReentrancyGuardReentrantCall(); } // Any calls to nonReentrant after this point will fail $._status = ENTERED; } function _nonReentrantAfter() private { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) $._status = NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); return $._status == ENTERED; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol) pragma solidity ^0.8.20; /** * @dev Standard ERC20 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens. */ interface IERC20Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC20InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC20InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. * @param spender Address that may be allowed to operate on tokens without being their owner. * @param allowance Amount of tokens a `spender` is allowed to operate with. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC20InvalidApprover(address approver); /** * @dev Indicates a failure with the `spender` to be approved. Used in approvals. * @param spender Address that may be allowed to operate on tokens without being their owner. */ error ERC20InvalidSpender(address spender); } /** * @dev Standard ERC721 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens. */ interface IERC721Errors { /** * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20. * Used in balance queries. * @param owner Address of the current owner of a token. */ error ERC721InvalidOwner(address owner); /** * @dev Indicates a `tokenId` whose `owner` is the zero address. * @param tokenId Identifier number of a token. */ error ERC721NonexistentToken(uint256 tokenId); /** * @dev Indicates an error related to the ownership over a particular token. Used in transfers. * @param sender Address whose tokens are being transferred. * @param tokenId Identifier number of a token. * @param owner Address of the current owner of a token. */ error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC721InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC721InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param tokenId Identifier number of a token. */ error ERC721InsufficientApproval(address operator, uint256 tokenId); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC721InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC721InvalidOperator(address operator); } /** * @dev Standard ERC1155 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens. */ interface IERC1155Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. * @param tokenId Identifier number of a token. */ error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC1155InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC1155InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param owner Address of the current owner of a token. */ error ERC1155MissingApprovalForAll(address operator, address owner); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC1155InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC1155InvalidOperator(address operator); /** * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. * Used in batch transfers. * @param idsLength Length of the array of token identifiers * @param valuesLength Length of the array of token amounts */ error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol) pragma solidity ^0.8.20; interface IERC5267 { /** * @dev MAY be emitted to signal that the domain could have changed. */ event EIP712DomainChanged(); /** * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712 * signature. */ function eip712Domain() external view returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "./IERC20.sol"; import {IERC20Metadata} from "./extensions/IERC20Metadata.sol"; import {Context} from "../../utils/Context.sol"; import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. */ abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors { mapping(address account => uint256) private _balances; mapping(address account => mapping(address spender => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows _totalSupply += value; } else { uint256 fromBalance = _balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. _balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. _totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. _balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address owner, address spender, uint256 value) internal { _approve(owner, spender, value, true); } /** * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to * true using the following override: * ``` * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } _allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner` s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Does not emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol) pragma solidity ^0.8.20; import {IERC20Permit} from "./IERC20Permit.sol"; import {ERC20} from "../ERC20.sol"; import {ECDSA} from "../../../utils/cryptography/ECDSA.sol"; import {EIP712} from "../../../utils/cryptography/EIP712.sol"; import {Nonces} from "../../../utils/Nonces.sol"; /** * @dev Implementation 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. */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces { bytes32 private constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Permit deadline has expired. */ error ERC2612ExpiredSignature(uint256 deadline); /** * @dev Mismatched signature. */ error ERC2612InvalidSigner(address signer, address owner); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @inheritdoc IERC20Permit */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { if (block.timestamp > deadline) { revert ERC2612ExpiredSignature(deadline); } bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); if (signer != owner) { revert ERC2612InvalidSigner(signer, owner); } _approve(owner, spender, value); } /** * @inheritdoc IERC20Permit */ function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) { return super.nonces(owner); } /** * @inheritdoc IERC20Permit */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view virtual returns (bytes32) { return _domainSeparatorV4(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * ==== Security Considerations * * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be * considered as an intention to spend the allowance in any specific way. The second is that because permits have * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be * generally recommended is: * * ```solidity * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} * doThing(..., value); * } * * function doThing(..., uint256 value) public { * token.safeTransferFrom(msg.sender, address(this), value); * ... * } * ``` * * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also * {SafeERC20-safeTransferFrom}). * * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so * contracts should have entry points that don't rely on permit. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. * * CAUTION: See Security Considerations above. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the value of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the value of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves a `value` amount of tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the * allowance mechanism. `value` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 value) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.20; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS } /** * @dev The signature derives the `address(0)`. */ error ECDSAInvalidSignature(); /** * @dev The signature has an invalid length. */ error ECDSAInvalidSignatureLength(uint256 length); /** * @dev The signature has an S value that is in the upper half order. */ error ECDSAInvalidSignatureS(bytes32 s); /** * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not * return address(0) without also returning an error description. Errors are documented using an enum (error type) * and a bytes32 providing additional information about the error. * * If no error is returned, then the address can be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length)); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] */ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) { unchecked { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); // We do not check for an overflow here since the shift operation results in 0 or 1. uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError, bytes32) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS, s); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature, bytes32(0)); } return (signer, RecoverError.NoError, bytes32(0)); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s); _throwError(error, errorArg); return recovered; } /** * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided. */ function _throwError(RecoverError error, bytes32 errorArg) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert ECDSAInvalidSignature(); } else if (error == RecoverError.InvalidSignatureLength) { revert ECDSAInvalidSignatureLength(uint256(errorArg)); } else if (error == RecoverError.InvalidSignatureS) { revert ECDSAInvalidSignatureS(errorArg); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol) pragma solidity ^0.8.20; import {MessageHashUtils} from "./MessageHashUtils.sol"; import {ShortStrings, ShortString} from "../ShortStrings.sol"; import {IERC5267} from "../../interfaces/IERC5267.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the * separator from the immutable values, which is cheaper than accessing a cached version in cold storage. * * @custom:oz-upgrades-unsafe-allow state-variable-immutable */ abstract contract EIP712 is IERC5267 { using ShortStrings for *; bytes32 private constant TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _cachedDomainSeparator; uint256 private immutable _cachedChainId; address private immutable _cachedThis; bytes32 private immutable _hashedName; bytes32 private immutable _hashedVersion; ShortString private immutable _name; ShortString private immutable _version; string private _nameFallback; string private _versionFallback; /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _name = name.toShortStringWithFallback(_nameFallback); _version = version.toShortStringWithFallback(_versionFallback); _hashedName = keccak256(bytes(name)); _hashedVersion = keccak256(bytes(version)); _cachedChainId = block.chainid; _cachedDomainSeparator = _buildDomainSeparator(); _cachedThis = address(this); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _cachedThis && block.chainid == _cachedChainId) { return _cachedDomainSeparator; } else { return _buildDomainSeparator(); } } function _buildDomainSeparator() private view returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev See {IERC-5267}. */ function eip712Domain() public view virtual returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ) { return ( hex"0f", // 01111 _EIP712Name(), _EIP712Version(), block.chainid, address(this), bytes32(0), new uint256[](0) ); } /** * @dev The name parameter for the EIP712 domain. * * NOTE: By default this function reads _name which is an immutable value. * It only reads from storage if necessary (in case the value is too large to fit in a ShortString). */ // solhint-disable-next-line func-name-mixedcase function _EIP712Name() internal view returns (string memory) { return _name.toStringWithFallback(_nameFallback); } /** * @dev The version parameter for the EIP712 domain. * * NOTE: By default this function reads _version which is an immutable value. * It only reads from storage if necessary (in case the value is too large to fit in a ShortString). */ // solhint-disable-next-line func-name-mixedcase function _EIP712Version() internal view returns (string memory) { return _version.toStringWithFallback(_versionFallback); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol) pragma solidity ^0.8.20; import {Strings} from "../Strings.sol"; /** * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing. * * The library provides methods for generating a hash of a message that conforms to the * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712] * specifications. */ library MessageHashUtils { /** * @dev Returns the keccak256 digest of an EIP-191 signed data with version * `0x45` (`personal_sign` messages). * * The digest is calculated by prefixing a bytes32 `messageHash` with * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method. * * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with * keccak256, although any bytes32 value can be safely used because the final digest will * be re-hashed. * * See {ECDSA-recover}. */ function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) { /// @solidity memory-safe-assembly assembly { mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20) } } /** * @dev Returns the keccak256 digest of an EIP-191 signed data with version * `0x45` (`personal_sign` messages). * * The digest is calculated by prefixing an arbitrary `message` with * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method. * * See {ECDSA-recover}. */ function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) { return keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message)); } /** * @dev Returns the keccak256 digest of an EIP-191 signed data with version * `0x00` (data with intended validator). * * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended * `validator` address. Then hashing the result. * * See {ECDSA-recover}. */ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { return keccak256(abi.encodePacked(hex"19_00", validator, data)); } /** * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`). * * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with * `\x19\x01` and hashing the result. It corresponds to the hash signed by the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712. * * See {ECDSA-recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, hex"19_01") mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) digest := keccak256(ptr, 0x42) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol) pragma solidity ^0.8.20; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Muldiv operation overflow. */ error MathOverflowedMulDiv(); enum Rounding { Floor, // Toward negative infinity Ceil, // Toward positive infinity Trunc, // Toward zero Expand // Away from zero } /** * @dev Returns the addition of two unsigned integers, with an overflow flag. */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an overflow flag. */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @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 towards infinity instead * of rounding towards zero. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { // Guarantee the same behavior as in a regular Solidity division. return a / b; } // (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 = x * y; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) 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. if (denominator <= prod1) { revert MathOverflowedMulDiv(); } /////////////////////////////////////////////// // 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. uint256 twos = denominator & (0 - denominator); 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 (unsignedRoundsUp(rounding) && 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 * towards zero. * * 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2 of a positive value rounded towards zero. * 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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10 of a positive value rounded towards zero. * 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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256 of a positive value rounded towards zero. * 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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0); } } /** * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers. */ function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) { return uint8(rounding) % 2 == 1; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.20; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol) pragma solidity ^0.8.20; /** * @dev Provides tracking nonces for addresses. Nonces will only increment. */ abstract contract Nonces { /** * @dev The nonce used for an `account` is not the expected current nonce. */ error InvalidAccountNonce(address account, uint256 currentNonce); mapping(address account => uint256) private _nonces; /** * @dev Returns the next unused nonce for an address. */ function nonces(address owner) public view virtual returns (uint256) { return _nonces[owner]; } /** * @dev Consumes a nonce. * * Returns the current value and increments nonce. */ function _useNonce(address owner) internal virtual returns (uint256) { // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be // decremented or reset. This guarantees that the nonce never overflows. unchecked { // It is important to do x++ and not ++x here. return _nonces[owner]++; } } /** * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`. */ function _useCheckedNonce(address owner, uint256 nonce) internal virtual { uint256 current = _useNonce(owner); if (nonce != current) { revert InvalidAccountNonce(owner, current); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol) pragma solidity ^0.8.20; import {StorageSlot} from "./StorageSlot.sol"; // | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | // | length | 0x BB | type ShortString is bytes32; /** * @dev This library provides functions to convert short memory strings * into a `ShortString` type that can be used as an immutable variable. * * Strings of arbitrary length can be optimized using this library if * they are short enough (up to 31 bytes) by packing them with their * length (1 byte) in a single EVM word (32 bytes). Additionally, a * fallback mechanism can be used for every other case. * * Usage example: * * ```solidity * contract Named { * using ShortStrings for *; * * ShortString private immutable _name; * string private _nameFallback; * * constructor(string memory contractName) { * _name = contractName.toShortStringWithFallback(_nameFallback); * } * * function name() external view returns (string memory) { * return _name.toStringWithFallback(_nameFallback); * } * } * ``` */ library ShortStrings { // Used as an identifier for strings longer than 31 bytes. bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF; error StringTooLong(string str); error InvalidShortString(); /** * @dev Encode a string of at most 31 chars into a `ShortString`. * * This will trigger a `StringTooLong` error is the input string is too long. */ function toShortString(string memory str) internal pure returns (ShortString) { bytes memory bstr = bytes(str); if (bstr.length > 31) { revert StringTooLong(str); } return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length)); } /** * @dev Decode a `ShortString` back to a "normal" string. */ function toString(ShortString sstr) internal pure returns (string memory) { uint256 len = byteLength(sstr); // using `new string(len)` would work locally but is not memory safe. string memory str = new string(32); /// @solidity memory-safe-assembly assembly { mstore(str, len) mstore(add(str, 0x20), sstr) } return str; } /** * @dev Return the length of a `ShortString`. */ function byteLength(ShortString sstr) internal pure returns (uint256) { uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF; if (result > 31) { revert InvalidShortString(); } return result; } /** * @dev Encode a string into a `ShortString`, or write it to storage if it is too long. */ function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) { if (bytes(value).length < 32) { return toShortString(value); } else { StorageSlot.getStringSlot(store).value = value; return ShortString.wrap(FALLBACK_SENTINEL); } } /** * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}. */ function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) { if (ShortString.unwrap(value) != FALLBACK_SENTINEL) { return toString(value); } else { return store; } } /** * @dev Return the length of a string that was encoded to `ShortString` or written to storage using * {setWithFallback}. * * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of * actual characters as the UTF-8 encoding of a single character can span over multiple bytes. */ function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) { if (ShortString.unwrap(value) != FALLBACK_SENTINEL) { return byteLength(value); } else { return bytes(store).length; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol) // This file was procedurally generated from scripts/generate/templates/StorageSlot.js. pragma solidity ^0.8.20; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ```solidity * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(newImplementation.code.length > 0); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } struct StringSlot { string value; } struct BytesSlot { bytes value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` representation of the string storage pointer `store`. */ function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } /** * @dev Returns an `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. */ function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol) pragma solidity ^0.8.20; import {Math} from "./math/Math.sol"; import {SignedMath} from "./math/SignedMath.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant HEX_DIGITS = "0123456789abcdef"; uint8 private constant ADDRESS_LENGTH = 20; /** * @dev The `value` string doesn't fit in the specified `length`. */ error StringsInsufficientHexLength(uint256 value, uint256 length); /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), HEX_DIGITS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toStringSigned(int256 value) internal pure returns (string memory) { return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { uint256 localValue = value; bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = HEX_DIGITS[localValue & 0xf]; localValue >>= 4; } if (localValue != 0) { revert StringsInsufficientHexLength(value, length); } return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal * representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b)); } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import { ERC20 } from "solmate/src/tokens/ERC20.sol"; import { SPumpFoundry } from "./SPumpFoundry.sol"; // import { IUniswapV2Factory } from "./interfaces/IUniswapV2Factory.sol"; import { ISyncSwapPoolFactory } from "./interfaces/ISyncSwapPoolFactory.sol"; import { SyncSwapClassicPool } from "./SyncSwap/pool/classic/SyncSwapClassicPool.sol"; error Forbidden(); /// @title External entities registry. Primarily used to check and restrict pre-graduation token transfers to specific entities like Uniswap V2 pairs. /// @author strobie <@0xstrobe> /// @notice Refer to the SPumpToken template contract to verify that the restriction is lifted after graduation. contract ExternalEntities { address public immutable weth; ISyncSwapPoolFactory[] public knownFactories; mapping(address => bool) public pregradRestricted; address public owner; constructor(address _owner, address _weth) { owner = _owner; weth = _weth; } function addFactory(address factory) external { if (msg.sender != owner) revert Forbidden(); knownFactories.push(ISyncSwapPoolFactory(payable(factory))); } function removeFactory(address factory) external { if (msg.sender != owner) revert Forbidden(); for (uint256 i = 0; i < knownFactories.length; i++) { if (address(knownFactories[i]) == factory) { knownFactories[i] = knownFactories[knownFactories.length - 1]; knownFactories.pop(); break; } } } function addPregradRestricted(address to) external { if (msg.sender != owner) revert Forbidden(); pregradRestricted[to] = true; } function removePregradRestricted(address to) external { if (msg.sender != owner) revert Forbidden(); pregradRestricted[to] = false; } function computePair(ISyncSwapPoolFactory factory, address tokenA, address tokenB) public view returns (address pair, bool exists) { pair = factory.getPool(tokenA, tokenB); if (pair != address(0)) { return (pair, true); } (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); // both uniswap and quickswap v2 are using the same init code hash pair = address( uint160( uint256( keccak256( abi.encodePacked( hex"ff", factory, keccak256(abi.encodePacked(token0, token1)), hex"4831994a03a6928d76606fac94ca2843f850764d7e96b9245de8ee7bb2c81e97" ) ) ) ) ); return (pair, false); } function isPregradRestricted(address token, address to) external view returns (bool) { for (uint256 i = 0; i < knownFactories.length; i++) { (address pair,) = computePair(knownFactories[i], token, weth); if (pair == to) { return true; } } return pregradRestricted[to]; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; interface ISyncSwapPool { struct TokenAmount { address token; uint amount; } /// @dev Returns the address of pool master. function master() external view returns (address); /// @dev Returns the vault. function vault() external view returns (address); // [Deprecated] This is the interface before the dynamic fees update. /// @dev Returns the pool type. function poolType() external view returns (uint16); /// @dev Returns the assets of the pool. function getAssets() external view returns (address[] memory assets); // [Deprecated] This is the interface before the dynamic fees update. /// @dev Returns the swap fee of the pool. // This function will forward calls to the pool master. // function getSwapFee() external view returns (uint24 swapFee); // [Recommended] This is the latest interface. /// @dev Returns the swap fee of the pool. /// This function will forward calls to the pool master. function getSwapFee( address sender, address tokenIn, address tokenOut, bytes calldata data ) external view returns (uint24 swapFee); /// @dev Returns the protocol fee of the pool. function getProtocolFee() external view returns (uint24 protocolFee); // [Deprecated] The old interface for Era testnet. /// @dev Mints liquidity. // The data for Classic and Stable Pool is as follows. // `address _to = abi.decode(_data, (address));` //function mint(bytes calldata data) external returns (uint liquidity); /// @dev Mints liquidity. function mint( bytes calldata data, address sender, address callback, bytes calldata callbackData ) external returns (uint liquidity); // [Deprecated] The old interface for Era testnet. /// @dev Burns liquidity. // The data for Classic and Stable Pool is as follows. // `(address _to, uint8 _withdrawMode) = abi.decode(_data, (address, uint8));` //function burn(bytes calldata data) external returns (TokenAmount[] memory amounts); /// @dev Burns liquidity. function burn( bytes calldata data, address sender, address callback, bytes calldata callbackData ) external returns (TokenAmount[] memory tokenAmounts); // [Deprecated] The old interface for Era testnet. /// @dev Burns liquidity with single output token. // The data for Classic and Stable Pool is as follows. // `(address _tokenOut, address _to, uint8 _withdrawMode) = abi.decode(_data, (address, address, uint8));` //function burnSingle(bytes calldata data) external returns (uint amountOut); /// @dev Burns liquidity with single output token. function burnSingle( bytes calldata data, address sender, address callback, bytes calldata callbackData ) external returns (TokenAmount memory tokenAmount); // [Deprecated] The old interface for Era testnet. /// @dev Swaps between tokens. // The data for Classic and Stable Pool is as follows. // `(address _tokenIn, address _to, uint8 _withdrawMode) = abi.decode(_data, (address, address, uint8));` //function swap(bytes calldata data) external returns (uint amountOut); /// @dev Swaps between tokens. function swap( bytes calldata data, address sender, address callback, bytes calldata callbackData ) external returns (TokenAmount memory tokenAmount); } // // The base interface, with two tokens and Liquidity Pool (LP) token. // interface IBasePool is ISyncSwapPool, IERC20Permit2 { // function token0() external view returns (address); // function token1() external view returns (address); // function reserve0() external view returns (uint); // function reserve1() external view returns (uint); // function invariantLast() external view returns (uint); // function getReserves() external view returns (uint, uint); // // [Deprecated] The old interface for Era testnet. // //function getAmountOut(address tokenIn, uint amountIn) external view returns (uint amountOut); // //function getAmountIn(address tokenOut, uint amountOut) external view returns (uint amountIn); // function getAmountOut(address tokenIn, uint amountIn, address sender) external view returns (uint amountOut); // function getAmountIn(address tokenOut, uint amountOut, address sender) external view returns (uint amountIn); // event Mint( // address indexed sender, // uint amount0, // uint amount1, // uint liquidity, // address indexed to // ); // event Burn( // address indexed sender, // uint amount0, // uint amount1, // uint liquidity, // address indexed to // ); // event Swap( // address indexed sender, // uint amount0In, // uint amount1In, // uint amount0Out, // uint amount1Out, // address indexed to // ); // event Sync( // uint reserve0, // uint reserve1 // ); // } // // The Classic Pool. // interface IClassicPool is IBasePool { // } // // The Stable Pool with the additional multiplier for pool tokens. // interface IStablePool is IBasePool { // function token0PrecisionMultiplier() external view returns (uint); // function token1PrecisionMultiplier() external view returns (uint); // } // // The interface of callback (optional). // interface ICallback { // struct BaseMintCallbackParams { // address sender; // address to; // uint reserve0; // uint reserve1; // uint balance0; // uint balance1; // uint amount0; // uint amount1; // uint fee0; // uint fee1; // uint newInvariant; // uint oldInvariant; // uint totalSupply; // uint liquidity; // uint24 swapFee; // bytes callbackData; // } // function syncSwapBaseMintCallback(BaseMintCallbackParams calldata params) external; // struct BaseBurnCallbackParams { // address sender; // address to; // uint balance0; // uint balance1; // uint liquidity; // uint totalSupply; // uint amount0; // uint amount1; // uint8 withdrawMode; // bytes callbackData; // } // function syncSwapBaseBurnCallback(BaseBurnCallbackParams calldata params) external; // struct BaseBurnSingleCallbackParams { // address sender; // address to; // address tokenIn; // address tokenOut; // uint balance0; // uint balance1; // uint liquidity; // uint totalSupply; // uint amount0; // uint amount1; // uint amountOut; // uint amountSwapped; // uint feeIn; // uint24 swapFee; // uint8 withdrawMode; // bytes callbackData; // } // function syncSwapBaseBurnSingleCallback(BaseBurnSingleCallbackParams calldata params) external; // struct BaseSwapCallbackParams { // address sender; // address to; // address tokenIn; // address tokenOut; // uint reserve0; // uint reserve1; // uint balance0; // uint balance1; // uint amountIn; // uint amountOut; // uint feeIn; // uint24 swapFee; // uint8 withdrawMode; // bytes callbackData; // } // function syncSwapBaseSwapCallback(BaseSwapCallbackParams calldata params) external; // }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; // The standard interface. interface IPoolFactory { function master() external view returns (address); function getDeployData() external view returns (bytes memory); // Call the function with data to create a pool. // For base pool factories, the data is as follows. // `(address tokenA, address tokenB) = abi.decode(data, (address, address));` function createPool(bytes calldata data) external returns (address pool); } // The interface for base pools has two tokens. interface ISyncSwapPoolFactory is IPoolFactory { event PoolCreated( address indexed token0, address indexed token1, address pool ); function getPool(address tokenA, address tokenB) external view returns (address pool); receive() external payable; // // [Deprecated] This is the interface before the dynamic fees update. // // This function will forward calls to the pool master. // //function getSwapFee(address pool) external view returns (uint24 swapFee); // // [Recommended] This is the latest interface. // // This function will forward calls to the pool master. // function getSwapFee( // address pool, // address sender, // address tokenIn, // address tokenOut, // bytes calldata data // ) external view override returns (uint24 swapFee) { // swapFee = IPoolMaster(master).getSwapFee(pool, sender, tokenIn, tokenOut, data); // } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.20; import { ISyncSwapPool } from "./ISyncSwapPool.sol"; interface ISyncSwapRouter { struct TokenInput { address token; uint amount; } struct SwapStep { address pool; // The pool of the step. bytes data; // The data to execute swap with the pool. address callback; bytes callbackData; } struct SwapPath { SwapStep[] steps; // Steps of the path. address tokenIn; // The input token of the path. uint amountIn; // The input token amount of the path. } struct SplitPermitParams { address token; uint approveAmount; uint deadline; uint8 v; bytes32 r; bytes32 s; } struct ArrayPermitParams { uint approveAmount; uint deadline; bytes signature; } // Returns the vault address. function vault() external view returns (address); // Returns the wETH address. function wETH() external view returns (address); function addLiquidity2( address pool, TokenInput[] calldata inputs, bytes calldata data, uint minLiquidity, address callback, bytes calldata callbackData ) external payable returns (uint liquidity); function addLiquidityWithPermit( address pool, TokenInput[] calldata inputs, bytes calldata data, uint minLiquidity, address callback, bytes calldata callbackData, SplitPermitParams[] memory permits ) external payable returns (uint liquidity); // Burns some liquidity (balanced). function burnLiquidity( address pool, uint liquidity, bytes calldata data, uint[] calldata minAmounts, address callback, bytes calldata callbackData ) external returns (ISyncSwapPool.TokenAmount[] memory amounts); // Burns some liquidity with permit (balanced). function burnLiquidityWithPermit( address pool, uint liquidity, bytes calldata data, uint[] calldata minAmounts, address callback, bytes calldata callbackData, ArrayPermitParams memory permit ) external returns (ISyncSwapPool.TokenAmount[] memory amounts); // Burns some liquidity (single). function burnLiquiditySingle( address pool, uint liquidity, bytes memory data, uint minAmount, address callback, bytes memory callbackData ) external returns (uint amountOut); // Burns some liquidity with permit (single). function burnLiquiditySingleWithPermit( address pool, uint liquidity, bytes memory data, uint minAmount, address callback, bytes memory callbackData, ArrayPermitParams calldata permit ) external returns (uint amountOut); // Performs a swap. function swap( SwapPath[] memory paths, uint amountOutMin, uint deadline ) external payable returns (uint amountOut); function swapWithPermit( SwapPath[] memory paths, uint amountOutMin, uint deadline, SplitPermitParams calldata permit ) external payable returns (uint amountOut); /// @notice Wrapper function to allow pool deployment to be batched. function createPool(address factory, bytes calldata data) external payable returns (address); receive() external payable; }
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.25; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import {FixedPointMathLib} from "solmate/src/utils/FixedPointMathLib.sol"; import {SafeTransferLib} from "solmate/src/utils/SafeTransferLib.sol"; import {SPumpToken} from "./SPumpToken.sol"; import {SPumpHeadmaster} from "./SPumpHeadmaster.sol"; import {SPumpLedger} from "./SPumpLedger.sol"; import {ExternalEntities} from "./ExternalEntities.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; error InsufficientOutput(); error InsufficientTokenReserve(); error InsufficientEthReserve(); error InsufficientMcap(); error TooMuchMcap(); error AlreadyGraduated(); error NotSPumpToken(); error DeadlineExceeded(); error InvalidAmountIn(); error Forbidden(); error FeeTooHigh(); error Paused(); /// @title The SPump protocol singleton AMM with a custom bonding curve built-in. /// @author strobie <@0xstrobe> /// @notice Owner can pause trading, set fees, and set the graduation strategy, but cannot withdraw funds or modify the bonding curve. contract SPumpFoundry is ReentrancyGuardUpgradeable { using FixedPointMathLib for uint256; struct Pool { SPumpToken token; uint256 tokenReserve; uint256 virtualTokenReserve; uint256 ethReserve; uint256 virtualEthReserve; uint256 lastPrice; uint256 lastMcapInEth; uint256 lastTimestamp; uint256 lastBlock; address creator; address headmaster; // poolId is not limited to address to support non-uniswap styled AMMs uint256 poolId; // K is never updated uint256 K; } uint8 public constant DECIMALS = 18; uint256 public constant FEE_DENOMINATOR = 10000; uint256 public constant MAX_FEE = 1000; // 10% uint256 public feeRate_; uint256 public constant INIT_VIRTUAL_TOKEN_RESERVE = 1073000000 ether; uint256 public constant INIT_REAL_TOKEN_RESERVE = 793100000 ether; uint256 public constant TOTAL_SUPPLY = 1000000000 ether; uint256 public initVirtualEthReserve_; uint256 public graduationThreshold_; uint256 public K_; mapping(SPumpToken => Pool) public pools_; SPumpLedger public sPumpLedger_; uint256 public creationFee_; uint256 public graduationFeeRate_; address public feeTo_; bool public paused_; SPumpHeadmaster public headmaster_; // the contract which implements the graduation logic ExternalEntities public externalEntities_; /*////////////////////////////////////////////////// ///////////// PERMISSIONED METHODS ///////////// //////////////////////////////////////////////////*/ address public owner_; modifier onlyOwner() { if (msg.sender != owner_) revert Forbidden(); _; } function setFeeTo(address feeTo) external onlyOwner { feeTo_ = feeTo; } function setFeeRate(uint256 feeRate) external onlyOwner { if (feeRate > MAX_FEE) revert FeeTooHigh(); feeRate_ = feeRate; } function setGraduationFeeRate(uint256 feeRate) external onlyOwner { if (feeRate > MAX_FEE) revert FeeTooHigh(); graduationFeeRate_ = feeRate; } function setInitVirtualEthReserve( uint256 initVirtualEthReserve ) external onlyOwner { initVirtualEthReserve_ = initVirtualEthReserve; K_ = initVirtualEthReserve_ * INIT_VIRTUAL_TOKEN_RESERVE; graduationThreshold_ = K_ / (INIT_VIRTUAL_TOKEN_RESERVE - INIT_REAL_TOKEN_RESERVE) - initVirtualEthReserve_; } function setCreationFee(uint256 fee) external onlyOwner { creationFee_ = fee; } function setHeadmaster(SPumpHeadmaster headmaster) external onlyOwner { headmaster_ = headmaster; } function setExternalEntities( ExternalEntities externalEntities ) external onlyOwner { externalEntities_ = externalEntities; } function setOwner(address owner) external onlyOwner { owner_ = owner; } function setPaused(bool paused) external onlyOwner { paused_ = paused; } /*////////////////////////////////////////////////// //////////////// CONSTRUCTOR /////////////////// //////////////////////////////////////////////////*/ function initialize(uint256 initVirtualEthReserve) public initializer { feeTo_ = msg.sender; owner_ = msg.sender; paused_ = false; sPumpLedger_ = new SPumpLedger(); initVirtualEthReserve_ = initVirtualEthReserve; K_ = initVirtualEthReserve_ * INIT_VIRTUAL_TOKEN_RESERVE; graduationThreshold_ = K_ / (INIT_VIRTUAL_TOKEN_RESERVE - INIT_REAL_TOKEN_RESERVE) - initVirtualEthReserve_; feeRate_ = 100; // 1% creationFee_ = 0; graduationFeeRate_ = 700; } /*////////////////////////////////////////////////// ////////////////// ASSERTIONS ////////////////// //////////////////////////////////////////////////*/ modifier checkDeadline(uint256 deadline) { if (block.timestamp > deadline) revert DeadlineExceeded(); _; } modifier onlyUnpaused() { if (paused_) revert Paused(); _; } modifier onlyUngraduated(SPumpToken token) { if (pools_[token].headmaster != address(0)) revert AlreadyGraduated(); if (pools_[token].ethReserve > graduationThreshold_) revert TooMuchMcap(); _; } modifier onlySPumpToken(SPumpToken token) { if (token == SPumpToken(address(0)) || pools_[token].token != token) revert NotSPumpToken(); _; } function _isMcapGraduable(SPumpToken token) private view returns (bool) { return pools_[token].ethReserve >= graduationThreshold_; } /*////////////////////////////////////////////////// //////////////////// EVENTS //////////////////// //////////////////////////////////////////////////*/ event TokenCreated(SPumpToken indexed token, address indexed creator); event TokenGraduated( SPumpToken indexed token, SPumpHeadmaster indexed headmaster, uint256 indexed poolId, uint256 liquidity ); event Buy( SPumpToken indexed token, address indexed sender, uint256 amountIn, uint256 amountOut, address indexed to ); event Sell( SPumpToken indexed token, address indexed sender, uint256 amountIn, uint256 amountOut, address indexed to ); event PriceUpdate( SPumpToken indexed token, address indexed sender, uint256 price, uint256 mcapInEth ); /*////////////////////////////////////////////////// //////////////// POOL FUNCTIONS //////////////// //////////////////////////////////////////////////*/ /// @notice Creates a new token in the SPumpFoundry. /// @param name The name of the token. /// @param symbol The symbol of the token. /// @param initAmountIn The initial amount of ETH to swap for the token. /// @param description The description of the token. /// @param extended The extended description of the token, typically a JSON string. /// @return token The newly created token. /// @return amountOut The output amount of token the creator received. function createToken( string memory name, string memory symbol, uint256 initAmountIn, string memory description, string memory extended ) external payable onlyUnpaused returns (SPumpToken token, uint256 amountOut) { if (msg.value != initAmountIn + creationFee_) revert InvalidAmountIn(); if (creationFee_ > 0) { SafeTransferLib.safeTransferETH(feeTo_, creationFee_); } token = _deployToken(name, symbol, description, extended); if (initAmountIn > 0) { amountOut = _swapEthForTokens(token, initAmountIn, 0, msg.sender); } } function _deployToken( string memory name, string memory symbol, string memory description, string memory extended ) private returns (SPumpToken) { SPumpToken token = new SPumpToken( name, symbol, DECIMALS, TOTAL_SUPPLY, description, extended, address(this), msg.sender ); Pool storage pool = pools_[token]; pool.token = token; pool.tokenReserve = INIT_REAL_TOKEN_RESERVE; pool.virtualTokenReserve = INIT_VIRTUAL_TOKEN_RESERVE; pool.ethReserve = 0; pool.virtualEthReserve = initVirtualEthReserve_; pool.lastPrice = initVirtualEthReserve_.divWadDown( INIT_VIRTUAL_TOKEN_RESERVE ); pool.lastMcapInEth = TOTAL_SUPPLY.mulWadUp(pool.lastPrice); pool.lastTimestamp = block.timestamp; pool.lastBlock = block.number; pool.creator = msg.sender; pool.K = K_; emit TokenCreated(token, msg.sender); emit PriceUpdate(token, msg.sender, pool.lastPrice, pool.lastMcapInEth); sPumpLedger_.addCreation(token, msg.sender); return token; } function _graduate(SPumpToken token) private { pools_[token].lastTimestamp = block.timestamp; pools_[token].lastBlock = block.number; uint256 fee = (pools_[token].ethReserve * graduationFeeRate_) / FEE_DENOMINATOR; SafeTransferLib.safeTransferETH(feeTo_, fee); uint256 _amountETH = pools_[token].ethReserve - fee; uint256 _amountToken = TOTAL_SUPPLY - INIT_REAL_TOKEN_RESERVE; SPumpToken(address(token)).setIsUnrestricted(true); token.approve(address(headmaster_), type(uint256).max); (uint256 poolId, uint256 liquidity) = headmaster_.execute{ value: _amountETH }(token, _amountToken, _amountETH); pools_[token].headmaster = address(headmaster_); pools_[token].poolId = poolId; pools_[token].virtualTokenReserve = 0; pools_[token].virtualEthReserve = 0; pools_[token].tokenReserve = 0; pools_[token].ethReserve = 0; emit TokenGraduated(token, headmaster_, poolId, liquidity); sPumpLedger_.addGraduation(token, _amountETH); } /*////////////////////////////////////////////////// //////////////// SWAP FUNCTIONS //////////////// //////////////////////////////////////////////////*/ /// @notice Swaps ETH for tokens. /// @param token The token to swap. /// @param amountIn Input amount of ETH. /// @param amountOutMin Minimum output amount of token. /// @param to Recipient of token. /// @param deadline Deadline for the swap. /// @return amountOut The actual output amount of token. function swapEthForTokens( SPumpToken token, uint256 amountIn, uint256 amountOutMin, address to, uint256 deadline ) external payable nonReentrant onlyUnpaused onlyUngraduated(token) onlySPumpToken(token) checkDeadline(deadline) returns (uint256 amountOut) { if (msg.value != amountIn) revert InvalidAmountIn(); amountOut = _swapEthForTokens(token, amountIn, amountOutMin, to); if (_isMcapGraduable(token)) { _graduate(token); } } function _swapEthForTokens( SPumpToken token, uint256 amountIn, uint256 amountOutMin, address to ) private returns (uint256 amountOut) { if (amountIn == 0) revert InvalidAmountIn(); uint256 fee = (amountIn * feeRate_) / FEE_DENOMINATOR; SafeTransferLib.safeTransferETH(feeTo_, fee); amountIn -= fee; uint256 newVirtualEthReserve = pools_[token].virtualEthReserve + amountIn; uint256 newVirtualTokenReserve = pools_[token].K / newVirtualEthReserve; amountOut = pools_[token].virtualTokenReserve - newVirtualTokenReserve; if (amountOut > pools_[token].tokenReserve) { amountOut = pools_[token].tokenReserve; } if (amountOut < amountOutMin) revert InsufficientOutput(); pools_[token].virtualTokenReserve = newVirtualTokenReserve; pools_[token].virtualEthReserve = newVirtualEthReserve; pools_[token].lastPrice = newVirtualEthReserve.divWadDown( newVirtualTokenReserve ); pools_[token].lastMcapInEth = TOTAL_SUPPLY.mulWadUp( pools_[token].lastPrice ); pools_[token].lastTimestamp = block.timestamp; pools_[token].lastBlock = block.number; pools_[token].ethReserve += amountIn; pools_[token].tokenReserve -= amountOut; SafeTransferLib.safeTransfer(token, to, amountOut); emit Buy(token, msg.sender, amountIn + fee, amountOut, to); emit PriceUpdate( token, msg.sender, pools_[token].lastPrice, pools_[token].lastMcapInEth ); SPumpLedger.Trade memory trade = SPumpLedger.Trade( token, true, msg.sender, amountIn + fee, amountOut, uint128(block.timestamp), uint128(block.number) ); sPumpLedger_.addTrade(trade); } /// @notice Swaps tokens for ETH. /// @param token The token to swap. /// @param amountIn Input amount of token. /// @param amountOutMin Minimum output amount of ETH. /// @param to Recipient of ETH. /// @param deadline Deadline for the swap. /// @return amountOut The actual output amount of ETH. function swapTokensForEth( SPumpToken token, uint256 amountIn, uint256 amountOutMin, address to, uint256 deadline ) external nonReentrant onlyUnpaused onlyUngraduated(token) onlySPumpToken(token) checkDeadline(deadline) returns (uint256 amountOut) { if (amountIn == 0) revert InvalidAmountIn(); SafeTransferLib.safeTransferFrom( token, msg.sender, address(this), amountIn ); uint256 newVirtualTokenReserve = pools_[token].virtualTokenReserve + amountIn; uint256 newVirtualEthReserve = pools_[token].K / newVirtualTokenReserve; amountOut = pools_[token].virtualEthReserve - newVirtualEthReserve; pools_[token].virtualTokenReserve = newVirtualTokenReserve; pools_[token].virtualEthReserve = newVirtualEthReserve; pools_[token].lastPrice = newVirtualEthReserve.divWadDown( newVirtualTokenReserve ); pools_[token].lastMcapInEth = TOTAL_SUPPLY.mulWadUp( pools_[token].lastPrice ); pools_[token].lastTimestamp = block.timestamp; pools_[token].lastBlock = block.number; pools_[token].tokenReserve += amountIn; pools_[token].ethReserve -= amountOut; uint256 fee = (amountOut * feeRate_) / FEE_DENOMINATOR; amountOut -= fee; if (amountOut < amountOutMin) revert InsufficientOutput(); SafeTransferLib.safeTransferETH(feeTo_, fee); SafeTransferLib.safeTransferETH(to, amountOut); emit Sell(token, msg.sender, amountIn, amountOut, to); emit PriceUpdate( token, msg.sender, pools_[token].lastPrice, pools_[token].lastMcapInEth ); SPumpLedger.Trade memory trade = SPumpLedger.Trade( token, false, msg.sender, amountIn, amountOut + fee, uint128(block.timestamp), uint128(block.number) ); sPumpLedger_.addTrade(trade); } /*////////////////////////////////////////////////// //////////////// VIEW FUNCTIONS //////////////// //////////////////////////////////////////////////*/ /// @notice Calculates the expected output amount of ETH given an input amount of token. /// @param token The token to swap. /// @param amountIn Input amount of token. /// @return amountOut The expected output amount of ETH. function calcAmountOutFromToken( SPumpToken token, uint256 amountIn ) external view returns (uint256 amountOut) { if (amountIn == 0) revert InvalidAmountIn(); uint256 newVirtualTokenReserve = pools_[token].virtualTokenReserve + amountIn; uint256 newVirtualEthReserve = pools_[token].K / newVirtualTokenReserve; amountOut = pools_[token].virtualEthReserve - newVirtualEthReserve; uint256 fee = (amountOut * feeRate_) / FEE_DENOMINATOR; amountOut -= fee; } /// @notice Calculates the expected output amount of token given an input amount of ETH. /// @param token The token to swap. /// @param amountIn Input amount of ETH. /// @return amountOut The expected output amount of token. function calcAmountOutFromEth( SPumpToken token, uint256 amountIn ) external view returns (uint256 amountOut) { if (amountIn == 0) revert InvalidAmountIn(); uint256 fee = (amountIn * feeRate_) / FEE_DENOMINATOR; amountIn -= fee; uint256 newVirtualEthReserve = pools_[token].virtualEthReserve + amountIn; uint256 newVirtualTokenReserve = pools_[token].K / newVirtualEthReserve; amountOut = pools_[token].virtualTokenReserve - newVirtualTokenReserve; if (amountOut > pools_[token].tokenReserve) { amountOut = pools_[token].tokenReserve; } } /*/////////////////////////////////////////// // Storage Getters // ///////////////////////////////////////////*/ function getPool(SPumpToken token) external view returns (Pool memory) { return pools_[token]; } function getPoolsAll( uint256 offset, uint256 limit ) external view returns (Pool[] memory) { SPumpToken[] memory tokens = sPumpLedger_.getTokens(offset, limit); Pool[] memory pools = new Pool[](tokens.length); for (uint256 i = 0; i < tokens.length; i++) { pools[i] = pools_[tokens[i]]; } return pools; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.25; import {SafeTransferLib} from "solmate/src/utils/SafeTransferLib.sol"; // import { IUniswapV2Router02 } from "./interfaces/IUniswapV2Router02.sol"; // import { IUniswapV2Factory } from "./interfaces/IUniswapV2Factory.sol"; import {ISyncSwapRouter} from "./interfaces/ISyncSwapRouter.sol"; import {ISyncSwapPoolFactory} from "./interfaces/ISyncSwapPoolFactory.sol"; import {SyncSwapClassicPool} from "./SyncSwap/pool/classic/SyncSwapClassicPool.sol"; import {WrappedEther} from "./SyncSwap/WrappedEther.sol"; import {SPumpToken} from "./SPumpToken.sol"; import {SPumpFoundry} from "./SPumpFoundry.sol"; error Forbidden(); error InvalidAmountToken(); error InvalidAmountEth(); /// @title A SPump protocol graduation strategy for bootstrapping liquidity on uni-v2 AMMs. /// @author strobie <@0xstrobe> /// @notice This contract may be replaced by other strategies in the future. contract SPumpHeadmaster { SPumpFoundry public immutable sPumpFoundry; ISyncSwapRouter public immutable syncSwapRouter; ISyncSwapPoolFactory public immutable syncSwapPoolFactory; address public constant liquidityOwner = address(0); SPumpToken[] public alumni; constructor( SPumpFoundry _sPumpFoundry, ISyncSwapRouter _syncSwapRouter, ISyncSwapPoolFactory _syncSwapPoolFactory ) { sPumpFoundry = _sPumpFoundry; syncSwapRouter = ISyncSwapRouter(payable(_syncSwapRouter)); syncSwapPoolFactory = ISyncSwapPoolFactory( payable(_syncSwapPoolFactory) ); } modifier onlySPumpFoundry() { if (msg.sender != address(sPumpFoundry)) revert Forbidden(); _; } event Executed( SPumpToken token, uint256 indexed poolId, uint256 liquidity, address indexed owner ); function execute( SPumpToken token, uint256 amountToken, uint256 amountEth ) external payable onlySPumpFoundry returns (uint256 poolId, uint256 liquidity) { if (amountToken == 0) revert InvalidAmountToken(); if (amountEth == 0 || msg.value != amountEth) revert InvalidAmountEth(); SafeTransferLib.safeTransferFrom( token, msg.sender, address(this), amountToken ); SafeTransferLib.safeApprove( token, address(syncSwapRouter), amountToken ); address pair = syncSwapPoolFactory.getPool( address(token), syncSwapRouter.wETH() ); if (pair == address(0)) pair = syncSwapRouter.createPool( address(syncSwapPoolFactory), abi.encode(address(token), syncSwapRouter.wETH()) ); // 20 40? poolId = uint256(uint160(pair)); ISyncSwapRouter.TokenInput[] memory inputs = new ISyncSwapRouter.TokenInput[](2); inputs[0] = ISyncSwapRouter.TokenInput(address(token), amountToken); inputs[1] = ISyncSwapRouter.TokenInput(address(0), amountEth); liquidity = syncSwapRouter.addLiquidity2{value: amountEth}( pair, inputs, abi.encode(address(0)), 0, address(0), abi.encode(0) ); alumni.push(token); emit Executed(token, poolId, liquidity, liquidityOwner); } /*/////////////////////////////////////////// // Storage Getters // ///////////////////////////////////////////*/ function getAlumni( uint256 offset, uint256 limit ) external view returns (SPumpToken[] memory) { uint256 length = alumni.length; if (offset >= length) { return new SPumpToken[](0); } uint256 end = offset + limit; if (end > length) { end = length; } SPumpToken[] memory result = new SPumpToken[](end - offset); for (uint256 i = offset; i < end; i++) { result[i - offset] = alumni[i]; } return result; } }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.25; import {SPumpFoundry} from "./SPumpFoundry.sol"; import {SPumpToken} from "./SPumpToken.sol"; error NotFoundry(); /// @title The SPump protocol user activity bookkeeper. /// @author strobie <@0xstrobe> /// @notice Since this version of the protocol is not deployed on gas-expensive networks, this contract is designed to make data more available from onchain. contract SPumpLedger { struct Stats { uint256 totalVolume; uint256 totalLiquidityBootstrapped; uint256 totalTokensCreated; uint256 totalTokensGraduated; uint256 totalTrades; } struct Trade { SPumpToken token; bool isBuy; address maker; uint256 amountIn; uint256 amountOut; uint128 timestamp; uint128 blockNumber; } uint256 public totalVolume; uint256 public totalLiquidityBootstrapped; mapping(address => SPumpToken[]) public tokensCreatedBy; mapping(address => SPumpToken[]) public tokensTradedBy; mapping(SPumpToken => mapping(address => bool)) public hasTraded; SPumpToken[] public tokensCreated; SPumpToken[] public tokensGraduated; mapping(SPumpToken => bool) public isGraduated; Trade[] public trades; mapping(SPumpToken => uint256[]) public tradesByToken; mapping(address => uint256[]) public tradesByUser; SPumpFoundry public immutable sPumpFoundry; constructor() { sPumpFoundry = SPumpFoundry(msg.sender); } modifier onlyFoundry() { if (msg.sender != address(sPumpFoundry)) revert NotFoundry(); _; } /// Add a token to the list of tokens created by a user /// @param token The token to add /// @param user The user to add the token for /// @notice This method should only be called once per token creation function addCreation(SPumpToken token, address user) public onlyFoundry { tokensCreatedBy[user].push(token); tokensCreated.push(token); } /// Add a trade to the ledger /// @param trade The trade to add function addTrade(Trade memory trade) public onlyFoundry { uint256 tradeId = trades.length; trades.push(trade); tradesByToken[trade.token].push(tradeId); tradesByUser[trade.maker].push(tradeId); totalVolume += trade.isBuy ? trade.amountIn : trade.amountOut; if (hasTraded[trade.token][trade.maker]) return; tokensTradedBy[trade.maker].push(trade.token); hasTraded[trade.token][trade.maker] = true; } /// Add a token to the list of graduated tokens /// @param token The token to add /// @notice This method should only be called once per token graduation function addGraduation( SPumpToken token, uint256 amountEth ) public onlyFoundry { tokensGraduated.push(token); isGraduated[token] = true; totalLiquidityBootstrapped += amountEth; } /*/////////////////////////////////////////// // Storage Getters // ///////////////////////////////////////////*/ function getTokensCreatedBy( address user, uint256 offset, uint256 limit ) public view returns (SPumpToken[] memory) { SPumpToken[] storage allTokens = tokensCreatedBy[user]; uint256 length = allTokens.length; if (offset >= length) { return new SPumpToken[](0); } uint256 end = offset + limit; if (end > length) { end = length; } SPumpToken[] memory result = new SPumpToken[](end - offset); for (uint256 i = offset; i < end; i++) { result[i - offset] = allTokens[i]; } return result; } function getTokensTradedBy( address user, uint256 offset, uint256 limit ) public view returns (SPumpToken[] memory) { SPumpToken[] storage allTokens = tokensTradedBy[user]; uint256 length = allTokens.length; if (offset >= length) { return new SPumpToken[](0); } uint256 end = offset + limit; if (end > length) { end = length; } SPumpToken[] memory result = new SPumpToken[](end - offset); for (uint256 i = offset; i < end; i++) { result[i - offset] = allTokens[i]; } return result; } function getTokens( uint256 offset, uint256 limit ) public view returns (SPumpToken[] memory) { uint256 length = tokensCreated.length; if (offset >= length) { return new SPumpToken[](0); } uint256 end = offset + limit; if (end > length) { end = length; } SPumpToken[] memory result = new SPumpToken[](end - offset); for (uint256 i = offset; i < end; i++) { result[i - offset] = tokensCreated[i]; } return result; } function getToken(uint256 tokenId) public view returns (SPumpToken) { return tokensCreated[tokenId]; } function getTokensLength() public view returns (uint256) { return tokensCreated.length; } function getTokensGraduated( uint256 offset, uint256 limit ) public view returns (SPumpToken[] memory) { uint256 length = tokensGraduated.length; if (offset >= length) { return new SPumpToken[](0); } uint256 end = offset + limit; if (end > length) { end = length; } SPumpToken[] memory result = new SPumpToken[](end - offset); for (uint256 i = offset; i < end; i++) { result[i - offset] = tokensGraduated[i]; } return result; } function getTokenGraduated( uint256 tokenId ) public view returns (SPumpToken) { return tokensGraduated[tokenId]; } function getTokensGraduatedLength() public view returns (uint256) { return tokensGraduated.length; } function getTradesAll( uint256 offset, uint256 limit ) public view returns (Trade[] memory) { uint256 length = trades.length; if (offset >= length) { return new Trade[](0); } uint256 end = offset + limit; if (end > length) { end = length; } Trade[] memory result = new Trade[](end - offset); for (uint256 i = offset; i < end; i++) { result[i - offset] = trades[i]; } return result; } function getTrade(uint256 tradeId) public view returns (Trade memory) { return trades[tradeId]; } function getTradesLength() public view returns (uint256) { return trades.length; } function getTradesByTokenLength( SPumpToken token ) public view returns (uint256) { return tradesByToken[token].length; } function getTradeIdsByToken( SPumpToken token, uint256 offset, uint256 limit ) public view returns (uint256[] memory) { uint256 length = tradesByToken[token].length; if (offset >= length) { return new uint256[](0); } uint256 end = offset + limit; if (end > length) { end = length; } uint256[] memory result = new uint256[](end - offset); for (uint256 i = offset; i < end; i++) { result[i - offset] = tradesByToken[token][i]; } return result; } function getTradesByUserLength(address user) public view returns (uint256) { return tradesByUser[user].length; } function getTradeIdsByUser( address user, uint256 offset, uint256 limit ) public view returns (uint256[] memory) { uint256 length = tradesByUser[user].length; if (offset >= length) { return new uint256[](0); } uint256 end = offset + limit; if (end > length) { end = length; } uint256[] memory result = new uint256[](end - offset); for (uint256 i = offset; i < end; i++) { result[i - offset] = tradesByUser[user][i]; } return result; } function getStats() public view returns (Stats memory) { return Stats({ totalVolume: totalVolume, totalLiquidityBootstrapped: totalLiquidityBootstrapped, totalTokensCreated: tokensCreated.length, totalTokensGraduated: tokensGraduated.length, totalTrades: trades.length }); } }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; interface IPoolFactory { function master() external view returns (address); function getDeployData() external view returns (bytes memory); function createPool(bytes calldata data) external returns (address pool); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; /// @dev The callback interface for SyncSwap base pool operations. /// Note additional checks will be required for some callbacks, see below for more information. /// Visit the documentation https://syncswap.gitbook.io/api-documentation/ for more details. interface ICallback { struct BaseMintCallbackParams { address sender; address to; uint reserve0; uint reserve1; uint balance0; uint balance1; uint amount0; uint amount1; uint fee0; uint fee1; uint newInvariant; uint oldInvariant; uint totalSupply; uint liquidity; uint24 swapFee; bytes callbackData; } function syncSwapBaseMintCallback(BaseMintCallbackParams calldata params) external; struct BaseBurnCallbackParams { address sender; address to; uint balance0; uint balance1; uint liquidity; uint totalSupply; uint amount0; uint amount1; uint8 withdrawMode; bytes callbackData; } function syncSwapBaseBurnCallback(BaseBurnCallbackParams calldata params) external; struct BaseBurnSingleCallbackParams { address sender; address to; address tokenIn; address tokenOut; uint balance0; uint balance1; uint liquidity; uint totalSupply; uint amount0; uint amount1; uint amountOut; uint amountSwapped; uint feeIn; uint24 swapFee; uint8 withdrawMode; bytes callbackData; } /// @dev Note the `tokenOut` parameter can be decided by the caller, and the correctness is not guaranteed. /// Additional checks MUST be performed in callback to ensure the `tokenOut` is one of the pools tokens if the sender /// is not a trusted source to avoid potential issues. function syncSwapBaseBurnSingleCallback(BaseBurnSingleCallbackParams calldata params) external; struct BaseSwapCallbackParams { address sender; address to; address tokenIn; address tokenOut; uint reserve0; uint reserve1; uint balance0; uint balance1; uint amountIn; uint amountOut; uint feeIn; uint24 swapFee; uint8 withdrawMode; bytes callbackData; } /// @dev Note the `tokenIn` parameter can be decided by the caller, and the correctness is not guaranteed. /// Additional checks MUST be performed in callback to ensure the `tokenIn` is one of the pools tokens if the sender /// is not a trusted source to avoid potential issues. function syncSwapBaseSwapCallback(BaseSwapCallbackParams calldata params) external; }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; /// @notice The manager contract to control fees. /// Management functions are omitted. interface IFeeManager { function getSwapFee( address pool, address sender, address tokenIn, address tokenOut, bytes calldata data) external view returns (uint24); function getProtocolFee(address pool) external view returns (uint24); function getFeeRecipient() external view returns (address); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; interface IFeeRecipient { /// @dev Notifies the fee recipient after sent fees. function notifyFees( uint16 feeType, address token, uint amount, uint feeRate, bytes calldata data ) external; }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; interface IForwarderRegistry { function isForwarder(address forwarder) external view returns (bool); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; import "./IFeeManager.sol"; import "./IForwarderRegistry.sol"; /// @dev The master contract to create pools and manage whitelisted factories. /// Inheriting the fee manager interface to support fee queries. interface IPoolMaster is IFeeManager, IForwarderRegistry { event SetFactoryWhitelisted(address indexed factory, bool whitelisted); event RegisterPool( address indexed factory, address indexed pool, uint16 indexed poolType, bytes data ); event UpdateForwarderRegistry(address indexed newForwarderRegistry); event UpdateFeeManager(address indexed newFeeManager); function vault() external view returns (address); function feeManager() external view returns (address); function pools(uint) external view returns (address); function poolsLength() external view returns (uint); // Forwarder Registry function setForwarderRegistry(address) external; // Fees function setFeeManager(address) external; // Factories function isFactoryWhitelisted(address) external view returns (bool); function setFactoryWhitelisted(address factory, bool whitelisted) external; // Pools function isPool(address) external view returns (bool); function getPool(bytes32) external view returns (address); function createPool(address factory, bytes calldata data) external returns (address pool); function registerPool(address pool, uint16 poolType, bytes calldata data) external; }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; import "./IPool.sol"; import "../token/IERC20Permit2.sol"; interface IBasePool is IPool, IERC20Permit2 { function token0() external view returns (address); function token1() external view returns (address); function reserve0() external view returns (uint); function reserve1() external view returns (uint); function invariantLast() external view returns (uint); function getReserves() external view returns (uint, uint); function getAmountOut(address tokenIn, uint amountIn, address sender) external view returns (uint amountOut); function getAmountIn(address tokenOut, uint amountOut, address sender) external view returns (uint amountIn); event Mint( address indexed sender, uint amount0, uint amount1, uint liquidity, address indexed to ); event Burn( address indexed sender, uint amount0, uint amount1, uint liquidity, address indexed to ); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync( uint reserve0, uint reserve1 ); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; import "./IBasePool.sol"; interface IClassicPool is IBasePool { }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; interface IPool { struct TokenAmount { address token; uint amount; } /// @dev Returns the address of pool master. function master() external view returns (address); /// @dev Returns the vault. function vault() external view returns (address); /// @dev Returns the pool type. function poolType() external view returns (uint16); /// @dev Returns the assets of the pool. function getAssets() external view returns (address[] memory assets); /// @dev Returns the swap fee of the pool. function getSwapFee(address sender, address tokenIn, address tokenOut, bytes calldata data) external view returns (uint24 swapFee); /// @dev Returns the protocol fee of the pool. function getProtocolFee() external view returns (uint24 protocolFee); /// @dev Mints liquidity. function mint( bytes calldata data, address sender, address callback, bytes calldata callbackData ) external returns (uint liquidity); /// @dev Burns liquidity. function burn( bytes calldata data, address sender, address callback, bytes calldata callbackData ) external returns (TokenAmount[] memory tokenAmounts); /// @dev Burns liquidity with single output token. function burnSingle( bytes calldata data, address sender, address callback, bytes calldata callbackData ) external returns (TokenAmount memory tokenAmount); /// @dev Swaps between tokens. function swap( bytes calldata data, address sender, address callback, bytes calldata callbackData ) external returns (TokenAmount memory tokenAmount); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; import "./IERC20Base.sol"; interface IERC20 is IERC20Base { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; interface IERC20Base { function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint amount) external returns (bool); function transfer(address to, uint amount) external returns (bool); function transferFrom(address from, address to, uint amount) external returns (bool); event Approval(address indexed owner, address indexed spender, uint amount); event Transfer(address indexed from, address indexed to, uint amount); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; import "./IERC20.sol"; interface IERC20Permit is IERC20 { function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; function nonces(address owner) external view returns (uint); function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; import "./IERC20Permit.sol"; interface IERC20Permit2 is IERC20Permit { function permit2(address owner, address spender, uint amount, uint deadline, bytes calldata signature) external; }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; interface IERC3156FlashBorrower { /** * @dev Receive a flash loan. * @param initiator The initiator of the loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @param fee The additional amount of tokens to repay. * @param data Arbitrary data structure, intended to contain user-defined parameters. * @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan" */ function onFlashLoan( address initiator, address token, uint256 amount, uint256 fee, bytes calldata data ) external returns (bytes32); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; import "./IERC3156FlashBorrower.sol"; interface IERC3156FlashLender { /** * @dev The amount of currency available to be lent. * @param token The loan currency. * @return The amount of `token` that can be borrowed. */ function maxFlashLoan( address token ) external view returns (uint256); /** * @dev The fee to be charged for a given loan. * @param token The loan currency. * @param amount The amount of tokens lent. * @return The amount of `token` to be charged for the loan, on top of the returned principal. */ function flashFee( address token, uint256 amount ) external view returns (uint256); /** * @dev Initiate a flash loan. * @param receiver The receiver of the tokens in the loan, and the receiver of the callback. * @param token The loan currency. * @param amount The amount of tokens lent. * @param data Arbitrary data structure, intended to contain user-defined parameters. */ function flashLoan( IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data ) external returns (bool); }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; import "./IFlashLoanRecipient.sol"; import "./IERC3156FlashLender.sol"; interface IFlashLoan is IERC3156FlashLender { function flashLoanFeePercentage() external view returns (uint); /** * @dev Performs a 'flash loan', sending tokens to `recipient`, executing the `receiveFlashLoan` hook on it, * and then reverting unless the tokens plus a proportional protocol fee have been returned. * * The `tokens` and `amounts` arrays must have the same length, and each entry in these indicates the loan amount * for each token contract. `tokens` must be sorted in ascending order. * * The 'userData' field is ignored by the Vault, and forwarded as-is to `recipient` as part of the * `receiveFlashLoan` call. * * Emits `FlashLoan` events. */ function flashLoanMultiple( IFlashLoanRecipient recipient, address[] memory tokens, uint[] memory amounts, bytes memory userData ) external; /** * @dev Emitted for each individual flash loan performed by `flashLoan`. */ event FlashLoan(address indexed recipient, address indexed token, uint amount, uint feeAmount); }
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.7.0 <0.9.0; // Inspired by Aave Protocol's IFlashLoanReceiver. interface IFlashLoanRecipient { /** * @dev When `flashLoan` is called on the Vault, it invokes the `receiveFlashLoan` hook on the recipient. * * At the time of the call, the Vault will have transferred `amounts` for `tokens` to the recipient. Before this * call returns, the recipient must have transferred `amounts` plus `feeAmounts` for each token back to the * Vault, or else the entire flash loan will revert. * * `userData` is the same value passed in the `IVault.flashLoan` call. */ function receiveFlashLoan( address[] memory tokens, uint[] memory amounts, uint[] memory feeAmounts, bytes memory userData ) external; }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity >=0.5.0; import "./IFlashLoan.sol"; interface IVault is IFlashLoan { function wETH() external view returns (address); function reserves(address token) external view returns (uint reserve); function balanceOf(address token, address owner) external view returns (uint balance); function deposit(address token, address to) external payable returns (uint amount); function depositETH(address to) external payable returns (uint amount); function transferAndDeposit(address token, address to, uint amount) external payable returns (uint); function transfer(address token, address to, uint amount) external; function withdraw(address token, address to, uint amount) external; function withdrawAlternative(address token, address to, uint amount, uint8 mode) external; function withdrawETH(address to, uint amount) external; }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. * * Based on OpenZeppelin's ECDSA library. * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/561d1061fc568f04c7a65853538e834a889751e8/contracts/utils/cryptography/ECDSA.sol */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return address(0); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } return ecrecover(hash, v, r, s); } }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.0; import "../interfaces/token/IERC165.sol"; import "../interfaces/token/IERC20Permit2.sol"; import "./SignatureChecker.sol"; error Expired(); error InvalidSignature(); /** * @dev A simple ERC20 implementation for pool's liquidity token, supports permit by both ECDSA signatures from * externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like Argent. * * Based on Solmate's ERC20. * https://github.com/transmissions11/solmate/blob/bff24e835192470ed38bf15dbed6084c2d723ace/src/tokens/ERC20.sol */ contract ERC20Permit2 is IERC165, IERC20Permit2 { uint8 public immutable override decimals = 18; uint public override totalSupply; mapping(address => uint) public override balanceOf; mapping(address => mapping(address => uint)) public override allowance; bytes32 private constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)") mapping(address => uint) public override nonces; // These members are actually immutable as // `_initialize` will only indent to be called once. string public override name; string public override symbol; uint private INITIAL_CHAIN_ID; bytes32 private INITIAL_DOMAIN_SEPARATOR; function _initialize(string memory _name, string memory _symbol) internal { name = _name; symbol = _symbol; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = _computeDomainSeparator(); } function supportsInterface(bytes4 interfaceID) external pure override returns (bool) { return interfaceID == this.supportsInterface.selector || // ERC-165 interfaceID == this.permit.selector || // ERC-2612 interfaceID == this.permit2.selector; // Permit2 } function DOMAIN_SEPARATOR() public view override returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : _computeDomainSeparator(); } function _computeDomainSeparator() private view returns (bytes32) { return keccak256( abi.encode( // keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)") 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f, keccak256(bytes(name)), // keccak256(bytes("1")) 0xc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc6, block.chainid, address(this) ) ); } function _approve(address _owner, address _spender, uint _amount) private { allowance[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } function approve(address _spender, uint _amount) public override returns (bool) { _approve(msg.sender, _spender, _amount); return true; } function transfer(address _to, uint _amount) public override returns (bool) { balanceOf[msg.sender] -= _amount; // Cannot overflow because the sum of all user balances can't exceed the max uint256 value. unchecked { balanceOf[_to] += _amount; } emit Transfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint _amount) public override returns (bool) { uint256 _allowed = allowance[_from][msg.sender]; // Saves gas for limited approvals. if (_allowed != type(uint).max) { allowance[_from][msg.sender] = _allowed - _amount; } balanceOf[_from] -= _amount; // Cannot overflow because the sum of all user balances can't exceed the max uint256 value. unchecked { balanceOf[_to] += _amount; } emit Transfer(_from, _to, _amount); return true; } function _mint(address _to, uint _amount) internal { totalSupply += _amount; // Cannot overflow because the sum of all user balances can't exceed the max uint256 value. unchecked { balanceOf[_to] += _amount; } emit Transfer(address(0), _to, _amount); } function _burn(address _from, uint _amount) internal { balanceOf[_from] -= _amount; // Cannot underflow because a user's balance will never be larger than the total supply. unchecked { totalSupply -= _amount; } emit Transfer(_from, address(0), _amount); } modifier ensures(uint _deadline) { // solhint-disable-next-line not-rely-on-time if (block.timestamp > _deadline) { revert Expired(); } _; } function _permitHash( address _owner, address _spender, uint _amount, uint _deadline ) private returns (bytes32) { return keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, _owner, _spender, _amount, nonces[_owner]++, _deadline)) ) ); } function permit( address _owner, address _spender, uint _amount, uint _deadline, uint8 _v, bytes32 _r, bytes32 _s ) public override ensures(_deadline) { bytes32 _hash = _permitHash(_owner, _spender, _amount, _deadline); address _recoveredAddress = ecrecover(_hash, _v, _r, _s); if (_recoveredAddress != _owner) { revert InvalidSignature(); } if (_recoveredAddress == address(0)) { revert InvalidSignature(); } _approve(_owner, _spender, _amount); } function permit2( address _owner, address _spender, uint _amount, uint _deadline, bytes calldata _signature ) public override ensures(_deadline) { bytes32 _hash = _permitHash(_owner, _spender, _amount, _deadline); if (!SignatureChecker.isValidSignatureNow(_owner, _hash, _signature)) { revert InvalidSignature(); } _approve(_owner, _spender, _amount); } }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.0; /// @dev Math functions. /// @dev Modified from Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/FixedPointMathLib.sol) library Math { /// @notice Compares a and b and returns 'true' if the difference between a and b /// is less than 1 or equal to each other. /// @param a uint256 to compare with. /// @param b uint256 to compare with. function within1(uint256 a, uint256 b) internal pure returns (bool) { unchecked { if (a > b) { return a - b <= 1; } return b - a <= 1; } } /// @dev Returns the square root of `x`. function sqrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`. z := 181 // The "correct" value is 1, but this saves a multiplication later. // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. // Let `y = x / 2**r`. // We check `y >= 2**(k + 8)` but shift right by `k` bits // each branch to ensure that if `x >= 256`, then `y >= 256`. let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffffff, shr(r, x)))) z := shl(shr(1, r), z) // Goal was to get `z*z*y` within a small factor of `x`. More iterations could // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`. // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small. // That's not possible if `x < 256` but we can just verify those cases exhaustively. // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`. // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`. // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps. // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)` // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`, // with largest error when `s = 1` and when `s = 256` or `1/256`. // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`. // Then we can estimate `sqrt(y)` using // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`. // There is no overflow risk here since `y < 2**136` after the first branch above. z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181. // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // If `x+1` is a perfect square, the Babylonian method cycles between // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor. // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case. // If you don't care whether the floor or ceil square root is returned, you can remove this statement. z := sub(z, lt(div(x, z), z)) } } // Mul Div /// @dev Rounded down. function mulDiv( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x == 0 || (x * y) / x == y)) if iszero(and(iszero(iszero(denominator)), or(iszero(x), eq(div(z, x), y)))) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } /// @dev Rounded down. /// This function assumes that `x` is not zero, and must be checked externally. function mulDivUnsafeFirst( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(denominator != 0 && (x * y) / x == y) if iszero(and(iszero(iszero(denominator)), eq(div(z, x), y))) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } /// @dev Rounded down. /// This function assumes that `denominator` is not zero, and must be checked externally. function mulDivUnsafeLast( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(x == 0 || (x * y) / x == y) if iszero(or(iszero(x), eq(div(z, x), y))) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } /// @dev Rounded down. /// This function assumes that both `x` and `denominator` are not zero, and must be checked externally. function mulDivUnsafeFirstLast( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require((x * y) / x == y) if iszero(eq(div(z, x), y)) { revert(0, 0) } // Divide z by the denominator. z := div(z, denominator) } } // Mul /// @dev Optimized safe multiplication operation for minimal gas cost. /// Equivalent to * function mul( uint256 x, uint256 y ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require(x == 0 || (x * y) / x == y) if iszero(or(iszero(x), eq(div(z, x), y))) { revert(0, 0) } } } /// @dev Optimized unsafe multiplication operation for minimal gas cost. /// This function assumes that `x` is not zero, and must be checked externally. function mulUnsafeFirst( uint256 x, uint256 y ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := mul(x, y) // Equivalent to require((x * y) / x == y) if iszero(eq(div(z, x), y)) { revert(0, 0) } } } // Div /// @dev Optimized safe division operation for minimal gas cost. /// Equivalent to / function div( uint256 x, uint256 y ) internal pure returns (uint256 z) { assembly { // Store x * y in z for now. z := div(x, y) // Equivalent to require(y != 0) if iszero(y) { revert(0, 0) } } } /// @dev Optimized unsafe division operation for minimal gas cost. /// Division by 0 will not reverts and returns 0, and must be checked externally. function divUnsafeLast( uint256 x, uint256 y ) internal pure returns (uint256 z) { assembly { z := div(x, y) } } }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.0; library MetadataHelper { /** * @dev Returns symbol of the token. * * @param token The address of a ERC20 token. * * Return boolean indicating the status and the symbol as string; * * NOTE: Symbol is not the standard interface and some tokens may not support it. * Calling against these tokens will not success, with an empty result. */ function getSymbol(address token) internal view returns (bool, string memory) { // bytes4(keccak256(bytes("symbol()"))) (bool success, bytes memory returndata) = token.staticcall(abi.encodeWithSelector(0x95d89b41)); if (success) { return (true, abi.decode(returndata, (string))); } else { return (false, ""); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { // On the first call to nonReentrant, _status will be _NOT_ENTERED require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; } function _nonReentrantAfter() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { return _status == _ENTERED; } }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like * Argent and Gnosis Safe. * * Based on OpenZeppelin's SignatureChecker library. * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/561d1061fc568f04c7a65853538e834a889751e8/contracts/utils/cryptography/SignatureChecker.sol */ library SignatureChecker { bytes4 constant internal MAGICVALUE = 0x1626ba7e; // bytes4(keccak256("isValidSignature(bytes32,bytes)") /** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered) = ECDSA.recover(hash, signature); if (recovered == signer) { if (recovered != address(0)) { return true; } } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(MAGICVALUE, hash, signature) ); return ( success && result.length == 32 && abi.decode(result, (bytes32)) == bytes32(MAGICVALUE) ); } }
// SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity ^0.8.0; import "../../libraries/Math.sol"; import "../../libraries/ERC20Permit2.sol"; import "../../libraries/MetadataHelper.sol"; import "../../libraries/ReentrancyGuard.sol"; import "../../interfaces/ICallback.sol"; import "../../interfaces/vault/IVault.sol"; import "../../interfaces/pool/IClassicPool.sol"; import "../../interfaces/master/IPoolMaster.sol"; import "../../interfaces/master/IFeeRecipient.sol"; import "../../interfaces/factory/IPoolFactory.sol"; error Overflow(); error InsufficientLiquidityMinted(); contract SyncSwapClassicPool is IClassicPool, ERC20Permit2, ReentrancyGuard { using Math for uint; uint private constant MINIMUM_LIQUIDITY = 1000; uint private constant MAX_FEE = 1e5; /// @dev 100%. /// @dev Pool type `1` for classic pools. // uint16 public constant override poolType = 1; function poolType() external override pure returns (uint16){ return 1; } address public immutable override master; address public immutable override vault; address public immutable override token0; address public immutable override token1; /// @dev Pool reserve of each pool token as of immediately after the most recent balance event. /// The value is used to measure growth in invariant on mints and input tokens on swaps. uint public override reserve0; uint public override reserve1; /// @dev Invariant of the pool as of immediately after the most recent liquidity event. /// The value is used to measure growth in invariant when protocol fee is enabled, /// and will be reset to zero if protocol fee is disabled. uint public override invariantLast; /// @dev Factory must ensures that the parameters are valid. constructor() { (bytes memory _deployData) = IPoolFactory(msg.sender).getDeployData(); (address _token0, address _token1) = abi.decode(_deployData, (address, address)); address _master = IPoolFactory(msg.sender).master(); master = _master; vault = IPoolMaster(_master).vault(); (token0, token1) = (_token0, _token1); // try to set symbols for the LP token (bool _success0, string memory _symbol0) = MetadataHelper.getSymbol(_token0); (bool _success1, string memory _symbol1) = MetadataHelper.getSymbol(_token1); if (_success0 && _success1) { _initialize( string(abi.encodePacked("SyncSwap ", _symbol0, "/", _symbol1, " Classic LP")), string(abi.encodePacked(_symbol0, "/", _symbol1, " cSLP")) ); } else { _initialize( "SyncSwap Classic LP", "cSLP" ); } } function getAssets() external view override returns (address[] memory assets) { assets = new address[](2); assets[0] = token0; assets[1] = token1; } /// @dev Returns the verified sender address otherwise `address(0)`. function _getVerifiedSender(address _sender) private view returns (address) { if (_sender != address(0)) { if (_sender != msg.sender) { if (!IPoolMaster(master).isForwarder(msg.sender)) { // The sender from non-forwarder is invalid. return address(0); } } } return _sender; } /// @dev Mints LP tokens - should be called via the router after transferring pool tokens. /// The router should ensure that sufficient LP tokens are minted. function mint( bytes calldata _data, address _sender, address _callback, bytes calldata _callbackData ) external override nonReentrant returns (uint) { ICallback.BaseMintCallbackParams memory params; params.to = abi.decode(_data, (address)); (params.reserve0, params.reserve1) = (reserve0, reserve1); (params.balance0, params.balance1) = _balances(); params.newInvariant = _computeInvariant(params.balance0, params.balance1); params.amount0 = params.balance0 - params.reserve0; params.amount1 = params.balance1 - params.reserve1; //require(_amount0 != 0 && _amount1 != 0); // Gets swap fee for the sender. _sender = _getVerifiedSender(_sender); uint _amount1Optimal = params.reserve0 == 0 ? 0 : (params.amount0 * params.reserve1) / params.reserve0; bool _swap0For1 = params.amount1 < _amount1Optimal; if (_swap0For1) { params.swapFee = _getSwapFee(_sender, token0, token1); } else { params.swapFee = _getSwapFee(_sender, token1, token0); } // Adds mint fee to reserves (applies to invariant increase) if unbalanced. (params.fee0, params.fee1) = _unbalancedMintFee(params.swapFee, params.amount0, params.amount1, _amount1Optimal, params.reserve0, params.reserve1); params.reserve0 += params.fee0; params.reserve1 += params.fee1; // Calculates old invariant (where unbalanced fee added to) and, mint protocol fee if any. params.oldInvariant = _computeInvariant(params.reserve0, params.reserve1); bool _feeOn; (_feeOn, params.totalSupply) = _mintProtocolFee(0, 0, params.oldInvariant); if (params.totalSupply == 0) { params.liquidity = params.newInvariant - MINIMUM_LIQUIDITY; _mint(address(0), MINIMUM_LIQUIDITY); // permanently lock on first mint. } else { // Calculates liquidity proportional to invariant growth. params.liquidity = ((params.newInvariant - params.oldInvariant) * params.totalSupply) / params.oldInvariant; } // Mints liquidity for recipient. if (params.liquidity == 0) { revert InsufficientLiquidityMinted(); } _mint(params.to, params.liquidity); // Calls callback with data. if (_callback != address(0)) { // Fills additional values for callback params. params.sender = _sender; params.callbackData = _callbackData; ICallback(_callback).syncSwapBaseMintCallback(params); } // Updates reserves and last invariant with new balances. _updateReserves(params.balance0, params.balance1); if (_feeOn) { invariantLast = params.newInvariant; } emit Mint(msg.sender, params.amount0, params.amount1, params.liquidity, params.to); return params.liquidity; } /// @dev Burns LP tokens sent to this contract. /// The router should ensure that sufficient pool tokens are received. function burn( bytes calldata _data, address _sender, address _callback, bytes calldata _callbackData ) external override nonReentrant returns (TokenAmount[] memory _amounts) { ICallback.BaseBurnCallbackParams memory params; (params.to, params.withdrawMode) = abi.decode(_data, (address, uint8)); (params.balance0, params.balance1) = _balances(); params.liquidity = balanceOf[address(this)]; // Mints protocol fee if any. // Note `_mintProtocolFee` here will checks overflow. bool _feeOn; (_feeOn, params.totalSupply) = _mintProtocolFee(params.balance0, params.balance1, 0); // Calculates amounts of pool tokens proportional to balances. params.amount0 = params.liquidity * params.balance0 / params.totalSupply; params.amount1 = params.liquidity * params.balance1 / params.totalSupply; //require(_amount0 != 0 || _amount1 != 0); // Burns liquidity and transfers pool tokens. _burn(address(this), params.liquidity); _transferTokens(token0, params.to, params.amount0, params.withdrawMode); _transferTokens(token1, params.to, params.amount1, params.withdrawMode); // Updates balances. /// @dev Cannot underflow because amounts are lesser figures derived from balances. unchecked { params.balance0 -= params.amount0; params.balance1 -= params.amount1; } // Calls callback with data. // Note reserves are not updated at this point to allow read the old values. if (_callback != address(0)) { // Fills additional values for callback params. params.sender = _getVerifiedSender(_sender); params.callbackData = _callbackData; ICallback(_callback).syncSwapBaseBurnCallback(params); } // Updates reserves and last invariant with up-to-date balances (after transfers). _updateReserves(params.balance0, params.balance1); if (_feeOn) { invariantLast = _computeInvariant(params.balance0, params.balance1); } _amounts = new TokenAmount[](2); _amounts[0] = TokenAmount(token0, params.amount0); _amounts[1] = TokenAmount(token1, params.amount1); emit Burn(msg.sender, params.amount0, params.amount1, params.liquidity, params.to); } /// @dev Burns LP tokens sent to this contract and swaps one of the output tokens for another /// - i.e., the user gets a single token out by burning LP tokens. /// The router should ensure that sufficient pool tokens are received. function burnSingle( bytes calldata _data, address _sender, address _callback, bytes calldata _callbackData ) external override nonReentrant returns (TokenAmount memory _tokenAmount) { ICallback.BaseBurnSingleCallbackParams memory params; (params.tokenOut, params.to, params.withdrawMode) = abi.decode(_data, (address, address, uint8)); (params.balance0, params.balance1) = _balances(); params.liquidity = balanceOf[address(this)]; // Mints protocol fee if any. // Note `_mintProtocolFee` here will checks overflow. bool _feeOn; (_feeOn, params.totalSupply) = _mintProtocolFee(params.balance0, params.balance1, 0); // Calculates amounts of pool tokens proportional to balances. params.amount0 = params.liquidity * params.balance0 / params.totalSupply; params.amount1 = params.liquidity * params.balance1 / params.totalSupply; // Burns liquidity. _burn(address(this), params.liquidity); // Gets swap fee for the sender. _sender = _getVerifiedSender(_sender); // Swaps one token for another, transfers desired tokens, and update context values. /// @dev Calculate `amountOut` as if the user first withdrew balanced liquidity and then swapped from one token for another. if (params.tokenOut == token1) { // Swaps `token0` for `token1`. params.swapFee = _getSwapFee(_sender, token0, token1); params.tokenIn = token0; (params.amountSwapped, params.feeIn) = _getAmountOut( params.swapFee, params.amount0, params.balance0 - params.amount0, params.balance1 - params.amount1, true ); params.amount1 += params.amountSwapped; _transferTokens(token1, params.to, params.amount1, params.withdrawMode); params.amountOut = params.amount1; params.amount0 = 0; params.balance1 -= params.amount1; } else { // Swaps `token1` for `token0`. //require(_tokenOut == token0); params.swapFee = _getSwapFee(_sender, token1, token0); params.tokenIn = token1; (params.amountSwapped, params.feeIn) = _getAmountOut( params.swapFee, params.amount1, params.balance0 - params.amount0, params.balance1 - params.amount1, false ); params.amount0 += params.amountSwapped; _transferTokens(token0, params.to, params.amount0, params.withdrawMode); params.amountOut = params.amount0; params.amount1 = 0; params.balance0 -= params.amount0; } // Calls callback with data. // Note reserves are not updated at this point to allow read the old values. if (_callback != address(0)) { // Fills additional values for callback params. params.sender = _sender; params.callbackData = _callbackData; /// @dev Note the `tokenOut` parameter can be decided by the caller, and the correctness is not guaranteed. /// Additional checks MUST be performed in callback to ensure the `tokenOut` is one of the pools tokens if the sender /// is not a trusted source to avoid potential issues. ICallback(_callback).syncSwapBaseBurnSingleCallback(params); } // Update reserves and last invariant with up-to-date balances (updated above). _updateReserves(params.balance0, params.balance1); if (_feeOn) { invariantLast = _computeInvariant(params.balance0, params.balance1); } _tokenAmount = TokenAmount(params.tokenOut, params.amountOut); emit Burn(msg.sender, params.amount0, params.amount1, params.liquidity, params.to); } /// @dev Swaps one token for another - should be called via the router after transferring input tokens. /// The router should ensure that sufficient output tokens are received. function swap( bytes calldata _data, address _sender, address _callback, bytes calldata _callbackData ) external override nonReentrant returns (TokenAmount memory _tokenAmount) { ICallback.BaseSwapCallbackParams memory params; (params.tokenIn, params.to, params.withdrawMode) = abi.decode(_data, (address, address, uint8)); (params.reserve0, params.reserve1) = (reserve0, reserve1); (params.balance0, params.balance1) = _balances(); // Gets swap fee for the sender. _sender = _getVerifiedSender(_sender); // Calculates output amount, update context values and emit event. if (params.tokenIn == token0) { params.swapFee = _getSwapFee(_sender, token0, token1); params.tokenOut = token1; params.amountIn = params.balance0 - params.reserve0; (params.amountOut, params.feeIn) = _getAmountOut(params.swapFee, params.amountIn, params.reserve0, params.reserve1, true); params.balance1 -= params.amountOut; emit Swap(msg.sender, params.amountIn, 0, 0, params.amountOut, params.to); } else { //require(params.tokenIn == token1); params.swapFee = _getSwapFee(_sender, token1, token0); params.tokenOut = token0; params.amountIn = params.balance1 - params.reserve1; (params.amountOut, params.feeIn) = _getAmountOut(params.swapFee, params.amountIn, params.reserve0, params.reserve1, false); params.balance0 -= params.amountOut; emit Swap(msg.sender, 0, params.amountIn, params.amountOut, 0, params.to); } // Checks overflow. if (params.balance0 > type(uint128).max) { revert Overflow(); } if (params.balance1 > type(uint128).max) { revert Overflow(); } // Transfers output tokens. _transferTokens(params.tokenOut, params.to, params.amountOut, params.withdrawMode); // Calls callback with data. if (_callback != address(0)) { // Fills additional values for callback params. params.sender = _sender; params.callbackData = _callbackData; /// @dev Note the `tokenIn` parameter can be decided by the caller, and the correctness is not guaranteed. /// Additional checks MUST be performed in callback to ensure the `tokenIn` is one of the pools tokens if the sender /// is not a trusted source to avoid potential issues. ICallback(_callback).syncSwapBaseSwapCallback(params); } // Updates reserves with up-to-date balances (updated above). _updateReserves(params.balance0, params.balance1); _tokenAmount.token = params.tokenOut; _tokenAmount.amount = params.amountOut; } function _getSwapFee(address _sender, address _tokenIn, address _tokenOut) private view returns (uint24 _swapFee) { _swapFee = getSwapFee(_sender, _tokenIn, _tokenOut, ""); } /// @dev This function doesn't check the forwarder. function getSwapFee(address _sender, address _tokenIn, address _tokenOut, bytes memory data) public view override returns (uint24 _swapFee) { _swapFee = IPoolMaster(master).getSwapFee(address(this), _sender, _tokenIn, _tokenOut, data); } function getProtocolFee() public view override returns (uint24 _protocolFee) { _protocolFee = IPoolMaster(master).getProtocolFee(address(this)); } function _updateReserves(uint _balance0, uint _balance1) private { (reserve0, reserve1) = (_balance0, _balance1); emit Sync(_balance0, _balance1); } function _transferTokens(address token, address to, uint amount, uint8 withdrawMode) private { if (withdrawMode == 0) { IVault(vault).transfer(token, to, amount); } else { IVault(vault).withdrawAlternative(token, to, amount, withdrawMode); } } function _balances() private view returns (uint balance0, uint balance1) { balance0 = IVault(vault).balanceOf(token0, address(this)); balance1 = IVault(vault).balanceOf(token1, address(this)); } /// @dev This fee is charged to cover for the swap fee when users adding unbalanced liquidity. function _unbalancedMintFee( uint _swapFee, uint _amount0, uint _amount1, uint _amount1Optimal, uint _reserve0, uint _reserve1 ) private pure returns (uint _token0Fee, uint _token1Fee) { if (_reserve0 == 0) { return (0, 0); } if (_amount1 >= _amount1Optimal) { _token1Fee = (_swapFee * (_amount1 - _amount1Optimal)) / (2 * MAX_FEE); } else { uint _amount0Optimal = (_amount1 * _reserve0) / _reserve1; _token0Fee = (_swapFee * (_amount0 - _amount0Optimal)) / (2 * MAX_FEE); } } function _mintProtocolFee(uint _reserve0, uint _reserve1, uint _invariant) private returns (bool _feeOn, uint _totalSupply) { _totalSupply = totalSupply; address _feeRecipient = IPoolMaster(master).getFeeRecipient(); _feeOn = (_feeRecipient != address(0)); uint _invariantLast = invariantLast; if (_invariantLast != 0) { if (_feeOn) { if (_invariant == 0) { _invariant = _computeInvariant(_reserve0, _reserve1); } if (_invariant > _invariantLast) { /// @dev Mints `protocolFee` % of growth in liquidity (invariant). uint _protocolFee = getProtocolFee(); uint _numerator = _totalSupply * (_invariant - _invariantLast) * _protocolFee; uint _denominator = (MAX_FEE - _protocolFee) * _invariant + _protocolFee * _invariantLast; uint _liquidity = _numerator / _denominator; if (_liquidity != 0) { _mint(_feeRecipient, _liquidity); // Notifies the fee recipient. IFeeRecipient(_feeRecipient).notifyFees(1, address(this), _liquidity, _protocolFee, ""); _totalSupply += _liquidity; // update cached value. } } } else { /// @dev Resets last invariant to clear measured growth if protocol fee is not enabled. invariantLast = 0; } } } function getReserves() external view override returns (uint _reserve0, uint _reserve1) { (_reserve0, _reserve1) = (reserve0, reserve1); } function getAmountOut(address _tokenIn, uint _amountIn, address _sender) external view override returns (uint _amountOut) { (uint _reserve0, uint _reserve1) = (reserve0, reserve1); bool _swap0For1 = _tokenIn == token0; address _tokenOut = _swap0For1 ? token1 : token0; (_amountOut,) = _getAmountOut(_getSwapFee(_sender, _tokenIn, _tokenOut), _amountIn, _reserve0, _reserve1, _swap0For1); } function getAmountIn(address _tokenOut, uint _amountOut, address _sender) external view override returns (uint _amountIn) { (uint _reserve0, uint _reserve1) = (reserve0, reserve1); bool _swap1For0 = _tokenOut == token0; address _tokenIn = _swap1For0 ? token1 : token0; _amountIn = _getAmountIn(_getSwapFee(_sender, _tokenIn, _tokenOut), _amountOut, _reserve0, _reserve1, _swap1For0); } function _getAmountOut( uint _swapFee, uint _amountIn, uint _reserve0, uint _reserve1, bool _token0In ) private pure returns (uint _dy, uint _feeIn) { if (_amountIn == 0) { _dy = 0; } else { uint _amountInWithFee = _amountIn * (MAX_FEE - _swapFee); _feeIn = _amountIn * _swapFee / MAX_FEE; if (_token0In) { _dy = (_amountInWithFee * _reserve1) / (_reserve0 * MAX_FEE + _amountInWithFee); } else { _dy = (_amountInWithFee * _reserve0) / (_reserve1 * MAX_FEE + _amountInWithFee); } } } function _getAmountIn( uint _swapFee, uint _amountOut, uint _reserve0, uint _reserve1, bool _token0Out ) private pure returns (uint _dx) { if (_amountOut == 0) { _dx = 0; } else { if (_token0Out) { _dx = (_reserve1 * _amountOut * MAX_FEE) / ((_reserve0 - _amountOut) * (MAX_FEE - _swapFee)) + 1; } else { _dx = (_reserve0 * _amountOut * MAX_FEE) / ((_reserve1 - _amountOut) * (MAX_FEE - _swapFee)) + 1; } } } function _computeInvariant(uint _reserve0, uint _reserve1) private pure returns (uint _invariant) { if (_reserve0 > type(uint128).max) { revert Overflow(); } if (_reserve1 > type(uint128).max) { revert Overflow(); } _invariant = (_reserve0 * _reserve1).sqrt(); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; // solhint-disable reason-string // solhint-disable no-empty-blocks /// @author Inspired by WETH9 (https://github.com/dapphub/ds-weth/blob/master/src/weth9.sol) contract WrappedEther is ERC20Permit { /// @notice Emitted when user deposits Ether to this contract. /// @param dst The address of depositor. /// @param wad The amount of Ether in wei deposited. event Deposit(address indexed dst, uint256 wad); /// @notice Emitted when user withdraws some Ether from this contract. /// @param src The address of caller. /// @param wad The amount of Ether in wei withdrawn. event Withdrawal(address indexed src, uint256 wad); constructor() ERC20Permit("Wrapped Ether") ERC20("Wrapped Ether", "WETH") {} receive() external payable { deposit(); } function deposit() public payable { _mint(msg.sender, msg.value); emit Deposit(msg.sender, msg.value); } function withdraw(uint256 wad) external { _burn(msg.sender, wad); (bool success, ) = msg.sender.call{value: wad}(""); require(success, "withdraw ETH failed"); emit Withdrawal(msg.sender, wad); } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 { /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); /*////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public immutable decimals; /*////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ uint256 internal immutable INITIAL_CHAIN_ID; bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ constructor( string memory _name, string memory _symbol, uint8 _decimals ) { name = _name; symbol = _symbol; decimals = _decimals; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator(); } /*////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED"); // Unchecked because the only math done is incrementing // the owner's nonce which cannot realistically overflow. unchecked { address recoveredAddress = ecrecover( keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR(), keccak256( abi.encode( keccak256( "Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)" ), owner, spender, value, nonces[owner]++, deadline ) ) ) ), v, r, s ); require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER"); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator(); } function computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name)), keccak256("1"), block.chainid, address(this) ) ); } /*////////////////////////////////////////////////////////////// INTERNAL MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol) /// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol) library FixedPointMathLib { /*////////////////////////////////////////////////////////////// SIMPLIFIED FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ uint256 internal constant MAX_UINT256 = 2**256 - 1; uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. } function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up. } function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down. } function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up. } /*////////////////////////////////////////////////////////////// LOW LEVEL FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ function mulDivDown( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y)) if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) { revert(0, 0) } // Divide x * y by the denominator. z := div(mul(x, y), denominator) } } function mulDivUp( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y)) if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) { revert(0, 0) } // If x * y modulo the denominator is strictly greater than 0, // 1 is added to round up the division of x * y by the denominator. z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator)) } } function rpow( uint256 x, uint256 n, uint256 scalar ) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { switch x case 0 { switch n case 0 { // 0 ** 0 = 1 z := scalar } default { // 0 ** n = 0 z := 0 } } default { switch mod(n, 2) case 0 { // If n is even, store scalar in z for now. z := scalar } default { // If n is odd, store x in z for now. z := x } // Shifting right by 1 is like dividing by 2. let half := shr(1, scalar) for { // Shift n right by 1 before looping to halve it. n := shr(1, n) } n { // Shift n right by 1 each iteration to halve it. n := shr(1, n) } { // Revert immediately if x ** 2 would overflow. // Equivalent to iszero(eq(div(xx, x), x)) here. if shr(128, x) { revert(0, 0) } // Store x squared. let xx := mul(x, x) // Round to the nearest number. let xxRound := add(xx, half) // Revert if xx + half overflowed. if lt(xxRound, xx) { revert(0, 0) } // Set x to scaled xxRound. x := div(xxRound, scalar) // If n is even: if mod(n, 2) { // Compute z * x. let zx := mul(z, x) // If z * x overflowed: if iszero(eq(div(zx, x), z)) { // Revert if x is non-zero. if iszero(iszero(x)) { revert(0, 0) } } // Round to the nearest number. let zxRound := add(zx, half) // Revert if zx + half overflowed. if lt(zxRound, zx) { revert(0, 0) } // Return properly scaled zxRound. z := div(zxRound, scalar) } } } } } /*////////////////////////////////////////////////////////////// GENERAL NUMBER UTILITIES //////////////////////////////////////////////////////////////*/ function sqrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { let y := x // We start y at x, which will help us make our initial estimate. z := 181 // The "correct" value is 1, but this saves a multiplication later. // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. // We check y >= 2^(k + 8) but shift right by k bits // each branch to ensure that if x >= 256, then y >= 256. if iszero(lt(y, 0x10000000000000000000000000000000000)) { y := shr(128, y) z := shl(64, z) } if iszero(lt(y, 0x1000000000000000000)) { y := shr(64, y) z := shl(32, z) } if iszero(lt(y, 0x10000000000)) { y := shr(32, y) z := shl(16, z) } if iszero(lt(y, 0x1000000)) { y := shr(16, y) z := shl(8, z) } // Goal was to get z*z*y within a small factor of x. More iterations could // get y in a tighter range. Currently, we will have y in [256, 256*2^16). // We ensured y >= 256 so that the relative difference between y and y+1 is small. // That's not possible if x < 256 but we can just verify those cases exhaustively. // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256. // Correctness can be checked exhaustively for x < 256, so we assume y >= 256. // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps. // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256. // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18. // There is no overflow risk here since y < 2^136 after the first branch above. z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181. // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // If x+1 is a perfect square, the Babylonian method cycles between // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor. // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case. // If you don't care whether the floor or ceil square root is returned, you can remove this statement. z := sub(z, lt(div(x, z), z)) } } function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Mod x by y. Note this will return // 0 instead of reverting if y is zero. z := mod(x, y) } } function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { // Divide x by y. Note this will return // 0 instead of reverting if y is zero. r := div(x, y) } } function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Add 1 to x * y if x % y > 0. Note this will // return 0 instead of reverting if y is zero. z := add(gt(mod(x, y), 0), div(x, y)) } } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "../tokens/ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller. library SafeTransferLib { /*////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool success; /// @solidity memory-safe-assembly assembly { // Transfer the ETH and store if it succeeded or not. success := call(gas(), to, amount, 0, 0, 0, 0) } require(success, "ETH_TRANSFER_FAILED"); } /*////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool success; /// @solidity memory-safe-assembly assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata into memory, beginning with the function selector. mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000) mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "from" argument. mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type. success := and( // Set success to whether the call reverted, if not we check it either // returned exactly 1 (can't just be non-zero data), or had no return data. or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), // We use 100 because the length of our calldata totals up like so: 4 + 32 * 3. // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. // Counterintuitively, this call must be positioned second to the or() call in the // surrounding and() call or else returndatasize() will be zero during the computation. call(gas(), token, 0, freeMemoryPointer, 100, 0, 32) ) } require(success, "TRANSFER_FROM_FAILED"); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool success; /// @solidity memory-safe-assembly assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata into memory, beginning with the function selector. mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000) mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type. success := and( // Set success to whether the call reverted, if not we check it either // returned exactly 1 (can't just be non-zero data), or had no return data. or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2. // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. // Counterintuitively, this call must be positioned second to the or() call in the // surrounding and() call or else returndatasize() will be zero during the computation. call(gas(), token, 0, freeMemoryPointer, 68, 0, 32) ) } require(success, "TRANSFER_FAILED"); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool success; /// @solidity memory-safe-assembly assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata into memory, beginning with the function selector. mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000) mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type. success := and( // Set success to whether the call reverted, if not we check it either // returned exactly 1 (can't just be non-zero data), or had no return data. or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())), // We use 68 because the length of our calldata totals up like so: 4 + 32 * 2. // We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. // Counterintuitively, this call must be positioned second to the or() call in the // surrounding and() call or else returndatasize() will be zero during the computation. call(gas(), token, 0, freeMemoryPointer, 68, 0, 32) ) } require(success, "APPROVE_FAILED"); } }
{ "optimizer": { "enabled": true, "runs": 200 }, "viaIR": true, "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":"string","name":"_name","type":"string"},{"internalType":"string","name":"_symbol","type":"string"},{"internalType":"uint8","name":"_decimals","type":"uint8"},{"internalType":"uint256","name":"_supply","type":"uint256"},{"internalType":"string","name":"_description","type":"string"},{"internalType":"string","name":"_extended","type":"string"},{"internalType":"address","name":"_sPumpFoundry","type":"address"},{"internalType":"address","name":"_creator","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"Forbidden","type":"error"},{"inputs":[],"name":"NotSPumpFoundry","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"creator","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"description","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"extended","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"getHolders","outputs":[{"internalType":"address[]","name":"","type":"address[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getHoldersLength","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"offset","type":"uint256"},{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"getHoldersWithBalance","outputs":[{"internalType":"address[]","name":"","type":"address[]"},{"internalType":"uint256[]","name":"","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getMetadata","outputs":[{"components":[{"internalType":"contract SPumpToken","name":"token","type":"address"},{"internalType":"string","name":"name","type":"string"},{"internalType":"string","name":"symbol","type":"string"},{"internalType":"string","name":"description","type":"string"},{"internalType":"string","name":"extended","type":"string"},{"internalType":"address","name":"creator","type":"address"},{"internalType":"bool","name":"isGraduated","type":"bool"},{"internalType":"uint256","name":"mcap","type":"uint256"}],"internalType":"struct SPumpToken.Metadata","name":"","type":"tuple"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"holders","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isGraduated","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"isHolder","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isUnrestricted","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"sPumpFoundry","outputs":[{"internalType":"contract SPumpFoundry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"_isUnrestricted","type":"bool"}],"name":"setIsUnrestricted","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]
Deployed Bytecode
0x608060408181526004918236101561001657600080fd5b60009260e08435811c92836302d05d3f14610ff25750826306fdde0314610f41578263095ea7b314610eb657826318160ddd14610e9657826323b872dd14610c605782632a11ced014610c1e578263313ce56714610bdf5782633644e51514610bba5782636f3921ee14610b9b57826370a0823114610b625782637284e41614610b305782637a5b4f59146108c15782637ecebe00146108885782638911e26b146108635782638e846972146107f657826395c996411461078157826395d89b41146106965782639e5f26021461066f578263a9059cbb146104b8578263b569807114610483578263d4d7b19a14610444578263d505accf146101ec57508163db04aef4146101cd578163dd62ed3e14610180575063fffdf0341461013a57600080fd5b3461017c578160031936011261017c57517f00000000000000000000000056d456d96baf484026fc333b7e4794ca70dfe4566001600160a01b03168152602090f35b5080fd5b9050346101c957816003193601126101c957602092829161019f61128d565b6101a76112a8565b6001600160a01b03918216845291865283832091168252845220549051908152f35b8280fd5b50503461017c578160031936011261017c576020906008549051908152f35b849084346101c957816003193601126101c95761020761128d565b61020f6112a8565b9160443590606435926084359460ff86168096036104405760ff600a541615610430574285106103ed57610241611395565b9460018060a01b0380931696878a5260209660058852858b20998a549a60018c019055865193868a8601967f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c988528c8a880152169b8c606087015289608087015260a086015260c085015260c08452830167ffffffffffffffff94848210868311176103d9578188528451902061010085019261190160f01b845261010286015261012285015260428152610160840194818610908611176103c657848752519020835261018082015260a4356101a082015260c4356101c0909101528780528490889060809060015afa156103bc5786511696871515806103b3575b156103815786977f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9259596975283528087208688528352818188205551908152a380f35b83606492519162461bcd60e51b8352820152600e60248201526d24a72b20a624a22fa9a4a3a722a960911b6044820152fd5b5084881461033e565b81513d88823e3d90fd5b634e487b7160e01b8c5260418d5260248cfd5b50634e487b7160e01b8c5260418d5260248cfd5b825162461bcd60e51b81526020818b0152601760248201527f5045524d49545f444541444c494e455f455850495245440000000000000000006044820152606490fd5b8251631dd2188d60e31b81528990fd5b8780fd5b5050503461017c57602036600319011261017c5760209160ff9082906001600160a01b0361047061128d565b1681526009855220541690519015158152f35b5050503461017c576104b4906104a161049b3661130b565b90611888565b9051918291602083526020830190611321565b0390f35b5082843461066c578160031936011261066c576104d361128d565b926024359060ff600a541615610554575b5082846104f260209661191d565b338452600386528184206105078482546116f5565b90556001600160a01b0316808452600386529220805482019055825190815233907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef908590a35160018152f35b8351631500a3df60e21b81526020906001600160a01b03828285817f00000000000000000000000056d456d96baf484026fc333b7e4794ca70dfe45685165afa918215610662579083918793610633575b50875163eb56a3bd60e01b8152308682019081526001600160a01b038b1660208201529093849291839003604001918391165afa9182156106295785926105fc575b5050156104e4578351631dd2188d60e31b8152fd5b61061b9250803d10610622575b61061381836110be565b81019061137d565b86806105e7565b503d610609565b86513d87823e3d90fd5b610654919350823d841161065b575b61064c81836110be565b81019061135e565b91896105a5565b503d610642565b87513d88823e3d90fd5b80fd5b5050503461017c578160031936011261017c5760209061068d6117f8565b90519015158152f35b83853461066c578060031936011261066c578151918282600193600154946106bd86611035565b918285526020968760018216918260001461075a5750506001146106fe575b5050506104b492916106ef9103856110be565b51928284938452830190611268565b9190869350600183527fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf65b82841061074257505050820101816106ef6104b46106dc565b8054848a018601528895508794909301928101610729565b60ff19168782015293151560051b860190930193508492506106ef91506104b490506106dc565b509050346101c95760203660031901126101c9578035918215158093036107f2577f00000000000000000000000056d456d96baf484026fc333b7e4794ca70dfe4566001600160a01b031633036107e557505060ff8019600a5416911617600a5580f35b516307d0dbc760e11b8152fd5b8380fd5b83853461066c579061081061080a3661130b565b90611716565b90926108258351948486958652850190611321565b60208482036020860152602080855193848152019401925b82811061084c57505050500390f35b83518552869550938101939281019260010161083d565b5050503461017c578160031936011261017c5760209060ff600a541690519015158152f35b5050503461017c57602036600319011261017c5760209181906001600160a01b036108b161128d565b1681526005845220549051908152f35b848285346101c957826003193601126101c95780516108df8161106f565b8381528385606092836020820152838582015283808201528360808201528260a08201528260c0820152015260018060a01b0394825163bbe4f6db60e01b815230858201526101a09081816024818b7f00000000000000000000000056d456d96baf484026fc333b7e4794ca70dfe456165afa918215610af9578792610b03575b505083516306fdde0360e01b81529486868281305afa958615610af9578796610add575b5086855180926395d89b4160e01b825281305afa968715610ad2578097610aad575b5050866109b16117f8565b9160c00151938551976109c38961106f565b308952602089019788528689019081526109db6111a6565b828a019081526109e96110e0565b9160808b0192835260a08b0199857f00000000000000000000000022a4157428ad6001afce4a7fd20b964a9e40a012168b5260c08c019615158752878c0198895289519c8d9c60208e52511660208d015251610100809a8d01526101208c01610a5191611268565b905190601f1994858d830301908d0152610a6a91611268565b905190838b82030160808c0152610a8091611268565b9051918982030160a08a0152610a9591611268565b95511660c08701525115159085015251908301520390f35b610aca9297503d8091833e610ac281836110be565b81019061161c565b9487806109a6565b8551903d90823e3d90fd5b610af29196503d8089833e610ac281836110be565b9488610984565b85513d89823e3d90fd5b610b229250803d10610b29575b610b1a81836110be565b810190611550565b8780610960565b503d610b10565b5050503461017c578160031936011261017c576104b490610b4f6111a6565b9051918291602083526020830190611268565b5050503461017c57602036600319011261017c5760209181906001600160a01b03610b8b61128d565b1681526003845220549051908152f35b5050503461017c578160031936011261017c576104b490610b4f6110e0565b5050503461017c578160031936011261017c57602090610bd8611395565b9051908152f35b5050503461017c578160031936011261017c576020905160ff7f0000000000000000000000000000000000000000000000000000000000000012168152f35b509050346101c95760203660031901126101c957359160085483101561066c5750610c4a6020926112be565b905491519160018060a01b039160031b1c168152f35b5082843461066c57606036600319011261066c57610c7c61128d565b610c846112a8565b9360443560ff600a541615610da1575b907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef918560018060a01b0380951694858752602098848a958652838920837f00000000000000000000000056d456d96baf484026fc333b7e4794ca70dfe4561690818b5287526000199081868c205403610d88575b50610d138361191d565b888a52818752848a20338b52875285858b2054918203610d65575b50505086885260038552828820610d468582546116f5565b9055169586815260038452208181540190558551908152a35160018152f35b610d6e916116f5565b90888a528652838920338a528652838920558a8085610d2e565b898b52828852858b20908b52875280858b20558c610d09565b8451631500a3df60e21b81526020906001600160a01b0390828186817f00000000000000000000000056d456d96baf484026fc333b7e4794ca70dfe45686165afa908115610e8c578391610e29918991610e6f575b50895163eb56a3bd60e01b8152308882019081526001600160a01b038d1660208201529094859384928391604090910190565b0392165afa918215610662578692610e52575b505015610c9457508351631dd2188d60e31b8152fd5b610e689250803d106106225761061381836110be565b8780610e3c565b610e869150833d851161065b5761064c81836110be565b8b610df6565b88513d89823e3d90fd5b5050503461017c578160031936011261017c576020906002549051908152f35b5082843461066c578160031936011261066c57610ed161128d565b906024359060ff600a541615610f315783829160209633825287528181209460018060a01b0316948582528752205582519081527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925843392a35160018152f35b50505051631dd2188d60e31b8152fd5b83853461066c578060031936011261066c5781519182828354610f6381611035565b908184526020956001918760018216918260001461075a575050600114610f97575050506104b492916106ef9103856110be565b91908693508280527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5635b828410610fda57505050820101816106ef6104b46106dc565b8054848a018601528895508794909301928101610fc1565b85903461017c578160031936011261017c577f00000000000000000000000022a4157428ad6001afce4a7fd20b964a9e40a0126001600160a01b03168152602090f35b90600182811c92168015611065575b602083101461104f57565b634e487b7160e01b600052602260045260246000fd5b91607f1691611044565b610100810190811067ffffffffffffffff82111761108c57604052565b634e487b7160e01b600052604160045260246000fd5b6020810190811067ffffffffffffffff82111761108c57604052565b90601f8019910116810190811067ffffffffffffffff82111761108c57604052565b60405190600082600754916110f483611035565b808352926020906001908181169081156111825750600114611121575b505061111f925003836110be565b565b91509260076000527fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c688936000925b82841061116a575061111f9450505081016020013880611111565b8554888501830152948501948794509281019261114f565b9150506020925061111f94915060ff191682840152151560051b8201013880611111565b60405190600082600654916111ba83611035565b8083529260209060019081811690811561118257506001146111e457505061111f925003836110be565b91509260066000527ff652222313e28459528d920b65115c16c04f3efc82aaedc97be59f3f377c0d3f936000925b82841061122d575061111f9450505081016020013880611111565b85548885018301529485019487945092810192611212565b60005b8381106112585750506000910152565b8181015183820152602001611248565b9060209161128181518092818552858086019101611245565b601f01601f1916010190565b600435906001600160a01b03821682036112a357565b600080fd5b602435906001600160a01b03821682036112a357565b6008548110156112f55760086000527ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee30190600090565b634e487b7160e01b600052603260045260246000fd5b60409060031901126112a3576004359060243590565b90815180825260208080930193019160005b828110611341575050505090565b83516001600160a01b031685529381019392810192600101611333565b908160209103126112a357516001600160a01b03811681036112a35790565b908160209103126112a3575180151581036112a35790565b6000467f0000000000000000000000000000000000000000000000000000000000082750036113e357507fde88d3d6376a4c37f721e58fd878d24e85185465c3ae365144c982622aba59e190565b604051815482916113f382611035565b80825281602094858201946001908760018216918260001461151e5750506001146114c5575b50611426925003826110be565b51902091604051918201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f845260408301527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608301524660808301523060a083015260a0825260c082019082821067ffffffffffffffff8311176114b1575060405251902090565b634e487b7160e01b81526041600452602490fd5b87805286915087907f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5635b858310611506575050611426935082010138611419565b805483880185015286945088939092019181016114ef565b60ff1916885261142695151560051b85010192503891506114199050565b51906001600160a01b03821682036112a357565b80916101a092839103126112a35760405191820182811067ffffffffffffffff82111761108c5760405280516001600160a01b03811681036112a35782526020810151602083015260408101516040830152606081015160608301526080810151608083015260a081015160a083015260c081015160c083015260e081015160e083015261010080820151908301526101206115ed81830161153c565b908301526101406115ff81830161153c565b908301526101608082015190830152610180809101519082015290565b6020818303126112a357805167ffffffffffffffff918282116112a357019082601f830112156112a357815190811161108c5760405192611667601f8301601f1916602001856110be565b818452602082840101116112a3576116859160208085019101611245565b90565b67ffffffffffffffff811161108c5760051b60200190565b906116aa82611688565b6116b760405191826110be565b82815280926116c8601f1991611688565b0190602036910137565b919082018092116116df57565b634e487b7160e01b600052601160045260246000fd5b919082039182116116df57565b80518210156112f55760209160051b010190565b919060085490818410156117ca5761172e90846116d2565b908082116117c2575b5061174a61174584836116f5565b6116a0565b9061175861174585836116f5565b93805b828110611769575050509190565b8060406117776001936112be565b905490600391858060a01b0391831b1c16908161179d61179788876116f5565b8a611702565b52600091825260205220546117bb6117b585846116f5565b89611702565b520161175b565b905038611737565b505060405191506117da826110a2565b60008252604051916117eb836110a2565b6000835260003681379190565b60405163bbe4f6db60e01b81523060048201526001600160a01b03906101a09081816024817f00000000000000000000000056d456d96baf484026fc333b7e4794ca70dfe45687165afa90811561187c576101409260009261185f575b5050015116151590565b6118759250803d10610b2957610b1a81836110be565b3880611855565b6040513d6000823e3d90fd5b9060085490818310156119025761189f90836116d2565b908082116118fa575b506118b661174583836116f5565b91805b8281106118c65750505090565b806118d26001926112be565b838060a01b0391549060031b1c166118f36118ed85846116f5565b87611702565b52016118b9565b9050386118a8565b505050604051611911816110a2565b60008152600036813790565b9060018060a01b03809216600090808252600960205260ff60408320541615611947575b50509050565b600854936801000000000000000085101561199d5761196f85600160409697016008556112be565b819291549060031b9184831b921b19161790558152600960205220600160ff19825416179055803880611941565b634e487b7160e01b83526041600452602483fdfea264697066735822122026a7310de205104595122e97d70d81568ebefa0aecacc5a90075af269f8c16de64736f6c63430008190033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
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.