Transaction Hash:
Block:
14352694 at Mar-09-2022 12:53:52 PM +UTC
Transaction Fee:
0.0007928941746672 ETH
$3.00
Gas Used:
46,777 Gas / 16.9505136 Gwei
Emitted Events:
219 |
StripToken.Transfer( from=[Sender] 0x1e6c27e91ec9fcf3353896b855dc377e419ad4c6, to=ERC20StakingPool, value=25000000000000000000000000000 )
|
Account State Difference:
Address | Before | After | State Difference | ||
---|---|---|---|---|---|
0x1E6C27E9...E419Ad4c6 |
0.052852176516621084 Eth
Nonce: 4
|
0.052059282341953884 Eth
Nonce: 5
| 0.0007928941746672 | ||
0xE9cB6838...8e9853C02 | |||||
0xEA674fdD...16B898ec8
Miner
| (Ethermine) | 262.308074737850146294 Eth | 262.308144903350146294 Eth | 0.0000701655 |
Execution Trace
StripToken.transfer( recipient=0x385dE61Fcedd62f8F573a84e46F2ee7c9F79916e, amount=25000000000000000000000000000 ) => ( True )
transfer[ERC20 (ln:251)]
_transfer[ERC20 (ln:252)]
_beforeTokenTransfer[ERC20 (ln:367)]
Transfer[ERC20 (ln:376)]
_afterTokenTransfer[ERC20 (ln:378)]
_msgSender[ERC20 (ln:252)]
File 1 of 2: StripToken
File 2 of 2: ERC20StakingPool
// Sources flattened with hardhat v2.5.0 https://hardhat.org // File @openzeppelin/contracts/token/ERC20/[email protected] // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, 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 `sender` to `recipient` 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 sender, address recipient, uint256 amount ) external returns (bool); /** * @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); } // File @openzeppelin/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @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); } // File @openzeppelin/contracts/utils/[email protected] 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; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of 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}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * 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 value {ERC20} uses, unless this function is * 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: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, 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}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), 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}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - 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) { _approve(_msgSender(), spender, _allowances[_msgSender()][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) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * 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: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, 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; _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; } _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 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 {} } // File @openzeppelin/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File @openzeppelin/contracts/utils/math/[email protected] pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File contracts/StripToken.sol /****************************************************************************** ██ ▒▓▓▒ ██ ▒▒ ██████ ██ ▒▓█▓ ████ ██████ █████ █ ████ ███ ████ █ █ ██ ██████▒ ▓███▒ █▒▒▒█▒ ▒██▒▒ ██▒▒▒█ █▒ █▒▒██ █▒ ▒█ █▒▒██ █▒ ██▒ ██▒ ▓██▓▒▒▓███▒ ██ ██▒ ██▒ █ █▒ █ ██▒ ██▒ █▒ ███▒ ██▒ ▒██████ ▒████▒ ██▒ █████▒ █▒ ████▒ ██▒ ██▒ █▒ █▒ ██▒█▒██▒ ▓█████ ▓█ ▒▒██▒ ██▒ ██▒▒██ █▒ ██▒ ██▒ ██▒ █▒ █▒ ██▒▒███▒ ███████ ██ ▒█ ██▒ ██▒ ██▒ █▒ █▒ ██▒ ▒██ █ ██▒ ██▒ █▒ ██▒ ▒██▒ ████████▓▓ █████▒ ██▒ ██▒ ██▒█▒ ██▒ ▒███▒ ████▒ █▒ ██▒ ▒█▒ ▒███████████▓▒▒ ▒▓█████████████▒ =================================================== ▓▓███████████▓ ██ ▒█████████▒ ██ ████████ Token..: STRIPCOIN ██ ▒███████▒ Version: 1.0 ██▒██████▒ License: MIT ██████▒ ▒████▒ ▓█████ ▒▓█▓▒ ▓█ ▒█▓▒ ██ ▒▓▒ ██ *******************************************************************************/ pragma solidity ^0.8.0; /** * @title StripToken Contract * @author * @dev */ contract StripToken is ERC20, Ownable { using SafeMath for uint256; // modify token name string public constant NAME = 'StripCoin'; // modify token symbol string public constant SYMBOL = 'STRIP'; // modify token decimals uint8 public constant DECIMALS = 18; // modify initial token supply uint256 public constant TOTAL_SUPPLY = 500e9 * (10**uint256(DECIMALS)); // 500,000,000,000 tokens // multisig contract address address public multiSigAdmin; event MultiSigAdminUpdated(address _multiSigAdmin); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor() Ownable() ERC20(NAME, SYMBOL) { _mint(msg.sender, TOTAL_SUPPLY); } /** * @dev Override decimals() function to customize decimals */ function decimals() public view virtual override returns (uint8) { return DECIMALS; } function setMultiSigAdminAddress(address _multiSigAdmin) external onlyOwner { require (_multiSigAdmin != address(0x00), "Invalid MultiSig admin address"); multiSigAdmin = _multiSigAdmin; emit MultiSigAdminUpdated(multiSigAdmin); } /** * @dev Recovers the ERC20 token balance mistakenly sent to the contract. Only multisig contract can call this function * @param tokenAddress The token contract address * @param tokenAmount Number of tokens to be sent */ function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyMultiSigAdmin { IERC20(tokenAddress).transfer(owner(), tokenAmount); } // modifier for multiSig only modifier onlyMultiSigAdmin() { require(msg.sender == multiSigAdmin, "Should be multiSig contract"); _; } }
File 2 of 2: ERC20StakingPool
// SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.4; import {Clone} from "Clone.sol"; import {ERC20} from "ERC20.sol"; import {SafeTransferLib} from "SafeTransferLib.sol"; import {Ownable} from "Ownable.sol"; import {FullMath} from "FullMath.sol"; /// @title ERC20StakingPool /// @author zefram.eth /// @notice A modern, gas optimized staking pool contract for rewarding ERC20 stakers /// with ERC20 tokens periodically and continuously contract ERC20StakingPool is Ownable, Clone { /// ----------------------------------------------------------------------- /// Library usage /// ----------------------------------------------------------------------- using SafeTransferLib for ERC20; /// ----------------------------------------------------------------------- /// Errors /// ----------------------------------------------------------------------- error Error_ZeroOwner(); error Error_AlreadyInitialized(); error Error_NotRewardDistributor(); error Error_AmountTooLarge(); /// ----------------------------------------------------------------------- /// Events /// ----------------------------------------------------------------------- event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); /// ----------------------------------------------------------------------- /// Constants /// ----------------------------------------------------------------------- uint256 internal constant PRECISION = 1e30; /// ----------------------------------------------------------------------- /// Storage variables /// ----------------------------------------------------------------------- /// @notice The last Unix timestamp (in seconds) when rewardPerTokenStored was updated uint64 public lastUpdateTime; /// @notice The Unix timestamp (in seconds) at which the current reward period ends uint64 public periodFinish; /// @notice The per-second rate at which rewardPerToken increases uint256 public rewardRate; /// @notice The last stored rewardPerToken value uint256 public rewardPerTokenStored; /// @notice The total tokens staked in the pool uint256 public totalSupply; /// @notice Tracks if an address can call notifyReward() mapping(address => bool) public isRewardDistributor; /// @notice The amount of tokens staked by an account mapping(address => uint256) public balanceOf; /// @notice The rewardPerToken value when an account last staked/withdrew/withdrew rewards mapping(address => uint256) public userRewardPerTokenPaid; /// @notice The earned() value when an account last staked/withdrew/withdrew rewards mapping(address => uint256) public rewards; /// ----------------------------------------------------------------------- /// Immutable parameters /// ----------------------------------------------------------------------- /// @notice The token being rewarded to stakers function rewardToken() public pure returns (ERC20 rewardToken_) { return ERC20(_getArgAddress(0)); } /// @notice The token being staked in the pool function stakeToken() public pure returns (ERC20 stakeToken_) { return ERC20(_getArgAddress(0x14)); } /// @notice The length of each reward period, in seconds function DURATION() public pure returns (uint64 DURATION_) { return _getArgUint64(0x28); } /// ----------------------------------------------------------------------- /// Initialization /// ----------------------------------------------------------------------- /// @notice Initializes the owner, called by StakingPoolFactory /// @param initialOwner The initial owner of the contract function initialize(address initialOwner) external { if (owner() != address(0)) { revert Error_AlreadyInitialized(); } if (initialOwner == address(0)) { revert Error_ZeroOwner(); } _transferOwnership(initialOwner); } /// ----------------------------------------------------------------------- /// User actions /// ----------------------------------------------------------------------- /// @notice Stakes tokens in the pool to earn rewards /// @param amount The amount of tokens to stake function stake(uint256 amount) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (amount == 0) { return; } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate ); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; rewards[msg.sender] = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // stake totalSupply = totalSupply_ + amount; balanceOf[msg.sender] = accountBalance + amount; /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- stakeToken().safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } /// @notice Withdraws staked tokens from the pool /// @param amount The amount of tokens to withdraw function withdraw(uint256 amount) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (amount == 0) { return; } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate ); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; rewards[msg.sender] = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // withdraw stake balanceOf[msg.sender] = accountBalance - amount; // total supply has 1:1 relationship with staked amounts // so can't ever underflow unchecked { totalSupply = totalSupply_ - amount; } /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- stakeToken().safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } /// @notice Withdraws all staked tokens and earned rewards function exit() external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate ); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // give rewards uint256 reward = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); if (reward > 0) { rewards[msg.sender] = 0; } // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // withdraw stake balanceOf[msg.sender] = 0; // total supply has 1:1 relationship with staked amounts // so can't ever underflow unchecked { totalSupply = totalSupply_ - accountBalance; } /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- // transfer stake stakeToken().safeTransfer(msg.sender, accountBalance); emit Withdrawn(msg.sender, accountBalance); // transfer rewards if (reward > 0) { rewardToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /// @notice Withdraws all earned rewards function getReward() external { /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 accountBalance = balanceOf[msg.sender]; uint64 lastTimeRewardApplicable_ = lastTimeRewardApplicable(); uint256 totalSupply_ = totalSupply; uint256 rewardPerToken_ = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate ); /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- uint256 reward = _earned( msg.sender, accountBalance, rewardPerToken_, rewards[msg.sender] ); // accrue rewards rewardPerTokenStored = rewardPerToken_; lastUpdateTime = lastTimeRewardApplicable_; userRewardPerTokenPaid[msg.sender] = rewardPerToken_; // withdraw rewards if (reward > 0) { rewards[msg.sender] = 0; /// ----------------------------------------------------------------------- /// Effects /// ----------------------------------------------------------------------- rewardToken().safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } /// ----------------------------------------------------------------------- /// Getters /// ----------------------------------------------------------------------- /// @notice The latest time at which stakers are earning rewards. function lastTimeRewardApplicable() public view returns (uint64) { return block.timestamp < periodFinish ? uint64(block.timestamp) : periodFinish; } /// @notice The amount of reward tokens each staked token has earned so far function rewardPerToken() external view returns (uint256) { return _rewardPerToken( totalSupply, lastTimeRewardApplicable(), rewardRate ); } /// @notice The amount of reward tokens an account has accrued so far. Does not /// include already withdrawn rewards. function earned(address account) external view returns (uint256) { return _earned( account, balanceOf[account], _rewardPerToken( totalSupply, lastTimeRewardApplicable(), rewardRate ), rewards[account] ); } /// ----------------------------------------------------------------------- /// Owner actions /// ----------------------------------------------------------------------- /// @notice Lets a reward distributor start a new reward period. The reward tokens must have already /// been transferred to this contract before calling this function. If it is called /// when a reward period is still active, a new reward period will begin from the time /// of calling this function, using the leftover rewards from the old reward period plus /// the newly sent rewards as the reward. /// @dev If the reward amount will cause an overflow when computing rewardPerToken, then /// this function will revert. /// @param reward The amount of reward tokens to use in the new reward period. function notifyRewardAmount(uint256 reward) external { /// ----------------------------------------------------------------------- /// Validation /// ----------------------------------------------------------------------- if (reward == 0) { return; } if (!isRewardDistributor[msg.sender]) { revert Error_NotRewardDistributor(); } /// ----------------------------------------------------------------------- /// Storage loads /// ----------------------------------------------------------------------- uint256 rewardRate_ = rewardRate; uint64 periodFinish_ = periodFinish; uint64 lastTimeRewardApplicable_ = block.timestamp < periodFinish_ ? uint64(block.timestamp) : periodFinish_; uint64 DURATION_ = DURATION(); uint256 totalSupply_ = totalSupply; /// ----------------------------------------------------------------------- /// State updates /// ----------------------------------------------------------------------- // accrue rewards rewardPerTokenStored = _rewardPerToken( totalSupply_, lastTimeRewardApplicable_, rewardRate_ ); lastUpdateTime = lastTimeRewardApplicable_; // record new reward uint256 newRewardRate; if (block.timestamp >= periodFinish_) { newRewardRate = reward / DURATION_; } else { uint256 remaining = periodFinish_ - block.timestamp; uint256 leftover = remaining * rewardRate_; newRewardRate = (reward + leftover) / DURATION_; } // prevent overflow when computing rewardPerToken if (newRewardRate >= ((type(uint256).max / PRECISION) / DURATION_)) { revert Error_AmountTooLarge(); } rewardRate = newRewardRate; lastUpdateTime = uint64(block.timestamp); periodFinish = uint64(block.timestamp + DURATION_); emit RewardAdded(reward); } /// @notice Lets the owner add/remove accounts from the list of reward distributors. /// Reward distributors can call notifyRewardAmount() /// @param rewardDistributor The account to add/remove /// @param isRewardDistributor_ True to add the account, false to remove the account function setRewardDistributor( address rewardDistributor, bool isRewardDistributor_ ) external onlyOwner { isRewardDistributor[rewardDistributor] = isRewardDistributor_; } /// ----------------------------------------------------------------------- /// Internal functions /// ----------------------------------------------------------------------- function _earned( address account, uint256 accountBalance, uint256 rewardPerToken_, uint256 accountRewards ) internal view returns (uint256) { return FullMath.mulDiv( accountBalance, rewardPerToken_ - userRewardPerTokenPaid[account], PRECISION ) + accountRewards; } function _rewardPerToken( uint256 totalSupply_, uint256 lastTimeRewardApplicable_, uint256 rewardRate_ ) internal view returns (uint256) { if (totalSupply_ == 0) { return rewardPerTokenStored; } return rewardPerTokenStored + FullMath.mulDiv( (lastTimeRewardApplicable_ - lastUpdateTime) * PRECISION, rewardRate_, totalSupply_ ); } function _getImmutableVariablesOffset() internal pure returns (uint256 offset) { assembly { offset := sub( calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2) ) } } } // SPDX-License-Identifier: BSD pragma solidity ^0.8.4; /// @title Clone /// @author zefram.eth /// @notice Provides helper functions for reading immutable args from calldata contract Clone { /// @notice Reads an immutable arg with type address /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgAddress(uint256 argOffset) internal pure returns (address arg) { uint256 offset = _getImmutableArgsOffset(); assembly { arg := shr(0x60, calldataload(add(offset, argOffset))) } } /// @notice Reads an immutable arg with type uint256 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint256(uint256 argOffset) internal pure returns (uint256 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := calldataload(add(offset, argOffset)) } } /// @notice Reads an immutable arg with type uint64 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint64(uint256 argOffset) internal pure returns (uint64 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0xc0, calldataload(add(offset, argOffset))) } } /// @notice Reads an immutable arg with type uint8 /// @param argOffset The offset of the arg in the packed data /// @return arg The arg value function _getArgUint8(uint256 argOffset) internal pure returns (uint8 arg) { uint256 offset = _getImmutableArgsOffset(); // solhint-disable-next-line no-inline-assembly assembly { arg := shr(0xf8, calldataload(add(offset, argOffset))) } } /// @return offset The offset of the packed immutable args in calldata function _getImmutableArgsOffset() internal pure returns (uint256 offset) { // solhint-disable-next-line no-inline-assembly assembly { offset := sub( calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2) ) } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {Clone} from "Clone.sol"; /// @notice Modern and gas efficient ERC20 + EIP-2612 implementation. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol) /// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol) /// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it. abstract contract ERC20 is Clone { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval( address indexed owner, address indexed spender, uint256 amount ); /*/////////////////////////////////////////////////////////////// ERC20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// METADATA //////////////////////////////////////////////////////////////*/ function name() external pure returns (string memory) { return string(abi.encodePacked(_getArgUint256(0))); } function symbol() external pure returns (string memory) { return string(abi.encodePacked(_getArgUint256(0x20))); } function decimals() external pure returns (uint8) { return _getArgUint8(0x40); } /*/////////////////////////////////////////////////////////////// ERC20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public virtual returns (bool) { balanceOf[msg.sender] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public virtual returns (bool) { uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals. if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount; balanceOf[from] -= amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// INTERNAL LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // Cannot overflow because the sum of all user // balances can't exceed the max uint256 value. unchecked { balanceOf[to] += amount; } emit Transfer(address(0), to, amount); } function _burn(address from, uint256 amount) internal virtual { balanceOf[from] -= amount; // Cannot underflow because a user's balance // will never be larger than the total supply. unchecked { totalSupply -= amount; } emit Transfer(from, address(0), amount); } function _getImmutableVariablesOffset() internal pure returns (uint256 offset) { assembly { offset := sub( calldatasize(), add(shr(240, calldataload(sub(calldatasize(), 2))), 2) ) } } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {ERC20} from "ERC20.sol"; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Gnosis (https://github.com/gnosis/gp-v2-contracts/blob/main/src/contracts/libraries/GPv2SafeERC20.sol) /// @dev Use with caution! Some functions in this library knowingly create dirty bits at the destination of the free memory pointer. /// @dev Note that none of the functions in this library check that a token has code at all! That responsibility is delegated to the caller. library SafeTransferLib { /*/////////////////////////////////////////////////////////////// ETH OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferETH(address to, uint256 amount) internal { bool callStatus; assembly { // Transfer the ETH and store if it succeeded or not. callStatus := call(gas(), to, amount, 0, 0, 0, 0) } require(callStatus, "ETH_TRANSFER_FAILED"); } /*/////////////////////////////////////////////////////////////// ERC20 OPERATIONS //////////////////////////////////////////////////////////////*/ function safeTransferFrom( ERC20 token, address from, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore( freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000 ) // Begin with the function selector. mstore( add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff) ) // Mask and append the "from" argument. mstore( add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff) ) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 68), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 100 because the calldata length is 4 + 32 * 3. callStatus := call(gas(), token, 0, freeMemoryPointer, 100, 0, 0) } require( didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FROM_FAILED" ); } function safeTransfer( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore( freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000 ) // Begin with the function selector. mstore( add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff) ) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require( didLastOptionalReturnCallSucceed(callStatus), "TRANSFER_FAILED" ); } function safeApprove( ERC20 token, address to, uint256 amount ) internal { bool callStatus; assembly { // Get a pointer to some free memory. let freeMemoryPointer := mload(0x40) // Write the abi-encoded calldata to memory piece by piece: mstore( freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000 ) // Begin with the function selector. mstore( add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff) ) // Mask and append the "to" argument. mstore(add(freeMemoryPointer, 36), amount) // Finally append the "amount" argument. No mask as it's a full 32 byte value. // Call the token and store if it succeeded or not. // We use 68 because the calldata length is 4 + 32 * 2. callStatus := call(gas(), token, 0, freeMemoryPointer, 68, 0, 0) } require(didLastOptionalReturnCallSucceed(callStatus), "APPROVE_FAILED"); } /*/////////////////////////////////////////////////////////////// INTERNAL HELPER LOGIC //////////////////////////////////////////////////////////////*/ function didLastOptionalReturnCallSucceed(bool callStatus) private pure returns (bool success) { assembly { // Get how many bytes the call returned. let returnDataSize := returndatasize() // If the call reverted: if iszero(callStatus) { // Copy the revert message into memory. returndatacopy(0, 0, returnDataSize) // Revert with the same message. revert(0, returnDataSize) } switch returnDataSize case 32 { // Copy the return data into memory. returndatacopy(0, 0, returnDataSize) // Set success to whether it returned true. success := iszero(iszero(mload(0))) } case 0 { // There was no return data. success := 1 } default { // It returned some malformed input. success := 0 } } } } // SPDX-License-Identifier: AGPL-3.0 pragma solidity ^0.8.4; abstract contract Ownable { error Ownable_NotOwner(); error Ownable_NewOwnerZeroAddress(); address private _owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @dev Returns the address of the current owner. function owner() public view virtual returns (address) { return _owner; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { if (owner() != msg.sender) revert Ownable_NotOwner(); _; } /// @dev Transfers ownership of the contract to a new account (`newOwner`). /// Can only be called by the current owner. function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress(); _transferOwnership(newOwner); } /// @dev Transfers ownership of the contract to a new account (`newOwner`). /// Internal function without access restriction. function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity >=0.8.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = (type(uint256).max - denominator + 1) & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); unchecked { if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } }