Transaction Hash:
Block:
17846987 at Aug-05-2023 06:29:23 AM +UTC
Transaction Fee:
0.003102593451334074 ETH
$7.05
Gas Used:
196,953 Gas / 15.752963658 Gwei
Emitted Events:
231 |
WETH9.Deposit( dst=InitialFairOffering, wad=4950000000000000 )
|
232 |
InitialFairOffering.MintDeposit( token=[Receiver] Inscription, ethAmount=4950000000000000, tokenAmount=1000000000000000000000, tokenLiquidity=388888888888888888888 )
|
233 |
Inscription.Transfer( from=0x0000000000000000000000000000000000000000, to=[Sender] 0xc4afbc756803c4838efe8ea1dd8b626a510f6461, value=1000000000000000000000 )
|
234 |
Inscription.Mint( sender=[Sender] 0xc4afbc756803c4838efe8ea1dd8b626a510f6461, to=[Sender] 0xc4afbc756803c4838efe8ea1dd8b626a510f6461, amount=1000000000000000000000, isVesting=False )
|
235 |
Inscription.Transfer( from=0x0000000000000000000000000000000000000000, to=InitialFairOffering, value=388888888888888888888 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x17fe21fA...3b73e7aA7 | 0.37395 Eth | 0.374 Eth | 0.00005 | ||
0x62700eA6...0AD901A4E | |||||
0x6F6A40a7...27A00E9F1 | |||||
0x95222290...5CC4BAfe5
Miner
| (beaverbuild) | 16.592992811287853878 Eth | 16.593012506587853878 Eth | 0.0000196953 | |
0xC02aaA39...83C756Cc2 | 3,345,289.484132234027770162 Eth | 3,345,289.489082234027770162 Eth | 0.00495 | ||
0xC4aFBc75...A510F6461 |
0.033151694993358075 Eth
Nonce: 206
|
0.025049101542024001 Eth
Nonce: 207
| 0.008102593451334074 |
Execution Trace
ETH 0.005
Inscription.mint( _to=0xC4aFBc756803C4838EFe8Ea1dd8B626A510F6461 )

ETH 0.00495
InitialFairOffering.CALL( )
- ETH 0.00495
WETH9.CALL( )
- ETH 0.00495
- ETH 0.00005
0x17fe21fab4784ecae27c7bb43d3d3cf3b73e7aa7.CALL( )
-
InitialFairOffering.setMintData( _addr=0xC4aFBc756803C4838EFe8Ea1dd8B626A510F6461, _ethAmount=4950000000000000, _tokenAmount=1000000000000000000000, _tokenLiquidity=388888888888888888888 )
File 1 of 3: Inscription
File 2 of 3: WETH9
File 3 of 3: InitialFairOffering
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.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}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * 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. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => 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 override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override 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 override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override 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 `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` 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 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); 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 `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `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. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer(address from, address to, uint256 amount) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by // decrementing then incrementing. _balances[to] += amount; } emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; unchecked { // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above. _balances[account] += amount; } emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; // Overflow not possible: amount <= accountBalance <= totalSupply. _totalSupply -= amount; } emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` 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. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 amount) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.18; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./libs/Logarithm.sol"; import "./libs/TransferHelper.sol"; import "./interfaces/IWhitelist.sol"; import "./interfaces/IInitialFairOffering.sol"; import "./interfaces/IInscription.sol"; import "./interfaces/ICustomizedCondition.sol"; import "./interfaces/ICustomizedVesting.sol"; // This is common token interface, get balance of owner's token by ERC20/ERC721/ERC1155. interface ICommonToken { function balanceOf(address owner) external returns(uint256); } // This contract is extended from ERC20 contract Inscription is ERC20 { using Logarithm for int256; IInscription.FERC20 private ferc20; mapping(address => uint256) private lastMintTimestamp; // record the last mint timestamp of account mapping(address => uint256) private lastMintFee; // record the last mint fee uint96 public totalRollups; event Mint(address sender, address to, uint amount, bool isVesting); event Burn(address sender, address to, uint amount); constructor( string memory _name, // token name string memory _tick, // token tick, same as symbol. must be 4 characters. uint128 _cap, // Max amount uint128 _limitPerMint, // Limitaion of each mint uint64 _inscriptionId, // Inscription Id uint32 _maxMintSize, // max mint size, that means the max mint quantity is: maxMintSize * limitPerMint. This is only availabe for non-frozen time token. uint40 _freezeTime, // The frozen time (interval) between two mints is a fixed number of seconds. You can mint, but you will need to pay an additional mint fee, and this fee will be double for each mint. address _onlyContractAddress, // Only addresses that hold these assets can mint uint128 _onlyMinQuantity, // Only addresses that the quantity of assets hold more than this amount can mint uint96 _baseFee, // base fee of the second mint after frozen interval. The first mint after frozen time is free. uint16 _fundingCommission, // commission rate of fund raising, 100 means 1% uint128 _crowdFundingRate, // rate of crowdfunding address _whitelist, // whitelist contract bool _isIFOMode, // receiving fee of crowdfunding uint16 _liquidityTokenPercent, address payable _ifoContractAddress, address payable _inscriptionFactory, uint96 _maxRollups, address _customizedConditionContractAddress, address _customizedVestingContractAddress ) ERC20(_name, _tick) { require(_cap >= _limitPerMint, "Limit per mint exceed cap"); ferc20.cap = _cap; ferc20.limitPerMint = _limitPerMint; ferc20.inscriptionId = _inscriptionId; ferc20.maxMintSize = _maxMintSize; ferc20.freezeTime = _freezeTime; ferc20.onlyContractAddress = _onlyContractAddress; ferc20.onlyMinQuantity = _onlyMinQuantity; ferc20.baseFee = _baseFee; ferc20.fundingCommission = _fundingCommission; ferc20.crowdFundingRate = _crowdFundingRate; ferc20.whitelist = _whitelist; ferc20.isIFOMode = _isIFOMode; ferc20.ifoContractAddress = _ifoContractAddress; ferc20.inscriptionFactory = _inscriptionFactory; ferc20.liquidityTokenPercent = _liquidityTokenPercent; ferc20.maxRollups = _maxRollups; ferc20.customizedConditionContractAddress = ICustomizedCondition(_customizedConditionContractAddress); ferc20.customizedVestingContractAddress = ICustomizedVesting(_customizedVestingContractAddress); } function mint(address _to) payable public { // Check if the quantity after mint will exceed the cap require(totalRollups + 1 <= ferc20.maxRollups, "Touched cap"); // Check if the assets in the msg.sender is satisfied require(ferc20.onlyContractAddress == address(0x0) || ICommonToken(ferc20.onlyContractAddress).balanceOf(msg.sender) >= ferc20.onlyMinQuantity, "You don't have required assets"); require(ferc20.whitelist == address(0x0) || IWhitelist(ferc20.whitelist).getStatus(address(this), msg.sender), "You are not in whitelist"); require(address(ferc20.customizedConditionContractAddress) == address(0x0) || ferc20.customizedConditionContractAddress.getStatus(address(this), msg.sender), "Customized condition not satisfied"); require(lastMintTimestamp[msg.sender] < block.timestamp, "Timestamp fail"); // The only line added on V2 uint256 tokenForInitialLiquidity = ferc20.isIFOMode ? ferc20.limitPerMint * ferc20.liquidityTokenPercent / (10000 - ferc20.liquidityTokenPercent) : 0; if(lastMintTimestamp[msg.sender] + ferc20.freezeTime > block.timestamp) { // The min extra tip is double of last mint fee lastMintFee[msg.sender] = lastMintFee[msg.sender] == 0 ? ferc20.baseFee : lastMintFee[msg.sender] * 2; // Check if the tip is high than the min extra fee require(msg.value >= ferc20.crowdFundingRate + lastMintFee[msg.sender], "Send ETH as fee and crowdfunding"); // Transfer the fee to the crowdfunding address if(ferc20.crowdFundingRate > 0) _dispatchFunding(_to, ferc20.crowdFundingRate, ferc20.limitPerMint, tokenForInitialLiquidity); // Transfer the tip to InscriptionFactory smart contract if(msg.value - ferc20.crowdFundingRate > 0) TransferHelper.safeTransferETH(ferc20.inscriptionFactory, msg.value - ferc20.crowdFundingRate); } else { // Transfer the fee to the crowdfunding address if(ferc20.crowdFundingRate > 0) { require(msg.value >= ferc20.crowdFundingRate, "Send ETH as crowdfunding"); if(msg.value - ferc20.crowdFundingRate > 0) TransferHelper.safeTransferETH(ferc20.inscriptionFactory, msg.value - ferc20.crowdFundingRate); _dispatchFunding(_to, ferc20.crowdFundingRate, ferc20.limitPerMint, tokenForInitialLiquidity); } // Out of frozen time, free mint. Reset the timestamp and mint times. lastMintFee[msg.sender] = 0; lastMintTimestamp[msg.sender] = block.timestamp; } // Do mint for the participant if(address(ferc20.customizedVestingContractAddress) == address(0x0)) { _mint(_to, ferc20.limitPerMint); emit Mint(msg.sender, _to, ferc20.limitPerMint, false); } else { _mint(address(ferc20.customizedVestingContractAddress), ferc20.limitPerMint); emit Mint(msg.sender, address(ferc20.customizedVestingContractAddress), ferc20.limitPerMint, true); ferc20.customizedVestingContractAddress.addAllocation(_to, ferc20.limitPerMint); } // Mint for initial liquidity if(tokenForInitialLiquidity > 0) _mint(ferc20.ifoContractAddress, tokenForInitialLiquidity); totalRollups++; } // batch mint is only available for non-frozen-time tokens function batchMint(address _to, uint32 _num) payable public { require(_num <= ferc20.maxMintSize, "exceed max mint size"); require(totalRollups + _num <= ferc20.maxRollups, "Touch cap"); require(ferc20.freezeTime == 0, "Batch mint only for non-frozen token"); require(ferc20.onlyContractAddress == address(0x0) || ICommonToken(ferc20.onlyContractAddress).balanceOf(msg.sender) >= ferc20.onlyMinQuantity, "You don't have required assets"); require(ferc20.whitelist == address(0x0) || IWhitelist(ferc20.whitelist).getStatus(address(this), msg.sender), "You are not in whitelist"); require(address(ferc20.customizedConditionContractAddress) == address(0x0) || ferc20.customizedConditionContractAddress.getStatus(address(this), msg.sender), "Customized condition not satisfied"); uint256 tokenForInitialLiquidity = ferc20.isIFOMode ? ferc20.limitPerMint * ferc20.liquidityTokenPercent / (10000 - ferc20.liquidityTokenPercent) : 0; if(ferc20.crowdFundingRate > 0) { require(msg.value >= ferc20.crowdFundingRate * _num, "Crowdfunding ETH not enough"); if(msg.value - ferc20.crowdFundingRate * _num > 0) TransferHelper.safeTransferETH(ferc20.inscriptionFactory, msg.value - ferc20.crowdFundingRate * _num); _dispatchFunding(_to, ferc20.crowdFundingRate * _num , ferc20.limitPerMint * _num, tokenForInitialLiquidity * _num); } for(uint256 i = 0; i < _num; i++) { // The reason for using for and repeat the operation is to let the average gas cost of batch mint same as single mint if(address(ferc20.customizedVestingContractAddress) == address(0x0)) { _mint(_to, ferc20.limitPerMint); emit Mint(msg.sender, _to, ferc20.limitPerMint, false); } else { _mint(address(ferc20.customizedVestingContractAddress), ferc20.limitPerMint); emit Mint(msg.sender, address(ferc20.customizedVestingContractAddress), ferc20.limitPerMint, true); ferc20.customizedVestingContractAddress.addAllocation(_to, ferc20.limitPerMint); } // Mint for initial liquidity if(tokenForInitialLiquidity > 0) { _mint(ferc20.ifoContractAddress, tokenForInitialLiquidity); } } totalRollups = totalRollups + _num; } function getMintFee(address _addr) public view returns(uint256 mintedTimes, uint256 nextMintFee) { if(lastMintTimestamp[_addr] + ferc20.freezeTime > block.timestamp) { int256 scale = 1e18; int256 halfScale = 5e17; // times = log_2(lastMintFee / baseFee) + 1 (if lastMintFee > 0) nextMintFee = lastMintFee[_addr] == 0 ? ferc20.baseFee : lastMintFee[_addr] * 2; mintedTimes = uint256((Logarithm.log2(int256(nextMintFee / ferc20.baseFee) * scale, scale, halfScale) + 1) / scale) + 1; } } function getFerc20Data() public view returns(IInscription.FERC20 memory) { return ferc20; } function getLastMintTimestamp(address _addr) public view returns(uint256) { return lastMintTimestamp[_addr]; } function getLastMintFee(address _addr) public view returns(uint256) { return lastMintFee[_addr]; } function transfer(address to, uint256 amount) public virtual override returns (bool) { require(!ferc20.isIFOMode || IInitialFairOffering(ferc20.ifoContractAddress).liquidityAdded(), "Only workable after public liquidity added"); address owner = _msgSender(); _transfer(owner, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { require(!ferc20.isIFOMode || IInitialFairOffering(ferc20.ifoContractAddress).liquidityAdded(), "Only workable after public liquidity added"); address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } function burn(address account, uint256 amount) public { require(account == msg.sender, "only owner can burn"); require(balanceOf(account) >= amount, "balance not enough"); _burn(account, amount); emit Burn(msg.sender, account, amount); } function burnFrom(address account, uint256 amount) public { uint256 currentAllowance = allowance(account, msg.sender); require(currentAllowance != type(uint256).max, "allowance exceed max"); require(currentAllowance >= amount, "allowance less than amount"); _approve(account, msg.sender, currentAllowance - amount); _burn(account, amount); emit Burn(msg.sender, account, amount); } function _dispatchFunding(address _to, uint256 _ethAmount, uint256 _tokenAmount, uint256 _tokenForLiquidity) private { require(ferc20.ifoContractAddress > address(0x0), "ifo address zero"); uint256 commission = _ethAmount * ferc20.fundingCommission / 10000; TransferHelper.safeTransferETH(ferc20.ifoContractAddress, _ethAmount - commission); if(commission > 0) TransferHelper.safeTransferETH(ferc20.inscriptionFactory, commission); IInitialFairOffering(ferc20.ifoContractAddress).setMintData( _to, uint128(_ethAmount - commission), uint128(_tokenAmount), uint128(_tokenForLiquidity) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ICustomizedCondition { function getStatus(address _tokenAddress, address _sender) external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ICustomizedVesting { function addAllocation(address recipient, uint amount) external; function removeAllocation(address recipient, uint amount) external; function claim() external; function available(address address_) external view returns (uint); function released(address address_) external view returns (uint); function outstanding(address address_) external view returns (uint); function setTokenAddress(address _tokenAddress) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IInscriptionFactory.sol"; interface IInitialFairOffering { function initialize(IInscriptionFactory.Token memory _token) external; function setMintData(address _addr, uint128 _ethAmount, uint128 _tokenAmount, uint128 _tokenLiquidity) external; function liquidityAdded() external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ICustomizedCondition.sol"; import "./ICustomizedVesting.sol"; interface IInscription { struct FERC20 { uint128 cap; // Max amount uint128 limitPerMint; // Limitaion of each mint address onlyContractAddress; // Only addresses that hold these assets can mint uint32 maxMintSize; // max mint size, that means the max mint quantity is: maxMintSize * limitPerMint uint64 inscriptionId; // Inscription Id uint128 onlyMinQuantity; // Only addresses that the quantity of assets hold more than this amount can mint uint128 crowdFundingRate; // rate of crowdfunding address whitelist; // whitelist contract uint40 freezeTime; // The frozen time (interval) between two mints is a fixed number of seconds. You can mint, but you will need to pay an additional mint fee, and this fee will be double for each mint. uint16 fundingCommission; // commission rate of fund raising, 1000 means 10% uint16 liquidityTokenPercent; bool isIFOMode; // receiving fee of crowdfunding address payable inscriptionFactory; // Inscription factory contract address uint128 baseFee; // base fee of the second mint after frozen interval. The first mint after frozen time is free. address payable ifoContractAddress; // Initial fair offering contract uint96 maxRollups; // Max rollups ICustomizedCondition customizedConditionContractAddress;// Customized condition for mint ICustomizedVesting customizedVestingContractAddress; // Customized vesting contract } function mint(address _to) payable external; function getFerc20Data() external view returns(FERC20 memory); function balanceOf(address owner) external view returns(uint256); function totalSupply() external view returns(uint256); function allowance(address owner, address spender) external view returns(uint256); function totalRollups() external view returns(uint256); function burn(address account, uint256 amount) external; function burnFrom(address account, uint256 amount) external; }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IInscriptionFactory { struct Token { uint128 cap; // Hard cap of token uint128 limitPerMint; // Limitation per mint address onlyContractAddress; uint32 maxMintSize; // max mint size, that means the max mint quantity is: maxMintSize * limitPerMint uint64 inscriptionId; // Inscription id uint128 onlyMinQuantity; uint128 crowdFundingRate; \t\t\t\t address addr; // Contract address of inscribed token uint40 freezeTime; uint40 timestamp; // Inscribe timestamp uint16 liquidityTokenPercent; // 10000 is 100% address ifoContractAddress; // Initial fair offerting contract uint16 refundFee; // To avoid the refund attack, deploy sets this fee rate uint40 startTime; uint40 duration; address customizedConditionContractAddress; // Customized condition for mint uint96 maxRollups; // max rollups address deployer; // Deployer string tick; // same as symbol in ERC20, max 5 chars, 10 bytes(80) uint16 liquidityEtherPercent; string name; // full name of token, max 16 chars, 32 bytes(256) address customizedVestingContractAddress; // Customized contract for token vesting bool isIFOMode; // is ifo mode bool isWhitelist; // is whitelst condition bool isVesting; bool isVoted; string logoUrl; // logo url, ifpfs cid, 64 chars, 128 bytes, 4 slots, ex.QmPK1s3pNYLi9ERiq3BDxKa4XosgWwFRQUydHUtz4YgpqB } function deploy( string memory _name, string memory _tick, uint256 _cap, uint256 _limitPerMint, uint256 _maxMintSize, // The max lots of each mint uint256 _freezeTime, // Freeze seconds between two mint, during this freezing period, the mint fee will be increased address _onlyContractAddress, // Only the holder of this asset can mint, optional uint256 _onlyMinQuantity, // The min quantity of asset for mint, optional uint256 _crowdFundingRate, address _crowdFundingAddress ) external returns (address _inscriptionAddress); function updateStockTick(string memory _tick, bool _status) external; function transferOwnership(address newOwner) external; function getIncriptionIdByAddress(address _addr) external view returns(uint256); function getIncriptionByAddress(address _addr) external view returns(Token memory tokens, uint256 totalSupplies, uint256 totalRollups); function fundingCommission() external view returns(uint16); function isExisting(string memory _tick) external view returns(bool); function isLiquidityAdded(address _addr) external view returns(bool); }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IWhitelist { function getStatus(address _tokenAddress, address _participant) external view returns(bool); }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Logarithm { /// @notice Finds the zero-based index of the first one in the binary representation of x. /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set /// @param x The uint256 number for which to find the index of the most significant bit. /// @return msb The index of the most significant bit as an uint256. function mostSignificantBit(uint256 x) public pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; } if (x >= 2**16) { x >>= 16; msb += 16; } if (x >= 2**8) { x >>= 8; msb += 8; } if (x >= 2**4) { x >>= 4; msb += 4; } if (x >= 2**2) { x >>= 2; msb += 2; } if (x >= 2**1) { // No need to shift x any more. msb += 1; } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than zero. /// /// Caveats: /// - The results are nor perfectly accurate to the last digit, due to the lossy precision of the iterative approximation. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as a signed 59.18-decimal fixed-point number. function log2(int256 x, int256 scale, int256 halfScale) public pure returns (int256 result) { require(x > 0); unchecked { // This works because log2(x) = -log2(1/x). int256 sign; if (x >= scale) { sign = 1; } else { sign = -1; // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. assembly { x := div(1000000000000000000000000000000000000, x) } } // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = mostSignificantBit(uint256(x / scale)); // The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1. result = int256(n) * scale; // This is y = x * 2^(-n). int256 y = x >> n; // If y = 1, the fractional part is zero. if (y == scale) { return result * sign; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (int256 delta = int256(halfScale); delta > 0; delta >>= 1) { y = (y * y) / scale; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * scale) { // Add the 2^(-m) factor to the logarithm. result += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } result *= sign; } } }// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } }
File 2 of 3: WETH9
// Copyright (C) 2015, 2016, 2017 Dapphub // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity ^0.4.18; contract WETH9 { string public name = "Wrapped Ether"; string public symbol = "WETH"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); event Deposit(address indexed dst, uint wad); event Withdrawal(address indexed src, uint wad); mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; function() public payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; Deposit(msg.sender, msg.value); } function withdraw(uint wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; msg.sender.transfer(wad); Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint) { return this.balance; } function approve(address guy, uint wad) public returns (bool) { allowance[msg.sender][guy] = wad; Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom(address src, address dst, uint wad) public returns (bool) { require(balanceOf[src] >= wad); if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; Transfer(src, dst, wad); return true; } } /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. */
File 3 of 3: InitialFairOffering
// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title The interface for the Uniswap V3 Factory /// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees interface IUniswapV3Factory { /// @notice Emitted when the owner of the factory is changed /// @param oldOwner The owner before the owner was changed /// @param newOwner The owner after the owner was changed event OwnerChanged(address indexed oldOwner, address indexed newOwner); /// @notice Emitted when a pool is created /// @param token0 The first token of the pool by address sort order /// @param token1 The second token of the pool by address sort order /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks /// @param pool The address of the created pool event PoolCreated( address indexed token0, address indexed token1, uint24 indexed fee, int24 tickSpacing, address pool ); /// @notice Emitted when a new fee amount is enabled for pool creation via the factory /// @param fee The enabled fee, denominated in hundredths of a bip /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing); /// @notice Returns the current owner of the factory /// @dev Can be changed by the current owner via setOwner /// @return The address of the factory owner function owner() external view returns (address); /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee /// @return The tick spacing function feeAmountTickSpacing(uint24 fee) external view returns (int24); /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order /// @param tokenA The contract address of either token0 or token1 /// @param tokenB The contract address of the other token /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip /// @return pool The pool address function getPool( address tokenA, address tokenB, uint24 fee ) external view returns (address pool); /// @notice Creates a pool for the given two tokens and fee /// @param tokenA One of the two tokens in the desired pool /// @param tokenB The other of the two tokens in the desired pool /// @param fee The desired fee for the pool /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments /// are invalid. /// @return pool The address of the newly created pool function createPool( address tokenA, address tokenB, uint24 fee ) external returns (address pool); /// @notice Updates the owner of the factory /// @dev Must be called by the current owner /// @param _owner The new owner of the factory function setOwner(address _owner) external; /// @notice Enables a fee amount with the given tickSpacing /// @dev Fee amounts may never be removed once enabled /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6) /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount function enableFeeAmount(uint24 fee, int24 tickSpacing) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.18; import "./interfaces/IInscription.sol"; import "./interfaces/IInscriptionFactory.sol"; import "./interfaces/INonfungiblePositionManager.sol"; import "./interfaces/IWETH.sol"; import "./libs/TransferHelper.sol"; import "./libs/PriceFormat.sol"; import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol"; import "./interfaces/ICustomizedVesting.sol"; // This contract will be created while deploying // The liquidity can not be removed contract InitialFairOffering { int24 private constant MIN_TICK = -887272; // add liquidity with full range int24 private constant MAX_TICK = -MIN_TICK; // add liquidity with full range int24 public constant TICK_SPACING = 60; // Tick space is 60 uint24 public constant UNISWAP_FEE = 3000; INonfungiblePositionManager public constant nonfungiblePositionManager = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); IUniswapV3Factory public uniswapV3Factory = IUniswapV3Factory(0x1F98431c8aD98523631AE4a59f267346ea31F984); IWETH public weth; IInscriptionFactory public inscriptionFactory; bool public liquidityAdded = false; struct MintData { uint128 ethAmount; // eth payed by user(deduce commission) uint128 tokenAmount; // token minted by user uint128 tokenLiquidity; // token liquidity saved in this contract } mapping(address => MintData) public mintData; struct Deposit { address owner; uint128 liquidity; address token0; address token1; } mapping(uint => Deposit) public deposits; // uint - tokenId of liquidity NFT mapping(uint => uint) public tokenIds; uint public tokenIdCount; uint public totalBackToDeployAmount; uint public totalRefundedAmount; struct Position { uint96 nonce; address operator; address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint128 liquidity; uint256 feeGrowthInside0LastX128; uint256 feeGrowthInside1LastX128; uint128 tokensOwed0; uint128 tokensOwed1; uint256 tokenId; } struct Pool { address pool; address token0; address token1; uint uintRate; uint160 sqrtPriceX96; } Pool public poolData; IInscriptionFactory.Token public token; event MintDeposit( address token, uint128 ethAmount, uint128 tokenAmount, uint128 tokenLiquidity ); event Refund( address sender, uint128 etherAmount, uint128 senderToken, uint128 liquidityToken, uint16 refundFee ); // This contract can be only created by InscriptionFactory contract constructor(address _inscriptionFactory, address _weth) { inscriptionFactory = IInscriptionFactory(_inscriptionFactory); weth = IWETH(_weth); } receive() external payable { // Change all received ETH to WETH if (msg.sender != address(weth)) TransferHelper.safeTransferETH(address(weth), msg.value); } function initialize(IInscriptionFactory.Token memory _token) public { // Check if the deployer has sent the liquidity ferc20 tokens require( address(inscriptionFactory) == msg.sender, "Only inscription factory allowed" ); require(_token.inscriptionId > 0, "token data wrong"); token = _token; _initializePool(address(weth), _token.addr); } function _initializePool( address _weth, address _token ) private returns ( address _token0, address _token1, uint _uintRate, uint160 _sqrtPriceX96, address _pool ) { _token0 = _token; _token1 = _weth; _uintRate = PriceFormat.getInitialRate( token.crowdFundingRate, token.liquidityEtherPercent, token.liquidityTokenPercent, token.limitPerMint ); // weth quantity per token require(_uintRate > 0, "uint rate zero"); if (_token < _weth) { _sqrtPriceX96 = PriceFormat.priceToSqrtPriceX96( int(_uintRate), TICK_SPACING ); } else { _token0 = _weth; _token1 = _token; _uintRate = 10 ** 36 / _uintRate; // token quantity per weth _sqrtPriceX96 = PriceFormat.priceToSqrtPriceX96( int(_uintRate), TICK_SPACING ); } _pool = nonfungiblePositionManager.createAndInitializePoolIfNecessary( _token0, _token1, UNISWAP_FEE, _sqrtPriceX96 ); poolData = Pool(_pool, _token0, _token1, _uintRate, _sqrtPriceX96); } function addLiquidity(uint16 slippage) public { require(slippage >= 0 && slippage <= 10000, "slippage error"); require( IInscription(token.addr).totalRollups() >= token.maxRollups, "mint not finished" ); require( uniswapV3Factory.getPool(address(weth), token.addr, UNISWAP_FEE) > address(0x0), "Pool not exist, create pool in uniswapV3 manually" ); require(token.liquidityEtherPercent > 0, "no liquidity add"); uint256 totalTokenLiquidity = IInscription(token.addr).balanceOf( address(this) ); require(totalTokenLiquidity > 0, "no token in fto contract"); uint256 balanceOfWeth = IWETH(weth).balanceOf(address(this)); require(balanceOfWeth > 0, "no eth in fto contract"); // Send ether back to deployer, the eth liquidity is based on the balance of this contract. So, anyone can send eth to this contract uint256 backToDeployAmount = (balanceOfWeth * (10000 - token.liquidityEtherPercent)) / 10000; uint256 maxBackToDeployAmount = (token.maxRollups * (10000 - inscriptionFactory.fundingCommission()) * token.crowdFundingRate * (10000 - token.liquidityEtherPercent)) / 100000000; uint256 sum = totalBackToDeployAmount + backToDeployAmount; if (sum <= maxBackToDeployAmount) { weth.withdraw(backToDeployAmount); // Change WETH to ETH TransferHelper.safeTransferETH(token.deployer, backToDeployAmount); totalBackToDeployAmount += backToDeployAmount; } else { backToDeployAmount = 0; } liquidityAdded = true; // allow the transferring of token _mintNewPosition( balanceOfWeth - backToDeployAmount, totalTokenLiquidity, // ferc20 token amount MIN_TICK, MAX_TICK, slippage ); } function refund() public { require(mintData[msg.sender].ethAmount > 0, "you have not mint"); require( IInscription(token.addr).totalRollups() < token.maxRollups, "mint has finished" ); if ( token.isVesting && token.customizedVestingContractAddress != address(0x0) ) { // standard fto mode ICustomizedVesting(token.customizedVestingContractAddress) .removeAllocation(msg.sender, mintData[msg.sender].tokenAmount); } else { // not fto mode // check balance and allowance of tokens, if the balance or allowance is smaller than the what he/she get while do mint, the refund fail require( IInscription(token.addr).balanceOf(msg.sender) >= mintData[msg.sender].tokenAmount, "Your balance token not enough" ); require( IInscription(token.addr).allowance(msg.sender, address(this)) >= mintData[msg.sender].tokenAmount, "Your allowance not enough" ); // Burn the tokens from msg.sender IInscription(token.addr).burnFrom( msg.sender, mintData[msg.sender].tokenAmount ); } // Burn the token liquidity in this contract uint128 refundToken = (mintData[msg.sender].tokenLiquidity * token.refundFee) / 10000; IInscription(token.addr).burn( address(this), mintData[msg.sender].tokenLiquidity - refundToken ); // Refund Ether uint128 refundEth = (mintData[msg.sender].ethAmount * token.refundFee) / 10000; weth.withdraw(mintData[msg.sender].ethAmount - refundEth); // Change WETH to ETH TransferHelper.safeTransferETH( msg.sender, mintData[msg.sender].ethAmount - refundEth ); // Send balance to donator totalRefundedAmount = totalRefundedAmount + mintData[msg.sender].tokenAmount + mintData[msg.sender].tokenLiquidity - refundToken; emit Refund( msg.sender, mintData[msg.sender].ethAmount - refundEth, mintData[msg.sender].tokenAmount, mintData[msg.sender].tokenLiquidity - refundToken, token.refundFee ); mintData[msg.sender].tokenAmount = 0; mintData[msg.sender].tokenLiquidity = 0; mintData[msg.sender].ethAmount = 0; } function positions( uint128 pageNo, uint128 pageSize ) public view returns (Position[] memory _positions) { require(pageNo > 0 && pageSize > 0, "pageNo and size can not be zero"); Position[] memory filtered = new Position[](tokenIdCount); uint128 count = 0; for (uint128 i = 0; i < tokenIdCount; i++) { ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) = nonfungiblePositionManager.positions(tokenIds[i]); if (liquidity == 0) continue; filtered[count] = Position( nonce, operator, token0, token1, fee, tickLower, tickUpper, liquidity, feeGrowthInside0LastX128, feeGrowthInside1LastX128, tokensOwed0, tokensOwed1, tokenIds[i] ); count++; } uint128 startIndex = (pageNo - 1) * pageSize; if (startIndex > count) return new Position[](0); _positions = new Position[](pageSize); uint128 index; for (uint128 i = 0; i < filtered.length; i++) { if (i >= startIndex && i < startIndex + pageSize) { _positions[index] = filtered[i]; index++; } else continue; } } // Call from Inscription::mint only function setMintData( address _addr, uint128 _ethAmount, uint128 _tokenAmount, uint128 _tokenLiquidity ) public { require(msg.sender == token.addr, "Only call from inscription allowed"); require( _ethAmount > 0 && _tokenAmount > 0 && _tokenLiquidity > 0 && _addr > address(0x0), "setEtherLiquidity wrong params" ); mintData[_addr].ethAmount = mintData[_addr].ethAmount + _ethAmount; mintData[_addr].tokenAmount = mintData[_addr].tokenAmount + _tokenAmount; mintData[_addr].tokenLiquidity = mintData[_addr].tokenLiquidity + _tokenLiquidity; emit MintDeposit(msg.sender, _ethAmount, _tokenAmount, _tokenLiquidity); } function collectFee( uint256 _tokenId ) public returns (uint256 amount0, uint256 amount1) { // Collect INonfungiblePositionManager.CollectParams memory params = INonfungiblePositionManager.CollectParams({ tokenId: _tokenId, recipient: address(this), amount0Max: type(uint128).max, amount1Max: type(uint128).max }); (amount0, amount1) = nonfungiblePositionManager.collect(params); } function _mintNewPosition( uint amount0ToAdd, uint amount1ToAdd, int24 lowerTick, int24 upperTick, uint16 slippage ) private returns (uint tokenId, uint128 liquidity, uint amount0, uint amount1) { // If weth < ferc20, set token0/amount0 is weth and token1/amount1 is ferc20 // Otherwise, set token0/amount0 is ferc20, and token1/amount1 is weth address _token0; address _token1; uint _amount0; uint _amount1; int24 _lowerTick; int24 _upperTick; if (address(weth) > token.addr) { _token0 = token.addr; _token1 = address(weth); _amount0 = amount1ToAdd; _amount1 = amount0ToAdd; _lowerTick = lowerTick; _upperTick = upperTick; } else { _token0 = address(weth); _token1 = token.addr; _amount0 = amount0ToAdd; _amount1 = amount1ToAdd; _lowerTick = -upperTick; _upperTick = -lowerTick; } // Approve the position manager TransferHelper.safeApprove( _token0, address(nonfungiblePositionManager), _amount0 ); TransferHelper.safeApprove( _token1, address(nonfungiblePositionManager), _amount1 ); INonfungiblePositionManager.MintParams memory params = INonfungiblePositionManager .MintParams({ token0: _token0, token1: _token1, fee: UNISWAP_FEE, tickLower: (lowerTick / TICK_SPACING) * TICK_SPACING, // full range tickUpper: (upperTick / TICK_SPACING) * TICK_SPACING, amount0Desired: _amount0, amount1Desired: _amount1, amount0Min: (_amount0 * (10000 - slippage)) / 10000, // slipage amount1Min: (_amount1 * (10000 - slippage)) / 10000, recipient: address(this), deadline: block.timestamp }); (tokenId, liquidity, amount0, amount1) = nonfungiblePositionManager .mint(params); _createDeposit(msg.sender, tokenId); if (amount0 < _amount0) { TransferHelper.safeApprove( _token0, address(nonfungiblePositionManager), 0 ); } if (amount1 < _amount1) { TransferHelper.safeApprove( _token1, address(nonfungiblePositionManager), 0 ); } } function _createDeposit(address _operator, uint _tokenId) private { ( , , address token0, address token1, , , , uint128 liquidity, , , , ) = nonfungiblePositionManager.positions(_tokenId); if (deposits[_tokenId].owner == address(0x0)) { tokenIds[tokenIdCount] = _tokenId; tokenIdCount++; } deposits[_tokenId] = Deposit({ owner: _operator, liquidity: liquidity, token0: token0, token1: token1 }); } // function onERC721Received( // address operator, // address from, // uint tokenId, // bytes calldata // ) public returns (bytes4) { // _createDeposit(operator, tokenId); // return IERC721Receiver.onERC721Received.selector; // } // Add liquidity with lower/upper tick // function addLiquidity( // uint16 ratio, // The ratio of balance of eths and tokens will be added to liquidity pool // int24 lowerTick, // int24 upperTick, // uint16 slippage // ) public { // require(ratio > 0 && ratio <= 10000, "ratio error"); // require(slippage >= 0 && slippage <= 10000, "slippage error"); // require(IInscription(token.addr).balanceOf(msg.sender) >= token.minBalanceToManagerLiquidity, "Balance not enough to add liquidity"); // require(IInscription(token.addr).totalRollups() >= token.maxRollups, "mint not finished"); // require(uniswapV3Factory.getPool(address(weth), token.addr, UNISWAP_FEE) > address(0x0), "Pool not exist, create pool in uniswapV3 manually"); // require(token.liquidityEtherPercent > 0, "no liquidity add"); // uint256 totalTokenLiquidity = IInscription(token.addr).balanceOf(address(this)); // require(totalTokenLiquidity > 0, "no token in fto"); // uint256 balanceOfWeth = IWETH(weth).balanceOf(address(this)); // require(balanceOfWeth > 0, "no eth in fto"); // // Send ether back to deployer, the eth liquidity is based on the balance of this contract. So, anyone can send eth to this contract // uint256 backToDeployAmount = balanceOfWeth * (10000 - token.liquidityEtherPercent) * ratio / 100000000; // uint256 maxBackToDeployAmount = token.maxRollups * (10000 - inscriptionFactory.fundingCommission()) * token.crowdFundingRate * (10000 - token.liquidityEtherPercent) / 100000000; // uint256 sum = totalBackToDeployAmount + backToDeployAmount; // if(sum <= maxBackToDeployAmount) { // weth.withdraw(backToDeployAmount); // Change WETH to ETH // TransferHelper.safeTransferETH(token.deployer, backToDeployAmount); // totalBackToDeployAmount += backToDeployAmount; // } else { // backToDeployAmount = 0; // } // _mintNewPosition( // balanceOfWeth * ratio / 10000 - backToDeployAmount, // totalTokenLiquidity * ratio / 10000, // ferc20 token amount // lowerTick == 0 ? MIN_TICK : lowerTick, // upperTick == 0 ? MAX_TICK : upperTick, // slippage // ); // } // function decreaseLiquidity( // uint tokenId // ) public returns (uint amount0, uint amount1) { // require(IInscription(token.addr).totalRollups() >= token.maxRollups, "mint not finished"); // require(IInscription(token.addr).balanceOf(msg.sender) >= token.minBalanceToManagerLiquidity, "Balance not enough to decrease liquidity"); // uint128 decreaseLiquidityAmount = deposits[tokenId].liquidity; // INonfungiblePositionManager.DecreaseLiquidityParams memory params = INonfungiblePositionManager.DecreaseLiquidityParams({ // tokenId: tokenId, // liquidity: decreaseLiquidityAmount, // amount0Min: 0, // amount1Min: 0, // deadline: block.timestamp // }); // (amount0, amount1) = nonfungiblePositionManager.decreaseLiquidity(params); // // Collect // INonfungiblePositionManager.CollectParams memory params2 = INonfungiblePositionManager.CollectParams({ // tokenId: tokenId, // recipient: address(this), // amount0Max: type(uint128).max, // amount1Max: type(uint128).max // }); // (amount0, amount1) = nonfungiblePositionManager.collect(params2); // deposits[tokenId].liquidity = 0; // } // function setMinBalanceToManagerLiquidity(uint128 _minBalanceToManagerLiquidity) public { // require(msg.sender == token.deployer, "Call must be deployer"); // token.minBalanceToManagerLiquidity = _minBalanceToManagerLiquidity; // } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ICustomizedCondition { function getStatus(address _tokenAddress, address _sender) external view returns(bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ICustomizedVesting { function addAllocation(address recipient, uint amount) external; function removeAllocation(address recipient, uint amount) external; function claim() external; function available(address address_) external view returns (uint); function released(address address_) external view returns (uint); function outstanding(address address_) external view returns (uint); function setTokenAddress(address _tokenAddress) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ICustomizedCondition.sol"; import "./ICustomizedVesting.sol"; interface IInscription { struct FERC20 { uint128 cap; // Max amount uint128 limitPerMint; // Limitaion of each mint address onlyContractAddress; // Only addresses that hold these assets can mint uint32 maxMintSize; // max mint size, that means the max mint quantity is: maxMintSize * limitPerMint uint64 inscriptionId; // Inscription Id uint128 onlyMinQuantity; // Only addresses that the quantity of assets hold more than this amount can mint uint128 crowdFundingRate; // rate of crowdfunding address whitelist; // whitelist contract uint40 freezeTime; // The frozen time (interval) between two mints is a fixed number of seconds. You can mint, but you will need to pay an additional mint fee, and this fee will be double for each mint. uint16 fundingCommission; // commission rate of fund raising, 1000 means 10% uint16 liquidityTokenPercent; bool isIFOMode; // receiving fee of crowdfunding address payable inscriptionFactory; // Inscription factory contract address uint128 baseFee; // base fee of the second mint after frozen interval. The first mint after frozen time is free. address payable ifoContractAddress; // Initial fair offering contract uint96 maxRollups; // Max rollups ICustomizedCondition customizedConditionContractAddress;// Customized condition for mint ICustomizedVesting customizedVestingContractAddress; // Customized vesting contract } function mint(address _to) payable external; function getFerc20Data() external view returns(FERC20 memory); function balanceOf(address owner) external view returns(uint256); function totalSupply() external view returns(uint256); function allowance(address owner, address spender) external view returns(uint256); function totalRollups() external view returns(uint256); function burn(address account, uint256 amount) external; function burnFrom(address account, uint256 amount) external; }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IInscriptionFactory { struct Token { uint128 cap; // Hard cap of token uint128 limitPerMint; // Limitation per mint address onlyContractAddress; uint32 maxMintSize; // max mint size, that means the max mint quantity is: maxMintSize * limitPerMint uint64 inscriptionId; // Inscription id uint128 onlyMinQuantity; uint128 crowdFundingRate; \t\t\t\t address addr; // Contract address of inscribed token uint40 freezeTime; uint40 timestamp; // Inscribe timestamp uint16 liquidityTokenPercent; // 10000 is 100% address ifoContractAddress; // Initial fair offerting contract uint16 refundFee; // To avoid the refund attack, deploy sets this fee rate uint40 startTime; uint40 duration; address customizedConditionContractAddress; // Customized condition for mint uint96 maxRollups; // max rollups address deployer; // Deployer string tick; // same as symbol in ERC20, max 5 chars, 10 bytes(80) uint16 liquidityEtherPercent; string name; // full name of token, max 16 chars, 32 bytes(256) address customizedVestingContractAddress; // Customized contract for token vesting bool isIFOMode; // is ifo mode bool isWhitelist; // is whitelst condition bool isVesting; bool isVoted; string logoUrl; // logo url, ifpfs cid, 64 chars, 128 bytes, 4 slots, ex.QmPK1s3pNYLi9ERiq3BDxKa4XosgWwFRQUydHUtz4YgpqB } function deploy( string memory _name, string memory _tick, uint256 _cap, uint256 _limitPerMint, uint256 _maxMintSize, // The max lots of each mint uint256 _freezeTime, // Freeze seconds between two mint, during this freezing period, the mint fee will be increased address _onlyContractAddress, // Only the holder of this asset can mint, optional uint256 _onlyMinQuantity, // The min quantity of asset for mint, optional uint256 _crowdFundingRate, address _crowdFundingAddress ) external returns (address _inscriptionAddress); function updateStockTick(string memory _tick, bool _status) external; function transferOwnership(address newOwner) external; function getIncriptionIdByAddress(address _addr) external view returns(uint256); function getIncriptionByAddress(address _addr) external view returns(Token memory tokens, uint256 totalSupplies, uint256 totalRollups); function fundingCommission() external view returns(uint16); function isExisting(string memory _tick) external view returns(bool); function isLiquidityAdded(address _addr) external view returns(bool); }// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface INonfungiblePositionManager { struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint amount0Desired; uint amount1Desired; uint amount0Min; uint amount1Min; address recipient; uint deadline; } function mint( MintParams calldata params ) external payable returns (uint tokenId, uint128 liquidity, uint amount0, uint amount1); struct IncreaseLiquidityParams { uint tokenId; uint amount0Desired; uint amount1Desired; uint amount0Min; uint amount1Min; uint deadline; } function increaseLiquidity( IncreaseLiquidityParams calldata params ) external payable returns (uint128 liquidity, uint amount0, uint amount1); struct DecreaseLiquidityParams { uint tokenId; uint128 liquidity; uint amount0Min; uint amount1Min; uint deadline; } function decreaseLiquidity( DecreaseLiquidityParams calldata params ) external payable returns (uint amount0, uint amount1); struct CollectParams { uint tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } function collect( CollectParams calldata params ) external payable returns (uint amount0, uint amount1); function positions( uint256 tokenId ) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); function createAndInitializePoolIfNecessary( address token0, address token1, uint24 fee, uint160 sqrtPriceX96 ) external returns (address pool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // import "./IERC20.sol"; interface IWETH { function transfer(address recipient, uint amount) external returns (bool); function balanceOf(address account) external view returns (uint); function totalSupply() external view returns(uint); function deposit() external payable; function withdraw(uint amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; library Logarithm { /// @notice Finds the zero-based index of the first one in the binary representation of x. /// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set /// @param x The uint256 number for which to find the index of the most significant bit. /// @return msb The index of the most significant bit as an uint256. function mostSignificantBit(uint256 x) public pure returns (uint256 msb) { if (x >= 2**128) { x >>= 128; msb += 128; } if (x >= 2**64) { x >>= 64; msb += 64; } if (x >= 2**32) { x >>= 32; msb += 32; } if (x >= 2**16) { x >>= 16; msb += 16; } if (x >= 2**8) { x >>= 8; msb += 8; } if (x >= 2**4) { x >>= 4; msb += 4; } if (x >= 2**2) { x >>= 2; msb += 2; } if (x >= 2**1) { // No need to shift x any more. msb += 1; } } /// @notice Calculates the binary logarithm of x. /// /// @dev Based on the iterative approximation algorithm. /// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation /// /// Requirements: /// - x must be greater than zero. /// /// Caveats: /// - The results are nor perfectly accurate to the last digit, due to the lossy precision of the iterative approximation. /// /// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm. /// @return result The binary logarithm as a signed 59.18-decimal fixed-point number. function log2(int256 x, int256 scale, int256 halfScale) public pure returns (int256 result) { require(x > 0); unchecked { // This works because log2(x) = -log2(1/x). int256 sign; if (x >= scale) { sign = 1; } else { sign = -1; // Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE. assembly { x := div(1000000000000000000000000000000000000, x) } } // Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n). uint256 n = mostSignificantBit(uint256(x / scale)); // The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow // because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1. result = int256(n) * scale; // This is y = x * 2^(-n). int256 y = x >> n; // If y = 1, the fractional part is zero. if (y == scale) { return result * sign; } // Calculate the fractional part via the iterative approximation. // The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster. for (int256 delta = int256(halfScale); delta > 0; delta >>= 1) { y = (y * y) / scale; // Is y^2 > 2 and so in the range [2,4)? if (y >= 2 * scale) { // Add the 2^(-m) factor to the logarithm. result += delta; // Corresponds to z/2 on Wikipedia. y >>= 1; } } result *= sign; } } }// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.9.0; import "./TickMath.sol"; import "./Logarithm.sol"; library PriceFormat { function getInitialRate( uint128 _crowdFundingRate, uint16 _etherToLiquidityPercent, uint16 _tokenToLiquidityPercent, uint128 _limitPerMint ) internal pure returns(uint) { // return _crowdFundingRate * _etherToLiquidityPercent * (10000 - _tokenToLiquidityPercent) * 10**14 / _tokenToLiquidityPercent / _limitPerMint; // To avoid the result is zero, the params must satisfy the following condition: // _crowdFundingRate * 10**18 > _limitPerMint uint128 precision = 10**12; return (_crowdFundingRate / precision) * _etherToLiquidityPercent * (10000 - _tokenToLiquidityPercent) * 10**14 / _tokenToLiquidityPercent / (_limitPerMint / precision); } function tickToSqrtPriceX96(int24 _tick) internal pure returns(uint160) { return TickMath.getSqrtRatioAtTick(_tick); } function priceToTick(int256 _price, int24 _tickSpace) internal pure returns(int24) { // math.log(10**18,2) * 10**18 = 59794705707972520000 // math.log(1.0001,2) * 10**18 = 144262291094538 return round((Logarithm.log2(_price * 1e18, 1e18, 5e17) - 59794705707972520000 ), (int(144262291094538) * _tickSpace)) * _tickSpace; } function priceToSqrtPriceX96(int256 _price, int24 _tickSpace) internal pure returns(uint160) { return tickToSqrtPriceX96(priceToTick(_price, _tickSpace)); } function round(int256 _a, int256 _b) internal pure returns(int24) { return int24(10000 * _a / _b % 10000 > 10000 / 2 ? _a / _b + 1 : _a / _b); } }// SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0 <0.9.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = -887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = -MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { // uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick)); int256 absTick = tick < 0 ? int256(-int256(tick)) : int256(int256(tick)); require(absTick <= int256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require( success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } }